/** * Grants access token for request * * @param IRequest $request * * @throws \OAuth2\Exception\InvalidGrantException * @throws \OAuth2\Exception\InvalidRequestException * @throws \OAuth2\Exception\InvalidScopeException * @throws \OAuth2\Exception\UnauthorizedClientException * @return IAccessToken */ public function grant(IRequest $request) { $username = $request->request('username'); $password = $request->request('password'); if (empty($username) || empty($password)) { throw new InvalidRequestException('Username and password are required.'); } $client = $this->clientAuthenticator->authenticate($request); if (!$client->isAllowedToUse($this)) { throw new UnauthorizedClientException('Client can not use this grant type.'); } $user = $this->userAuthenticator->authenticate($username, $password); if (!$user) { throw new InvalidUserCredentialsException('Invalid user credentials.'); } $requestedScopes = $request->request('scope'); $availableScopes = $user->getScopes(); if (empty($availableScopes)) { $availableScopes = $this->scopeResolver->getDefaultScopes(); } if (empty($availableScopes)) { throw new InvalidScopeException('Scope parameter has to be specified.'); } // intersection of requested and user scopes $scopes = $this->scopeResolver->intersect($requestedScopes, $availableScopes); return $this->accessTokenStorage->generate($user, $client, $scopes); }
function it_issues_an_access_token_using_default_scopes(IRequest $request, IClientAuthenticator $clientAuthenticator, IUserAuthenticator $userAuthenticator, IScopeResolver $scopeResolver, IUser $user, IClient $client, IScope $scope, IAccessTokenStorage $accessTokenStorage, IAccessToken $accessToken) { $request->request('username')->willReturn('root')->shouldBeCalled(); $request->request('password')->willReturn('p')->shouldBeCalled(); $clientAuthenticator->authenticate($request)->willReturn($client)->shouldBeCalled(); $client->isAllowedToUse($this)->willReturn(true)->shouldBeCalled(); $userAuthenticator->authenticate('root', 'p')->willReturn($user)->shouldBeCalled(); $request->request('scope')->willReturn(null)->shouldBeCalled(); $user->getScopes()->willReturn([])->shouldBeCalled(); $scopeResolver->getDefaultScopes()->willReturn([$scope])->shouldBeCalled(); $scopeResolver->intersect(null, [$scope])->willReturn([$scope])->shouldBeCalled(); $accessTokenStorage->generate($user, $client, [$scope])->willReturn($accessToken)->shouldBeCalled(); $this->grant($request)->shouldReturn($accessToken); }