PasswordGrant::createTokenResponse()   B
last analyzed

Complexity

Conditions 7
Paths 8

Size

Total Lines 33
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 17
c 1
b 0
f 0
nc 8
nop 3
dl 0
loc 33
rs 8.8333
1
<?php
2
3
/**
4
 * Platine OAuth2
5
 *
6
 * Platine OAuth2 is a library that implements the OAuth2 specification
7
 *
8
 * This content is released under the MIT License (MIT)
9
 *
10
 * Copyright (c) 2020 Platine OAuth2
11
 *
12
 * Permission is hereby granted, free of charge, to any person obtaining a copy
13
 * of this software and associated documentation files (the "Software"), to deal
14
 * in the Software without restriction, including without limitation the rights
15
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
 * copies of the Software, and to permit persons to whom the Software is
17
 * furnished to do so, subject to the following conditions:
18
 *
19
 * The above copyright notice and this permission notice shall be included in all
20
 * copies or substantial portions of the Software.
21
 *
22
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
 * SOFTWARE.
29
 */
30
31
declare(strict_types=1);
32
33
namespace Platine\OAuth2\Grant;
34
35
use Platine\Http\ResponseInterface;
36
use Platine\Http\ServerRequestInterface;
37
use Platine\OAuth2\AuthorizationServerInterface;
38
use Platine\OAuth2\Entity\Client;
39
use Platine\OAuth2\Entity\TokenOwnerInterface;
40
use Platine\OAuth2\Entity\UserAuthenticationInterface;
41
use Platine\OAuth2\Exception\OAuth2Exception;
42
use Platine\OAuth2\Service\AccessTokenService;
43
use Platine\OAuth2\Service\RefreshTokenService;
44
45
/**
46
 * This authorization grant type, also known as "resource owner password credentials", is ideal
47
 * when you trust the client (for instance for a native app)
48
 *
49
 * @class PasswordGrant
50
 * @package Platine\OAuth2\Grant
51
 */
52
class PasswordGrant extends BaseGrant implements AuthorizationServerAwareInterface
53
{
54
    public const GRANT_TYPE = 'password';
55
    public const GRANT_RESPONSE_TYPE = '';
56
57
    /**
58
     * The authorization server instance
59
     * @var AuthorizationServerInterface|null
60
     */
61
    protected ?AuthorizationServerInterface $authorizationServer = null;
62
63
    /**
64
     * Create new instance
65
     * @param UserAuthenticationInterface $userAuthentication
66
     * @param AccessTokenService $accessTokenService
67
     * @param RefreshTokenService $refreshTokenService
68
     */
69
    public function __construct(
70
        protected UserAuthenticationInterface $userAuthentication,
71
        protected AccessTokenService $accessTokenService,
72
        protected RefreshTokenService $refreshTokenService
73
    ) {
74
    }
75
76
        /**
77
     * {@inheritdoc}
78
     */
79
    public function createAuthorizationResponse(
80
        ServerRequestInterface $request,
81
        Client $client,
82
        ?TokenOwnerInterface $owner = null
83
    ): ResponseInterface {
84
        throw OAuth2Exception::invalidRequest('Password grant does not support authorization');
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90
    public function createTokenResponse(
91
        ServerRequestInterface $request,
92
        ?Client $client = null,
93
        ?TokenOwnerInterface $owner = null
94
    ): ResponseInterface {
95
        $postParams = (array) $request->getParsedBody();
96
        $username = $postParams['username'] ?? null;
97
        $password = $postParams['password'] ?? null;
98
        $scope = $postParams['scope'] ?? null;
99
        $scopes = is_string($scope) ? explode(' ', $scope) : [];
100
101
        if ($username === null || $password === null) {
102
            throw OAuth2Exception::invalidRequest('Username and/or password is missing in the request');
103
        }
104
105
        $userOwner = $this->userAuthentication->validate($username, $password);
106
        if ($userOwner === null) {
107
            throw OAuth2Exception::accessDenied('Either username or password are incorrect');
108
        }
109
110
        $accessToken = $this->accessTokenService->createToken($userOwner, $client, $scopes);
111
112
        // Before generating a refresh token, we must make sure the
113
        //  authorization server supports this grant
114
        $refreshToken = null;
115
        if (
116
            $this->authorizationServer !== null &&
117
            $this->authorizationServer->hasGrant(RefreshTokenGrant::GRANT_TYPE)
118
        ) {
119
            $refreshToken = $this->refreshTokenService->createToken($userOwner, $client, $scopes);
120
        }
121
122
        return $this->generateTokenResponse($accessToken, $refreshToken);
123
    }
124
125
    /**
126
     * {@inheritdoc}
127
     */
128
    public function setAuthorizationServer(
129
        AuthorizationServerInterface $authorizationServer
130
    ): void {
131
        $this->authorizationServer = $authorizationServer;
132
    }
133
134
    /**
135
     * {@inheritdoc}
136
     */
137
    public function allowPublicClients(): bool
138
    {
139
        return true;
140
    }
141
}
142