LinkedinAuthController.php in Social Auth LinkedIn 8
File
src/Controller/LinkedinAuthController.php
View source
<?php
namespace Drupal\social_auth_linkedin\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\social_auth_linkedin\LinkedinAuthManager;
use Drupal\social_api\Plugin\NetworkManager;
use Drupal\social_auth\SocialAuthUserManager;
use LinkedIn\LinkedIn;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Zend\Diactoros\Response\RedirectResponse;
class LinkedinAuthController extends ControllerBase {
public $request;
protected $networkManager;
protected $linkedinManager;
protected $userManager;
protected $session;
public function __construct(NetworkManager $network_manager, SocialAuthUserManager $user_manager, LinkedinAuthManager $linkedin_manager, RequestStack $request, SessionInterface $session) {
$this->request = $request;
$this->networkManager = $network_manager;
$this->userManager = $user_manager;
$this->linkedinManager = $linkedin_manager;
$this->session = $session;
$this->userManager
->setPluginId('social_auth_linkedin');
$this->userManager
->setSessionKeysToNullify([
'social_auth_linkedin_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_linkedin.manager'), $container
->get('request_stack'), $container
->get('session'));
}
public function redirectToLinkedin() {
$client = $this->networkManager
->createInstance('social_auth_linkedin')
->getSdk();
$url = $client
->getLoginUrl([
LinkedIn::SCOPE_BASIC_PROFILE,
LinkedIn::SCOPE_EMAIL_ADDRESS,
]);
return new RedirectResponse($url);
}
public function callback() {
$error = $this->request
->getCurrentRequest()
->get('error');
if ($error) {
drupal_set_message($this
->t('You could not be authenticated.'), 'error');
return $this
->redirect('user.login');
}
$client = $this->networkManager
->createInstance('social_auth_linkedin')
->getSdk();
$this->linkedinManager
->setClient($client)
->authenticate();
$this->session
->set('social_auth_linkedin_access_token', $this->linkedinManager
->getAccessToken());
$user = $this->linkedinManager
->getUserInfo();
if ($user) {
$picture = isset($user['pictureUrls']['values'][0]) ? $user['pictureUrls']['values'][0] : FALSE;
$fullname = $user['firstName'] . ' ' . $user['lastName'];
return $this->userManager
->authenticateUser($user['emailAddress'], $fullname, $user['id'], $picture);
}
drupal_set_message($this
->t('You could not be authenticated, please contact the administrator'), 'error');
return $this
->redirect('user.login');
}
}