Completed
Pull Request — master (#788)
by
unknown
33:41
created

ImplicitGrant   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 190
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 11

Importance

Changes 8
Bugs 0 Features 0
Metric Value
wmc 18
lcom 2
cbo 11
dl 0
loc 190
rs 10
c 8
b 0
f 0

9 Methods

Rating   Name   Duplication   Size   Complexity  
A setRefreshTokenTTL() 0 4 1
A setRefreshTokenRepository() 0 4 1
A canRespondToAccessTokenRequest() 0 4 1
A getIdentifier() 0 4 1
A respondToAccessTokenRequest() 0 7 1
A canRespondToAuthorizationRequest() 0 8 3
A __construct() 0 4 1
B validateAuthorizationRequest() 0 51 4
B completeAuthorizationRequest() 0 49 5
1
<?php
2
/**
3
 * @author      Alex Bilbie <[email protected]>
4
 * @copyright   Copyright (c) Alex Bilbie
5
 * @license     http://mit-license.org/
6
 *
7
 * @link        https://github.com/thephpleague/oauth2-server
8
 */
9
10
namespace League\OAuth2\Server\Grant;
11
12
use League\OAuth2\Server\Entities\ClientEntityInterface;
13
use League\OAuth2\Server\Entities\UserEntityInterface;
14
use League\OAuth2\Server\Exception\OAuthServerException;
15
use League\OAuth2\Server\Repositories\RefreshTokenRepositoryInterface;
16
use League\OAuth2\Server\RequestEvent;
17
use League\OAuth2\Server\RequestTypes\AuthorizationRequest;
18
use League\OAuth2\Server\ResponseTypes\RedirectResponse;
19
use League\OAuth2\Server\ResponseTypes\ResponseTypeInterface;
20
use Psr\Http\Message\ServerRequestInterface;
21
22
class ImplicitGrant extends AbstractAuthorizeGrant
23
{
24
    /**
25
     * @var \DateInterval
26
     */
27
    private $accessTokenTTL;
28
29
    /**
30
     * @param \DateInterval $accessTokenTTL
31
     */
32
    public function __construct(\DateInterval $accessTokenTTL)
33
    {
34
        $this->accessTokenTTL = $accessTokenTTL;
35
    }
36
37
    /**
38
     * @param \DateInterval $refreshTokenTTL
39
     *
40
     * @throw \LogicException
41
     */
42
    public function setRefreshTokenTTL(\DateInterval $refreshTokenTTL)
43
    {
44
        throw new \LogicException('The Implicit Grant does not return refresh tokens');
45
    }
46
47
    /**
48
     * @param RefreshTokenRepositoryInterface $refreshTokenRepository
49
     *
50
     * @throw \LogicException
51
     */
52
    public function setRefreshTokenRepository(RefreshTokenRepositoryInterface $refreshTokenRepository)
53
    {
54
        throw new \LogicException('The Implicit Grant does not return refresh tokens');
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    public function canRespondToAccessTokenRequest(ServerRequestInterface $request)
61
    {
62
        return false;
63
    }
64
65
    /**
66
     * Return the grant identifier that can be used in matching up requests.
67
     *
68
     * @return string
69
     */
70
    public function getIdentifier()
71
    {
72
        return 'implicit';
73
    }
74
75
    /**
76
     * Respond to an incoming request.
77
     *
78
     * @param ServerRequestInterface $request
79
     * @param ResponseTypeInterface  $responseType
80
     * @param \DateInterval          $accessTokenTTL
81
     *
82
     * @return ResponseTypeInterface
83
     */
84
    public function respondToAccessTokenRequest(
85
        ServerRequestInterface $request,
86
        ResponseTypeInterface $responseType,
87
        \DateInterval $accessTokenTTL
88
    ) {
89
        throw new \LogicException('This grant does not used this method');
90
    }
91
92
    /**
93
     * {@inheritdoc}
94
     */
95
    public function canRespondToAuthorizationRequest(ServerRequestInterface $request)
96
    {
97
        return (
98
            array_key_exists('response_type', $request->getQueryParams())
99
            && $request->getQueryParams()['response_type'] === 'token'
100
            && isset($request->getQueryParams()['client_id'])
101
        );
102
    }
103
104
    /**
105
     * {@inheritdoc}
106
     */
107
    public function validateAuthorizationRequest(ServerRequestInterface $request)
108
    {
109
        $clientId = $this->getQueryStringParameter(
110
            'client_id',
111
            $request,
112
            $this->getServerParameter('PHP_AUTH_USER', $request)
113
        );
114
        if (is_null($clientId)) {
115
            throw OAuthServerException::invalidRequest('client_id');
116
        }
117
118
        $client = $this->clientRepository->getClientEntity(
119
            $clientId,
120
            $this->getIdentifier(),
121
            null,
122
            false
123
        );
124
125
        if ($client instanceof ClientEntityInterface === false) {
126
            $this->getEmitter()->emit(new RequestEvent(RequestEvent::CLIENT_AUTHENTICATION_FAILED, $request));
127
            throw OAuthServerException::invalidClient();
128
        }
129
130
        $redirectUri = $this->getQueryStringParameter('redirect_uri', $request);
131
        $this->checkRedirectUri($redirectUri, $client, $request);
132
133
        $scopes = $this->validateScopes(
134
            $this->getQueryStringParameter('scope', $request),
135
            is_array($client->getRedirectUri())
136
                ? $client->getRedirectUri()[0]
137
                : $client->getRedirectUri()
138
        );
139
140
        // Finalize the requested scopes
141
        $scopes = $this->scopeRepository->finalizeScopes(
142
            $scopes,
143
            $this->getIdentifier(),
144
            $client
145
        );
146
147
        $stateParameter = $this->getQueryStringParameter('state', $request);
148
149
        $authorizationRequest = new AuthorizationRequest();
150
        $authorizationRequest->setGrantTypeId($this->getIdentifier());
151
        $authorizationRequest->setClient($client);
152
        $authorizationRequest->setRedirectUri($redirectUri);
153
        $authorizationRequest->setState($stateParameter);
154
        $authorizationRequest->setScopes($scopes);
155
156
        return $authorizationRequest;
157
    }
158
159
    /**
160
     * {@inheritdoc}
161
     */
162
    public function completeAuthorizationRequest(AuthorizationRequest $authorizationRequest)
163
    {
164
        if ($authorizationRequest->getUser() instanceof UserEntityInterface === false) {
165
            throw new \LogicException('An instance of UserEntityInterface should be set on the AuthorizationRequest');
166
        }
167
168
        $finalRedirectUri = ($authorizationRequest->getRedirectUri() === null)
169
            ? is_array($authorizationRequest->getClient()->getRedirectUri())
170
                ? $authorizationRequest->getClient()->getRedirectUri()[0]
171
                : $authorizationRequest->getClient()->getRedirectUri()
172
            : $authorizationRequest->getRedirectUri();
173
174
        // The user approved the client, redirect them back with an access token
175
        if ($authorizationRequest->isAuthorizationApproved() === true) {
176
            $accessToken = $this->issueAccessToken(
177
                $this->accessTokenTTL,
178
                $authorizationRequest->getClient(),
179
                $authorizationRequest->getUser()->getIdentifier(),
180
                $authorizationRequest->getScopes()
181
            );
182
183
            $response = new RedirectResponse();
184
            $response->setRedirectUri(
185
                $this->makeRedirectUri(
186
                    $finalRedirectUri,
187
                    [
188
                        'access_token' => (string) $accessToken->convertToJWT($this->privateKey),
189
                        'token_type'   => 'Bearer',
190
                        'expires_in'   => $accessToken->getExpiryDateTime()->getTimestamp() - (new \DateTime())->getTimestamp(),
191
                        'state'        => $authorizationRequest->getState(),
192
                    ],
193
                    '#'
194
                )
195
            );
196
197
            return $response;
198
        }
199
200
        // The user denied the client, redirect them back with an error
201
        throw OAuthServerException::accessDenied(
202
            'The user denied the request',
203
            $this->makeRedirectUri(
204
                $finalRedirectUri,
205
                [
206
                    'state' => $authorizationRequest->getState(),
207
                ]
208
            )
209
        );
210
    }
211
}
212