You are here

public function OAuth2DrupalAuthProvider::authenticate in OAuth2 Server 8

Same name and namespace in other branches
  1. 2.0.x src/Authentication/Provider/OAuth2DrupalAuthProvider.php \Drupal\oauth2_server\Authentication\Provider\OAuth2DrupalAuthProvider::authenticate()

Authenticates the user.

Parameters

\Symfony\Component\HttpFoundation\Request|null $request: The request object.

Return value

\Drupal\Core\Session\AccountInterface|null AccountInterface - in case of a successful authentication. NULL - in case where authentication failed.

Overrides AuthenticationProviderInterface::authenticate

File

src/Authentication/Provider/OAuth2DrupalAuthProvider.php, line 141

Class

OAuth2DrupalAuthProvider
OAuth2 Drupal Auth Provider.

Namespace

Drupal\oauth2_server\Authentication\Provider

Code

public function authenticate(Request $request) {
  try {
    if (!empty($request->headers
      ->get('authorization'))) {
      $token = $this
        ->getInfoToken($request->headers
        ->get('authorization'), 'token');
    }
    if (!empty($request
      ->get('access_token'))) {
      $token = $request
        ->get('access_token');
    }

    // Determine if $token is empty.
    if (empty($token)) {
      throw new \InvalidArgumentException("The client has not transmitted the token in the request.");
    }

    // Retrieve access token data.
    $info = $this->storage
      ->getAccessToken($token);
    if (empty($info)) {
      throw new \InvalidArgumentException("The token: " . $token . " provided is not registered.");
    }

    // Determine if $info['server'] is empty.
    if (empty($info['server'])) {
      throw new \Exception("OAuth2 server was not set");
    }

    // Set $oauth2_server_name.
    $oauth2_server_name = 'oauth2_server.server.' . $info['server'];

    // Retrieves the configuration object.
    $config = $this->configFactory
      ->get($oauth2_server_name);

    // Determine if $config is empty.
    if (empty($config)) {
      throw new \Exception("The config for '.{$oauth2_server_name}.' server could not be loaded.");
    }
    $oauth2_server_settings = $config
      ->get('settings');
    if (empty($oauth2_server_settings['advanced_settings']) || empty($oauth2_server_settings['advanced_settings']['access_lifetime'])) {
      throw new \Exception("The access_lifetime was not set.");
    }
    if ($this->time
      ->getRequestTime() > $info['expires'] + $oauth2_server_settings['advanced_settings']['access_lifetime']) {
      throw new \Exception("The token is expired.");
    }
    return $this->entityTypeManager
      ->getStorage('user')
      ->load($info['user_id']);
  } catch (\Exception $e) {
    $this->loggerFactory
      ->get('access denied')
      ->warning($e
      ->getMessage());
    throw new AccessDeniedHttpException($e
      ->getMessage(), $e);
  }
}