You are here

public function FacebookAuthController::returnFromFb in Social Auth Facebook 8

Response for path 'user/login/facebook/callback'.

Facebook returns the user here after user has authenticated in FB.

1 string reference to 'FacebookAuthController::returnFromFb'
social_auth_facebook.routing.yml in ./social_auth_facebook.routing.yml
social_auth_facebook.routing.yml

File

src/Controller/FacebookAuthController.php, line 131

Class

FacebookAuthController
Returns responses for Simple FB Connect module routes.

Namespace

Drupal\social_auth_facebook\Controller

Code

public function returnFromFb() {

  // Checks if user cancel login via Facebook.
  $error = $this->request
    ->getCurrentRequest()
    ->get('error');
  if ($error == 'access_denied') {
    drupal_set_message($this
      ->t('You could not be authenticated.'), 'error');
    return $this
      ->redirect('user.login');
  }

  /* @var \Facebook\Facebook|false $facebook */
  $facebook = $this->networkManager
    ->createInstance('social_auth_facebook')
    ->getSdk();

  // If facebook client could not be obtained.
  if (!$facebook) {
    drupal_set_message($this
      ->t('Social Auth Facebook not configured properly. Contact site administrator.'), 'error');
    return $this
      ->redirect('user.login');
  }
  $this->facebookManager
    ->setClient($facebook)
    ->authenticate();

  // Checks that user authorized our app to access user's email address.
  if (!$this->facebookManager
    ->checkPermission('email')) {
    drupal_set_message($this
      ->t('Facebook login failed. This site requires permission to get your email address from Facebook. Please try again.'), 'error');
    $this->persistentDataHandler
      ->set('reprompt', TRUE);
    return $this
      ->redirect('user.login');
  }

  // Gets user's FB profile from Facebook API.
  if (!($fb_profile = $this->facebookManager
    ->getUserInfo())) {
    drupal_set_message($this
      ->t('Facebook login failed, could not load Facebook profile. Contact site administrator.'), 'error');
    return $this
      ->redirect('user.login');
  }

  // Gets user's email from the FB profile.
  if (!($email = $this->facebookManager
    ->getEmail($fb_profile))) {
    drupal_set_message($this
      ->t('Facebook login failed. This site requires permission to get your email address.'), 'error');
    return $this
      ->redirect('user.login');
  }

  // Saves access token to session so that event subscribers can call FB API.
  $this->persistentDataHandler
    ->set('access_token', $this->facebookManager
    ->getAccessToken());

  // If user information could be retrieved.
  return $this->userManager
    ->authenticateUser($email, $fb_profile
    ->getField('name'), $fb_profile
    ->getField('id'), $this->facebookManager
    ->getFbProfilePicUrl());
}