You are here

public function OAuth2Storage::getUserClaims in OAuth2 Server 8

Same name and namespace in other branches
  1. 2.0.x src/OAuth2Storage.php \Drupal\oauth2_server\OAuth2Storage::getUserClaims()

Get user claims.

Parameters

int $uid: The user id integer.

string $scope: The scope string.

Return value

array An associative array of claim strings.

Throws

\Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException

\Drupal\Component\Plugin\Exception\PluginNotFoundException

\Drupal\Core\Entity\EntityMalformedException

File

src/OAuth2Storage.php, line 735

Class

OAuth2Storage
Provides Drupal OAuth2 storage for the library.

Namespace

Drupal\oauth2_server

Code

public function getUserClaims($uid, $scope) {

  /** @var \Drupal\user\UserInterface $account */
  $account = $this->entityTypeManager
    ->getStorage('user')
    ->load($uid);
  if (!$account) {
    throw new \InvalidArgumentException("The supplied user couldn't be loaded.");
  }
  $requested_scopes = explode(' ', trim($scope));

  // The OpenID Connect 'sub' (Subject Identifier) property is usually the
  // user's UID, but this is configurable for backwards compatibility reasons.
  // See: https://www.drupal.org/node/2274357#comment-9779467
  $sub_property = $this->configFactory
    ->get('oauth2_server.oauth')
    ->get('user_sub_property');

  // Prepare the default claims.
  $claims = [
    'sub' => $account->{$sub_property}->value,
  ];
  if (in_array('email', $requested_scopes)) {
    $claims['email'] = $account
      ->getEmail();
    $claims['email_verified'] = $this->configFactory
      ->get('user.settings')
      ->get('verify_mail');
  }
  if (in_array('profile', $requested_scopes)) {
    if (!empty($account
      ->label())) {
      $claims['name'] = $account
        ->getDisplayName();
      $claims['preferred_username'] = $account
        ->getAccountName();
    }
    if (!empty($account->timezone)) {
      $claims['zoneinfo'] = $account
        ->getTimeZone();
    }
    $anonymous_user = new AnonymousUserSession();
    if ($anonymous_user
      ->hasPermission('access user profiles')) {
      $claims['profile'] = $account
        ->toUrl('canonical', [
        'absolute' => TRUE,
      ]);
    }
    if ($picture = $this
      ->getUserPicture($account)) {
      $claims['picture'] = $picture;
    }
  }

  // Allow modules to supply additional claims.
  $claims += $this->moduleHandler
    ->invokeAll('oauth2_server_user_claims', [
    'account' => $account,
    'requested_scopes' => $requested_scopes,
  ]);

  // Finally, allow modules to alter claims.
  $context = [
    'claims' => &$claims,
    'account' => $account,
    'requested_scopes' => $requested_scopes,
  ];
  $this->moduleHandler
    ->alter('oauth2_server_user_claims', $context);
  return $claims;
}