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

SessionAuthentication::getPermissions()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
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 SessionAuthentication.php
34
 *
35
 *  The Authentication using session feature 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 Platine\Framework\App\Application;
51
use Platine\Framework\Auth\AuthenticationInterface;
52
use Platine\Framework\Auth\Entity\User;
53
use Platine\Framework\Auth\Enum\UserStatus;
54
use Platine\Framework\Auth\Event\AuthInvalidPasswordEvent;
55
use Platine\Framework\Auth\Event\AuthLoginEvent;
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\UserRepository;
62
use Platine\Security\Hash\HashInterface;
63
use Platine\Session\Session;
64
65
/**
66
 * class SessionAuthentication
67
 * @package Platine\Framework\Auth\Authentication
68
 */
69
class SessionAuthentication implements AuthenticationInterface
70
{
71
    /**
72
     * Create new instance
73
     * @param Application $app
74
     * @param HashInterface $hash
75
     * @param Session $session
76
     * @param UserRepository $userRepository
77
     */
78
    public function __construct(
79
        protected Application $app,
80
        protected HashInterface $hash,
81
        protected Session $session,
82
        protected UserRepository $userRepository
83
    ) {
84
    }
85
86
    /**
87
     * {@inheritdoc}
88
     */
89
    public function getUser(): IdentityInterface
90
    {
91
        if ($this->isLogged() === false) {
92
            throw new AccountNotFoundException('User not logged', 401);
93
        }
94
95
        $id = $this->session->get('auth.user.id');
96
        $user = $this->userRepository->find($id);
97
98
        if ($user === null) {
99
            throw new AccountNotFoundException(
100
                'Can not find the logged user information, may be data is corrupted',
101
                401
102
            );
103
        }
104
105
        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...
106
    }
107
108
    /**
109
     * {@inheritdoc}
110
     */
111
    public function getPermissions(): array
112
    {
113
        return $this->session->get('auth.permissions', []);
114
    }
115
116
117
    /**
118
     * {@inheritdoc}
119
     */
120
    public function getId(): int|string
121
    {
122
        if ($this->isLogged() === false) {
123
            throw new AccountNotFoundException('User not logged', 401);
124
        }
125
126
        $id = $this->session->get('user.id');
127
128
        return $id;
129
    }
130
131
    /**
132
     * {@inheritdoc}
133
     */
134
    public function isLogged(): bool
135
    {
136
        return $this->session->has('auth');
137
    }
138
139
    /**
140
     * {@inheritdoc}
141
     */
142
    public function login(
143
        array $credentials = [],
144
        bool $remeberMe = false,
145
        bool $withPassword = true
146
    ): array {
147
        if (!isset($credentials['username'])) {
148
            throw new MissingCredentialsException(
149
                'Missing username information',
150
                401
151
            );
152
        }
153
154
        if ($withPassword && !isset($credentials['password'])) {
155
            throw new MissingCredentialsException(
156
                'Missing password information',
157
                401
158
            );
159
        }
160
161
        $username = $credentials['username'];
162
        $password = $credentials['password'] ?? '';
163
164
        $user = $this->getUserEntity($username, $password, $withPassword);
165
        if ($user === null) {
166
            throw new AccountNotFoundException(
167
                sprintf(
168
                    'Can not find the user [%s]',
169
                    $username
170
                ),
171
                401
172
            );
173
        } 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...
174
            throw new AccountLockedException(
175
                sprintf('User [%s] is locked', $username),
176
                401
177
            );
178
        }
179
180
        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...
181
            $this->app->dispatch(new AuthInvalidPasswordEvent($user));
182
183
            throw new InvalidCredentialsException(
184
                sprintf('Invalid credentials for user [%s]', $username),
185
                401
186
            );
187
        }
188
189
        $permissions = [];
190
        $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...
191
        foreach ($roles as $role) {
192
            $rolePermissions = $role->permissions;
193
            foreach ($rolePermissions as $permission) {
194
                $permissions[] = $permission->code;
195
            }
196
        }
197
198
        $data = [
199
          'user' => [
200
            'id' => $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...
201
            '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...
202
            '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...
203
            '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...
204
            '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...
205
            'status' => $user->status,
206
          ],
207
          'permissions' => $permissions,
208
        ];
209
210
        $loginData = array_merge($data, $this->getUserData($user));
211
212
        $this->session->set('auth', $loginData);
213
214
        // Inform the system that the user just login successfully
215
        $this->app->dispatch(new AuthLoginEvent($user));
216
217
        return $loginData;
218
    }
219
220
    /**
221
     * {@inheritdoc}
222
     */
223
    public function logout(bool $destroy = true): void
224
    {
225
        $this->session->remove('auth');
226
227
        if ($destroy) {
228
            $params = session_get_cookie_params();
229
            setcookie(
230
                (string) session_name(),
231
                '',
232
                time() - 42000,
233
                $params['path'],
234
                $params['domain'],
235
                $params['secure'],
236
                $params['httponly']
237
            );
238
            session_unset();
239
            session_destroy();
240
        }
241
    }
242
243
    /**
244
     * Return the user entity
245
     * @param string $username
246
     * @param string $password
247
     * @param bool $withPassword wether to use password to login
248
     * @return User|null
249
     */
250
    protected function getUserEntity(
251
        string $username,
252
        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

252
        /** @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...
253
        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

253
        /** @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...
254
    ): ?User {
255
        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...
256
                                    ->findBy(['username' => $username]);
257
    }
258
259
    /**
260
     * Return the user additional data
261
     * @param User $user
262
     * @return array<string, mixed>
263
     */
264
    protected function getUserData(User $user): array
0 ignored issues
show
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

264
    protected function getUserData(/** @scrutinizer ignore-unused */ User $user): 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...
265
    {
266
        return [];
267
    }
268
}
269