Passed
Push — develop ( 8f4078...6aa842 )
by nguereza
03:43
created

JWTAuthentication::getPermissions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Platine Framework
5
 *
6
 * Platine Framework is a lightweight, high-performance, simple and elegant
7
 * PHP Web framework
8
 *
9
 * This content is released under the MIT License (MIT)
10
 *
11
 * Copyright (c) 2020 Platine Framework
12
 *
13
 * Permission is hereby granted, free of charge, to any person obtaining a copy
14
 * of this software and associated documentation files (the "Software"), to deal
15
 * in the Software without restriction, including without limitation the rights
16
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
 * copies of the Software, and to permit persons to whom the Software is
18
 * furnished to do so, subject to the following conditions:
19
 *
20
 * The above copyright notice and this permission notice shall be included in all
21
 * copies or substantial portions of the Software.
22
 *
23
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
 * SOFTWARE.
30
 */
31
32
/**
33
 *  @file JWTAuthentication.php
34
 *
35
 *  The Authentication using JWT class
36
 *
37
 *  @package    Platine\Framework\Auth\Authentication
38
 *  @author Platine Developers team
39
 *  @copyright  Copyright (c) 2020
40
 *  @license    http://opensource.org/licenses/MIT  MIT License
41
 *  @link   https://www.platine-php.com
42
 *  @version 1.0.0
43
 *  @filesource
44
 */
45
46
declare(strict_types=1);
47
48
namespace Platine\Framework\Auth\Authentication;
49
50
use DateTime;
51
use Platine\Config\Config;
52
use Platine\Framework\Auth\AuthenticationInterface;
53
use Platine\Framework\Auth\Entity\Token;
54
use Platine\Framework\Auth\Entity\User;
55
use Platine\Framework\Auth\Enum\UserStatus;
56
use Platine\Framework\Auth\Exception\AccountLockedException;
57
use Platine\Framework\Auth\Exception\AccountNotFoundException;
58
use Platine\Framework\Auth\Exception\InvalidCredentialsException;
59
use Platine\Framework\Auth\Exception\MissingCredentialsException;
60
use Platine\Framework\Auth\IdentityInterface;
61
use Platine\Framework\Auth\Repository\TokenRepository;
62
use Platine\Framework\Auth\Repository\UserRepository;
63
use Platine\Framework\Security\JWT\Exception\JWTException;
64
use Platine\Framework\Security\JWT\JWT;
65
use Platine\Http\ServerRequestInterface;
66
use Platine\Logger\LoggerInterface;
67
use Platine\Security\Hash\HashInterface;
68
use Platine\Stdlib\Helper\Str;
69
70
/**
71
 * @class JWTAuthentication
72
 * @package Platine\Framework\Auth\Authentication
73
 * @template T
74
 */
