GoogleAuthController.php in Social Auth Google 8
File
src/Controller/GoogleAuthController.php
View source
<?php
namespace Drupal\social_auth_google\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\social_auth_google\GoogleAuthManager;
use Drupal\social_api\Plugin\NetworkManager;
use Drupal\social_auth\SocialAuthUserManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Zend\Diactoros\Response\RedirectResponse;
class GoogleAuthController extends ControllerBase {
protected $networkManager;
protected $googleManager;
protected $userManager;
protected $session;
public function __construct(NetworkManager $network_manager, SocialAuthUserManager $user_manager, GoogleAuthManager $google_manager, SessionInterface $session) {
$this->networkManager = $network_manager;
$this->userManager = $user_manager;
$this->googleManager = $google_manager;
$this->session = $session;
$this->userManager
->setPluginId('social_auth_google');
$this->userManager
->setSessionKeysToNullify([
'social_auth_google_access_token',
]);
}
public static function create(ContainerInterface $container) {
return new static($container
->get('plugin.network.manager'), $container
->get('social_auth.user_manager'), $container
->get('social_auth_google.manager'), $container
->get('session'));
}
public function redirectToGoogle() {
$client = $this->networkManager
->createInstance('social_auth_google')
->getSdk();
$client
->setScopes([
'email',
'profile',
]);
return new RedirectResponse($client
->createAuthUrl());
}
public function callback() {
$client = $this->networkManager
->createInstance('social_auth_google')
->getSdk();
$this->googleManager
->setClient($client)
->authenticate();
$this->session
->set('social_auth_google_access_token', $this->googleManager
->getAccessToken());
$user = $this->googleManager
->getUserInfo();
if ($user) {
return $this->userManager
->authenticateUser($user
->getEmail(), $user
->getName(), $user
->getId(), $user
->getPicture());
}
drupal_set_message($this
->t('You could not be authenticated, please contact the administrator'), 'error');
return $this
->redirect('user.login');
}
}