You are here

public function AccessTokenIssue::issue in Simple OAuth (OAuth2) & OpenID Connect 8

1 string reference to 'AccessTokenIssue::issue'
simple_oauth.routing.yml in ./simple_oauth.routing.yml
simple_oauth.routing.yml

File

src/Controller/AccessTokenIssue.php, line 54

Class

AccessTokenIssue

Namespace

Drupal\simple_oauth\Controller

Code

public function issue(Request $request) {
  $body = Json::decode($request
    ->getContent());
  if (!$body['grant_type'] == 'password') {
    throw new HttpException(422, 'Only grant_type=password is supported');
  }
  $scope = 'global';
  if (!empty($body['scope'])) {
    $scope = $body['scope'];
    $resource = $this->entityManager
      ->getStorage('access_token_resource')
      ->load($scope);
    if (!$resource) {
      throw new HttpException(422, sprintf('Unknown scope %s', $scope));
    }
  }
  $uid = $this->userAuth
    ->authenticate($body['username'], $body['password']);

  /** @var \Drupal\user\UserInterface $user */
  $user = $this->entityManager
    ->getStorage('user')
    ->load($uid);
  if (!$user || $user
    ->isBlocked()) {
    throw new HttpException(401, 'Authentication failed.');
  }
  $values = [
    'expire' => AccessToken::defaultExpiration(),
    'user_id' => $uid,
    'auth_user_id' => $uid,
    'resource' => $scope,
  ];
  $store = $this->entityManager
    ->getStorage('access_token');

  /** @var \Drupal\simple_oauth\Entity\AccessToken $token */
  $token = $store
    ->create($values);
  $token
    ->save();
  $this->response
    ->setData($this
    ->normalize($token));
  return $this->response;
}