Advertisement
AVONnadozie

Using Facebook SDK for user authentication

Dec 9th, 2015
562
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 5.48 KB | None | 0 0
  1. <?php
  2. //NOTE: This code wasn't tested but it should work fine since i almost copied and pasted everything from my previous work i've tested
  3. //Hope it guides you well enough.
  4. //
  5. //Defining some constants i need, replace with yours
  6. define('HOSTNAME', 'http://localhost/sample');
  7. define('CURRENT_PAGE', HOSTNAME . '/my_login_page.php');
  8.  
  9.  
  10. //THEN HERE WE GO!
  11. //
  12. //
  13. //Step 1
  14. //Create a Facebook APP on Facebook developer page
  15. //Make it public and copy your APP ID and APP SECRET
  16. //Add your HOSTNAME to the urls allowed to access the app
  17. //Download facebook sdk and extract to current folder
  18. //You can browse how to make it public and how to add urls if you don get it at first hand, can't remember the steps right now
  19. //Step 2
  20. //Start session, Facebook API needs it and you might need it too.
  21. //It might be important you understand how PHP session works
  22. session_start();
  23.  
  24. //load Facebook api
  25. require_once __DIR__ . '/path-to-downloaded-sdk/src/Facebook/autoload.php';
  26.  
  27. //Create Facebook object
  28. $fb = new Facebook\Facebook([
  29.     'app_id' => 'YOUR_APP_ID',
  30.     'app_secret' => 'YOUR_APP_SECRET',
  31.     'default_graph_version' => 'v2.2',
  32.         ]);
  33. //you'll need to repeat Step 2 on any other you have to use this Facebook API
  34. //
  35. //
  36. //Step 3
  37. //Assuming this is the same page you want facebook to redirect user after authentication
  38. //Check if this was a redirect from facebook
  39. //Am using the 'token' variable to identify a request uniquely, so its what i check for.
  40. //If the 'token' variable exists in the $_GET then i know its from Facebook and the user has visited this page before
  41. //I also made a copy of the token in the $_SESSION to match with the one from Facebook to be sure the user is not trying to bypass this step
  42.  
  43. if (isset($_GET['token']) and isset($_SESSION['token'])) {
  44.     //This is a redirect from Facebook
  45.     //Compare tokens to avoid unauthorized user access
  46.     if ($_GET['token'] === $_SESSION['token']) {
  47.  
  48.         $helper = $fb->getRedirectLoginHelper();
  49.         try {
  50.             $accessToken = $helper->getAccessToken();
  51.             if (isset($accessToken)) {
  52.                 //User logged in and was sucessfully authenticated!
  53.                 //Save accessToken wherever you like, am saving to session
  54.                 //This access token is what you use to extract the info you requested for about this user from facebook,
  55.                 //as far the session created by facebook api allows you, you can reuse the accessToken anywhere
  56.                 $_SESSION['facebook_access_token'] = (string) $accessToken;
  57.  
  58.                 //Extracting info
  59.                 // Sets the default fallback access token so we don't have to pass it to each request
  60.                 $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
  61.                 try {
  62.                     //Get fields you need
  63.                     $response = $fb->get('/me?fields=id,first_name,last_name,picture,email');
  64.                     $userNode = $response->getGraphUser();
  65.  
  66.                     $array = array();
  67.                     $array['id'] = $userNode->getId();
  68.                     $array['first_name'] = $userNode->getFirstName();
  69.                     $array['last_name'] = $userNode->getLastName();
  70.                     $pic = $userNode->getPicture();
  71.                     if (!empty($pic)) {
  72.                         $array['pic_url'] = $pic->getUrl();
  73.                     }
  74.                     $array['email'] = $userNode->getEmail();
  75.  
  76.                     //Now you have the information you want
  77.                     //You might want to save them to database now then redirect the user to his profile or wherever
  78.                     //And were done!!!!! phew!!
  79.                 } catch (Facebook\Exceptions\FacebookResponseException $e) {
  80.                     // When Graph returns an error
  81.                     $error = 'Graph returned an error: ' . $e->getMessage();
  82.                 } catch (Facebook\Exceptions\FacebookSDKException $e) {
  83.                     // When validation fails or other local issues
  84.                     $error = 'Facebook SDK returned an error: ' . $e->getMessage();
  85.                 }
  86.             }
  87.         } catch (Facebook\Exceptions\FacebookResponseException $e) {
  88.             // When Graph returns an error
  89.             $error = 'Graph returned an error: ' . $e->getMessage();
  90.         } catch (Facebook\Exceptions\FacebookSDKException $e) {
  91.             // When validation fails or other local issues
  92.             $error = 'Facebook SDK returned an error: ' . $e->getMessage();
  93.         }
  94.     } else {
  95.         //User may have tried to bypass authenticaton
  96.         //Do something and show him who's Boss :)
  97.         //Erm.. It's best to just notify him authentication failed
  98.     }
  99. } else {
  100.     //This is probably User's first visit and not from Facebook
  101.  
  102.     $helper = $fb->getRedirectLoginHelper();
  103.     $permissions = ['email', 'user_likes']; // optional, check developer page for more permissions you might need
  104.     //Generate token for unique identification of request
  105.     $token = md5(uniqid());
  106.     //token saved to session
  107.     $_SESSION['token'] = $token;
  108.  
  109.     //Generate login url, this url redirects the user to facebook and does all the authentication
  110.     $loginUrl = $helper->getLoginUrl(CURRENT_PAGE . "?token=$token", $permissions);
  111. }
  112. ?>
  113.  
  114. <?php
  115. if (isset($error)) {
  116.     echo $error;
  117. }
  118. ?>
  119. <div style="padding: 20px 20px 20px 20px; text-align: center">
  120.     <a href="<?= $loginUrl ?>" style="padding: 5px 5px 5px 5px; background: blue;">Log in with Facebook</a>
  121. </div>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement