social_auth_vipps-8.x-2.1/src/VippsAuthManager.php
src/VippsAuthManager.php
<?php
namespace Drupal\social_auth_vipps;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\social_auth\AuthManager\OAuth2Manager;
use League\OAuth2\Client\Provider\Exception\IdentityProviderException;
use League\OAuth2\Client\Token\AccessToken;
/**
* Contains all the logic for Vipps OAuth2 authentication.
*/
class VippsAuthManager extends OAuth2Manager {
/**
* Constructor.
*
* @param \Drupal\Core\Config\ConfigFactory $configFactory
* Used for accessing configuration object factory.
* @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
* The logger factory.
*/
public function __construct(ConfigFactory $configFactory, LoggerChannelFactoryInterface $logger_factory) {
parent::__construct($configFactory->get('social_auth_vipps.settings'), $logger_factory);
}
/**
* {@inheritdoc}
*/
public function authenticate() {
try {
$this->setAccessToken($this->client->getAccessToken('authorization_code',
['code' => \Drupal::request()->query->get('code')]));
}
catch (IdentityProviderException $e) {
$this->loggerFactory->get('social_auth_vipps')
->error('Unable to retrieve access token with error message: %message, code: %code, and response body: %response.', [
'%message' => $e->getMessage(),
'%code' => $e->getCode(),
'%response' => $e->getResponseBody(),
]);
}
}
/**
* {@inheritdoc}
*/
public function getUserInfo() {
if (!$this->user) {
$access_token = $this->getAccessToken();
$this->user = $access_token instanceof AccessToken
? $this->client->getResourceOwner($access_token)
: NULL;
}
return $this->user;
}
/**
* {@inheritdoc}
*/
public function getAuthorizationUrl() {
$scopes = [
'openid',
'address',
'email',
'name',
'phoneNumber',
];
$extra_scopes = $this->getScopes();
if ($extra_scopes) {
$scopes = array_merge($scopes, explode(',', $extra_scopes));
}
// Returns the URL where user will be redirected.
return $this->client->getAuthorizationUrl([
'scope' => $scopes,
'requested_flow' => 'automatic_return_from_vipps_app',
]);
}
/**
* {@inheritdoc}
*/
public function requestEndPoint($method, $path, $domain = NULL, array $options = []) {
if (!$domain) {
$domain = 'https://api.vipps.no';
}
$url = $domain . $path;
$request = $this->client->getAuthenticatedRequest($method, $url, $this->getAccessToken(), $options);
try {
return $this->client->getParsedResponse($request);
}
catch (IdentityProviderException $e) {
$this->loggerFactory->get('social_auth_vipps')
->error('There was an error when requesting ' . $url . '. Exception: ' . $e->getMessage());
}
return NULL;
}
/**
* {@inheritdoc}
*/
public function getState() {
return $this->client->getState();
}
}
