Completed
Pull Request — master (#1035)
by Matt
03:17
created

PasswordGrant   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 94
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 97.22%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 8
dl 0
loc 94
rs 10
c 0
b 0
f 0
ccs 35
cts 36
cp 0.9722

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
A getIdentifier() 0 4 1
A respondToAccessTokenRequest() 0 28 2
A validateUser() 0 29 4
1
<?php
2
/**
3
 * OAuth 2.0 Password grant.
4
 *
5
 * @author      Alex Bilbie <[email protected]>
6
 * @copyright   Copyright (c) Alex Bilbie
7
 * @license     http://mit-license.org/
8
 *
9
 * @link        https://github.com/thephpleague/oauth2-server
10
 */
11
12
namespace League\OAuth2\Server\Grant;
13
14
use DateInterval;
15
use League\OAuth2\Server\Entities\ClientEntityInterface;
16
use League\OAuth2\Server\Entities\UserEntityInterface;
17
use League\OAuth2\Server\Exception\OAuthServerException;
18
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
19
use League\OAuth2\Server\Repositories\UserRepositoryInterface;
20
use League\OAuth2\Server\RequestEvent;
21
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
22
use Psr\Http\Message\ServerRequestInterface;
23
24
/**
25
 * Password grant class.
26
 */
27
class PasswordGrant extends AbstractGrant
28
{
29
    /**
30
     * @param UserRepositoryInterface         $userRepository
31
     * @param RefreshTokenRepositoryInterface $refreshTokenRepository
32
     */
33 6
    public function __construct(
34
        UserRepositoryInterface $userRepository,
35
        RefreshTokenRepositoryInterface $refreshTokenRepository
36
    ) {
37 6
        $this->setUserRepository($userRepository);
38 6
        $this->setRefreshTokenRepository($refreshTokenRepository);
39
40 6
        $this->refreshTokenTTL = new DateInterval('P1M');
41 6
    }
42
43
    /**
44
     * {@inheritdoc}
45
     */
46 5
    public function respondToAccessTokenRequest(
47
        ServerRequestInterface $request,
48
        ResponseTypeInterface $responseType,
49
        DateInterval $accessTokenTTL
50
    ) {
51
        // Validate request
52 5
        $client = $this->validateClient($request);
53 4
        $scopes = $this->validateScopes($this->getRequestParameter('scope', $request, $this->defaultScope));
54 4
        $user = $this->validateUser($request, $client);
55
56
        // Finalize the requested scopes
57 2
        $finalizedScopes = $this->scopeRepository->finalizeScopes($scopes, $this->getIdentifier(), $client, $user->getIdentifier());
58
59
        // Issue and persist new access token
60 2
        $accessToken = $this->issueAccessToken($accessTokenTTL, $client, $user->getIdentifier(), $finalizedScopes);
61 2
        $this->getEmitter()->emit(new RequestEvent(RequestEvent::ACCESS_TOKEN_ISSUED, $request));
62 2
        $responseType->setAccessToken($accessToken);
0 ignored issues
show
Bug introduced by
It seems like $accessToken defined by $this->issueAccessToken(...er(), $finalizedScopes) on line 60 can be null; however, League\OAuth2\Server\Res...rface::setAccessToken() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
63
64
        // Issue and persist new refresh token if given
65 2
        $refreshToken = $this->issueRefreshToken($accessToken);
0 ignored issues
show
Bug introduced by
It seems like $accessToken defined by $this->issueAccessToken(...er(), $finalizedScopes) on line 60 can be null; however, League\OAuth2\Server\Gra...nt::issueRefreshToken() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
66
67 2
        if ($refreshToken !== null) {
68 1
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::REFRESH_TOKEN_ISSUED, $request));
69 1
            $responseType->setRefreshToken($refreshToken);
70
        }
71
72 2
        return $responseType;
73
    }
74
75
    /**
76
     * @param ServerRequestInterface $request
77
     * @param ClientEntityInterface  $client
78
     *
79
     * @throws OAuthServerException
80
     *
81
     * @return UserEntityInterface
82
     */
83 4
    protected function validateUser(ServerRequestInterface $request, ClientEntityInterface $client)
84
    {
85 4
        $username = $this->getRequestParameter('username', $request);
86
87 4
        if (is_null($username)) {
88
            throw OAuthServerException::invalidRequest('username');
89
        }
90
91 4
        $password = $this->getRequestParameter('password', $request);
92
93 4
        if (is_null($password)) {
94 1
            throw OAuthServerException::invalidRequest('password');
95
        }
96
97 3
        $user = $this->userRepository->getUserEntityByUserCredentials(
98 3
            $username,
99 3
            $password,
100 3
            $this->getIdentifier(),
101 3
            $client
102
        );
103
104 3
        if ($user instanceof UserEntityInterface === false) {
105 1
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::USER_AUTHENTICATION_FAILED, $request));
106
107 1
            throw OAuthServerException::invalidGrant();
108
        }
109
110 2
        return $user;
111
    }
112
113
    /**
114
     * {@inheritdoc}
115
     */
116 5
    public function getIdentifier()
117
    {
118 5
        return 'password';
119
    }
120
}
121