I was given a tech test for a prospective job a small game that uses Facebook API to connect a user then to guess the image. The feedback from the employer was good but they said they had to modify part of my code to get the API connection working even though the demo app works fine. This has caused them to lower the offered salary.
The company works a lot with Facebook APIs and other social media APIs so it was an important part, I personally can't see much wrong with the code apart from using native PHP sessions rather than trying to use Yii frameworks sessions.
Could people tell me of any errors in the code for connecting with Facebook as well as any general improvements?
<?php
namespace app\models;
use Yii;
use yii\base\Model;
use Facebook\FacebookSession;
use Facebook\FacebookRequest;
use Facebook\FacebookRedirectLoginHelper;
class fbConnector extends Model
{
function __construct() {
session_start();
}
/**
* fbLogin()
* Logs in user through facebook API && creates a user record in database
* or retrieves an existing user record after logging in
*
* @return bool|string
*/
public function fbLogin()
{
//get the facebook app credentials
$app_id = configParams('app_id');
$app_secret = configParams('app_secret');
$app_redirect_uri = configParams('redirect_url');
// Requested permissions
$permissions = array(
'public_profile',
'email'
);
//init the FB SDK
FacebookSession::setDefaultApplication($app_id, $app_secret);
$helper = new FacebookRedirectLoginHelper($app_redirect_uri);
//see if a existing session exists
if (isset($_SESSION) && isset($_SESSION['fb_token'])) {
// create new session from saved access_token
$session = new FacebookSession($_SESSION['fb_token']);
//validate the access_token to make sure it's still valid
try{
if (!$session->validate()) {
$session = null;
}
}catch (Exception $e){
// catch any exceptions
$session = null;
}
}
if (!isset($session) || $session === null) {
try{
$session = $helper->getSessionFromRedirect();
}catch (FacebookRequestException $ex){
//When Facebook returns an error
Yii::$app->user->setFlash('error', "Facebook returned an error when logging in, try again !!!");
//log to file
Yii::info($ex, 'facebookConnectErrors');
return false;
}catch (Exception $ex){
//When validation fails or other local issues
Yii::$app->user->setFlash(
'error',
"Ooh something didn't work there a highly trained monkey has been sent to investigate"
);
//log to file
Yii::info($ex, 'facebookConnectErrors');
return false;
}
}
//see if we have a session
if (isset($session)) {
//save the session
$_SESSION['fb_token'] = $session->getToken();
//create a session using saved token or the new one we generated at login
$session = new FacebookSession($session->getToken());
//graph api request for user data
$request = new FacebookRequest($session, 'GET', '/me');
//execute our request
$response = $request->execute();
//get response
$graphObject = $response->getGraphObject()->asArray();
//check our object exists
if ($graphObject != null) {
//if it exists check if we have usr in db
$user = (new \yii\db\Query())->select(['fb_uid', 'uid'])->from('tb_user')->where(
['fb_uid' => $graphObject['id']]
)->all();
//if query returns null insert them to db
if ($user == null) {
$command = Yii::$app->db->createCommand();
$command->insert(
'tb_user',
array(
'first_name' => $graphObject['first_name'],
'last_name' => $graphObject['last_name'],
'email' => $graphObject['email'],
'fb_uid' => $graphObject['id'],
'dob' => $graphObject['birthday']
)
)->execute();
//check usr was inserted correctly
$uid = Yii::$app->db->lastInsertID;
if ($uid != null) {
//add uid to session for later
$_SESSION['uid'] = $uid;
//add user details to session for later
$_SESSION['first_name'] = $graphObject['first_name'];
$_SESSION['last_name'] = $graphObject['last_name'];
$_SESSION['email'] = $graphObject['email'];
//send a positive bool back so app can continue
return true;
}else {
//havent been able to insert the user but we need to so return error with flash message
$user['error_msg'] = 'Not been able to insert this user';
Yii::info($user);
Yii::$app->user->setFlash('error', "Unable to create your account. Please try again!!!");
return false;
}
}else {
//add uid to session for later
$_SESSION['uid'] = $user[0]['uid'];
//add user details to session for later
$_SESSION['first_name'] = $graphObject['first_name'];
$_SESSION['last_name'] = $graphObject['last_name'];
$_SESSION['email'] = $graphObject['email'];
//user already exists so continue
return true;
}
}else {
//not returning a proper $graphObject
Yii::$app->user->setFlash('error', "Something went wrong at facebook try again.");
return false;
}
}else {
//pass login link back to controller
$login_url = $helper->getLoginUrl($permissions);
return $login_url;
}
}
}
-
\$\begingroup\$ Also, if you're looking for actual mistakes regarding the Facebook API you would also be better off asking that specific question on Stackoverflow. \$\endgroup\$ferada– ferada2015年06月23日 14:46:17 +00:00Commented Jun 23, 2015 at 14:46
-
1\$\begingroup\$ There is no mistakes in the php execution is the code connects the user via the api and stores them in the db as per the requirements, but there devs seem to think there was general errors in the code and how it was approached which i dont see personally hence asking for comment and review on it \$\endgroup\$James Kirkby– James Kirkby2015年06月23日 16:24:08 +00:00Commented Jun 23, 2015 at 16:24