You are here

public function Storage::getAuthorizationCode in OAuth2 Server 7

File

lib/Drupal/oauth2_server/Storage.php, line 163

Class

Storage
Provides Drupal storage (through the underlying Entity API) for the library.

Namespace

Drupal\oauth2_server

Code

public function getAuthorizationCode($code) {
  $code = oauth2_server_authorization_code_load($code);
  if ($code) {
    $code_wrapper = entity_metadata_wrapper('oauth2_server_authorization_code', $code);
    $scopes = array();
    foreach ($code_wrapper->scopes as $scope_wrapper) {
      $scopes[] = $scope_wrapper->name
        ->value();
    }

    // Return a code array in the format expected by the library.
    $code = array(
      'server' => $code_wrapper->client->server
        ->raw(),
      'client_id' => $code_wrapper->client->client_key
        ->value(),
      'user_id' => $code_wrapper->user->uid
        ->value(),
      'authorization_code' => $code_wrapper->code
        ->value(),
      'redirect_uri' => $code_wrapper->redirect_uri
        ->value(),
      'expires' => (int) $code_wrapper->expires
        ->value(),
      'scope' => implode(' ', $scopes),
      'id_token' => $code_wrapper->id_token
        ->value(),
    );
    if (module_exists('uuid')) {
      $code['user_uuid'] = $code_wrapper->user->uuid
        ->value();
    }

    // Examine the id_token and alter the OpenID Connect 'sub' property if
    // necessary. The 'sub' 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 = variable_get('oauth2_server_user_sub_property', 'uid');
    if (!empty($code['id_token']) && $sub_property != 'uid') {
      $account = $code_wrapper->user
        ->value();
      $desired_sub = $account->{$sub_property};
      $parts = explode('.', $code['id_token']);
      $claims = json_decode(oauth2_server_base64url_decode($parts[1]), TRUE);
      if (isset($claims['sub']) && $desired_sub != $claims['sub']) {
        $claims['sub'] = $desired_sub;
        $parts[1] = oauth2_server_base64url_encode(json_encode($claims));
        $code['id_token'] = implode('.', $parts);
      }
    }
  }
  return $code;
}