75
class JWTAuthentication implements AuthenticationInterface
76
{
77
    /**
78
     * Create new instance
79
     * @param JWT $jwt
80
     * @param LoggerInterface $logger
81
     * @param Config<T> $config
82
     * @param HashInterface $hash
83
     * @param UserRepository $userRepository
84
     * @param TokenRepository $tokenRepository
85
     * @param ServerRequestInterface $request
86
     */
87
    public function __construct(
88
        protected JWT $jwt,
89
        protected LoggerInterface $logger,
90
        protected Config $config,
91
        protected HashInterface $hash,
92
        protected UserRepository $userRepository,
93
        protected TokenRepository $tokenRepository,
94
        protected ServerRequestInterface $request
95
    ) {
96
    }
97
98
    /**
99
     * {@inheritdoc}
100
     */
101
    public function getUser(): IdentityInterface
102
    {
103
        if ($this->isLogged() === false) {
104
            throw new AccountNotFoundException('User not logged', 401);
105
        }
106
107
        $payload = $this->jwt->getPayload();
108
        $id = (int) ($payload['sub'] ?? -1);
109
110
        $user = $this->userRepository->find($id);
111
        if ($user === null) {
112
            throw new AccountNotFoundException(
113
                'Can not find the logged user information, may be data is corrupted',
114
                401
115
            );
116
        }
117
118
        return $user;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $user returns the type Platine\Orm\Entity which is incompatible with the type-hinted return Platine\Framework\Auth\IdentityInterface.
Loading history...
119
    }
120
121
    /**
122
     * {@inheritdoc}
123
     */
124
    public function getPermissions(): array
125
    {
126
        if ($this->isLogged() === false) {
127
            return [];
128
        }
129
130
        $payload = $this->jwt->getPayload();
131
        return $payload['permissions'] ?? [];
132
    }
133
134
135
    /**
136
     * {@inheritdoc}
137
     */
138
    public function getId(): int|string
139
    {
140
        if ($this->isLogged() === false) {
141
            throw new AccountNotFoundException('User not logged', 401);
142
        }
143
144
        $payload = $this->jwt->getPayload();
145
        $id = (int) ($payload['sub'] ?? -1);
146
147
        return $id;
148
    }
149
150
    /**
151
     * {@inheritdoc}
152
     */
153
    public function isLogged(): bool
154
    {
155
        $request = $this->request;
156
        $headerName = $this->config->get('api.auth.headers.name', 'Authorization');
157
        $tokenHeader = $request->getHeaderLine($headerName);
158
        if (empty($tokenHeader)) {
159
            $this->logger->error('API authentication failed missing token header');
160
161
            return false;
162
        }
163
        $tokenType = $this->config->get('api.auth.headers.token_type', 'Bearer');
164
        $secret = $this->config->get('api.sign.secret', '');
165
166
        $token = Str::replaceFirst($tokenType . ' ', '', $tokenHeader);
167
168
        $this->jwt->setSecret($secret);
169
        try {
170
            $this->jwt->decode($token);
171
172
            return true;
173
        } catch (JWTException $ex) {
174
            $this->logger->error('API authentication failed: {message}', [
175
                'message' => $ex->getMessage(),
176
            ]);
177
        }
178
179
        return false;
180
    }
181
182
    /**
183
     * {@inheritdoc}
184
     */
185
    public function login(
186
        array $credentials = [],
187
        bool $remeberMe = false,
188
        bool $withPassword = true
189
    ): array {
190
        if (!isset($credentials['username'])) {
191
            throw new MissingCredentialsException(
192
                'Missing username information',
193
                401
194
            );
195
        }
196
197
        if ($withPassword && !isset($credentials['password'])) {
198
            throw new MissingCredentialsException(
199
                'Missing password information',
200
                401
201
            );
202
        }
203
204
        $username = $credentials['username'];
205
        $password = $credentials['password'] ?? '';
206
        $user = $this->getUserEntity($username, $password, $withPassword);
207
208
        if ($user === null) {
209
            throw new AccountNotFoundException(
210
                sprintf(
211
                    'Can not find the user [%s]',
212
                    $username
213
                ),
214
                401
215
            );
216
        } elseif ($user->status === UserStatus::LOCKED) {
0 ignored issues
show
Bug Best Practice introduced by
The property status does not exist on Platine\Framework\Auth\Entity\User. Since you implemented __get, consider adding a @property annotation.
Loading history...
217
            throw new AccountLockedException(
218
                sprintf('User [%s] is locked', $username),
219
                401
220
            );
221
        }
222
223
        if ($withPassword && $this->hash->verify($password, $user->password) === false) {
0 ignored issues
show
Bug Best Practice introduced by
The property password does not exist on Platine\Framework\Auth\Entity\User. Since you implemented __get, consider adding a @property annotation.
Loading history...
224
            throw new InvalidCredentialsException(
225
                sprintf('Invalid credentials for user [%s]', $username),
226
                401
227
            );
228
        }
229
230
        $permissions = [];
231
        $roles = $user->roles;
0 ignored issues
show
Bug Best Practice introduced by
The property roles does not exist on Platine\Framework\Auth\Entity\User. Since you implemented __get, consider adding a @property annotation.
Loading history...
232
        foreach ($roles as $role) {
233
            $rolePermissions = $role->permissions;
234
            foreach ($rolePermissions as $permission) {
235
                if (in_array($permission->code, $permissions) === false) {
236
                    $permissions[] = $permission->code;
237
                }
238
            }
239
        }
240
241
        $secret = $this->config->get('api.sign.secret');
242
        $expire = $this->config->get('api.auth.token_expire', 900);
243
        $refreshExpire = $this->config->get('api.auth.refresh_token_expire', 30 * 86400);
244
        $tokenExpire = time() + $expire;
245
        $refreshTokenExpire = time() + $refreshExpire;
246
        $this->jwt->setSecret($secret)
247
                  ->setPayload([
248
                      'sub' => $user->id,
0 ignored issues
show
Bug Best Practice introduced by
The property id does not exist on Platine\Framework\Auth\Entity\User. Since you implemented __get, consider adding a @property annotation.
Loading history...
249
                      'exp' => $tokenExpire,
250
                      'permissions' => $permissions,
251
                  ])
252
                  ->sign();
253
254
        $refreshToken = Str::random(64);
255
        $jwtToken = $this->jwt->getToken();
256
257
        $token = $this->tokenRepository->create([
258
            'token' => $jwtToken,
259
            'refresh_token' => $refreshToken,
260
            'expire_at' => (new DateTime())->setTimestamp($refreshTokenExpire),
261
            'user_id' => $user->id,
262
        ]);
263
        $this->tokenRepository->save($token);
264
265
        $data = [
266
          'user' => [
267
            'id' => $user->id,
268
            'username' => $user->username,
0 ignored issues
show
Bug Best Practice introduced by
The property username does not exist on Platine\Framework\Auth\Entity\User. Since you implemented __get, consider adding a @property annotation.
Loading history...
269
            'lastname' => $user->lastname,
0 ignored issues
show
Bug Best Practice introduced by
The property lastname does not exist on Platine\Framework\Auth\Entity\User. Since you implemented __get, consider adding a @property annotation.
Loading history...
270
            'firstname' => $user->firstname,
0 ignored issues
show
Bug Best Practice introduced by
The property firstname does not exist on Platine\Framework\Auth\Entity\User. Since you implemented __get, consider adding a @property annotation.
Loading history...
271
            'email' => $user->email,
0 ignored issues
show
Bug Best Practice introduced by
The property email does not exist on Platine\Framework\Auth\Entity\User. Since you implemented __get, consider adding a @property annotation.
Loading history...
272
            'status' => $user->status,
273
          ],
274
          'permissions' => $permissions,
275
          'token' => $jwtToken,
276
          'refresh_token' => $refreshToken,
277
        ];
278
279
        return array_merge($data, $this->getUserData($user, $token));
280
    }
281
282
    /**
283
     * {@inheritdoc}
284
     */
285
    public function logout(bool $destroy = true): void
286
    {
287
        // do nothing now
288
    }
289
290
    /**
291
     * Return the user entity
292
     * @param string $username
293
     * @param string $password
294
     * @param bool $withPassword wether to use password to login
295
     * @return User|null
296
     */
297
    protected function getUserEntity(
298
        string $username,
299
        string $password,
0 ignored issues
show
Unused Code introduced by
The parameter $password is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

299
        /** @scrutinizer ignore-unused */ string $password,

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
300
        bool $withPassword = true
0 ignored issues
show
Unused Code introduced by
The parameter $withPassword is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

300
        /** @scrutinizer ignore-unused */ bool $withPassword = true

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
301
    ): ?User {
302
        return $this->userRepository->with('roles.permissions')
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->userReposi...sername' => $username)) could return the type Platine\Orm\Entity which includes types incompatible with the type-hinted return Platine\Framework\Auth\Entity\User|null. Consider adding an additional type-check to rule them out.
Loading history...
303
                                    ->findBy(['username' => $username]);
304
    }
305
306
    /**
307
     * Return the user additional data
308
     * @param User $user
309
     * @param Token $token
310
     * @return array<string, mixed>
311
     */
312
    protected function getUserData(User $user, Token $token): array
0 ignored issues
show
Unused Code introduced by
The parameter $token is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

312
    protected function getUserData(User $user, /** @scrutinizer ignore-unused */ Token $token): array

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $user is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

312
    protected function getUserData(/** @scrutinizer ignore-unused */ User $user, Token $token): array

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
313
    {
314
        return [];
315
    }
316
}
317