Passed
Pull Request — master (#235)
by Alexander
03:01
created

User::login()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
nc 2
nop 2
dl 0
loc 8
ccs 0
cts 1
cp 0
crap 6
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace Yiisoft\Yii\Web\User;
4
5
use Nyholm\Psr7\Response;
6
use Psr\EventDispatcher\EventDispatcherInterface;
7
use Yiisoft\Access\AccessCheckerInterface;
8
use Yiisoft\Auth\IdentityInterface;
9
use Yiisoft\Auth\IdentityRepositoryInterface;
10
use Yiisoft\Yii\Web\Cookie;
11
use Yiisoft\Yii\Web\Session\SessionInterface;
12
use Yiisoft\Yii\Web\User\AuthenticationKeyInterface;
13
use Yiisoft\Yii\Web\User\Event\AfterLogin;
14
use Yiisoft\Yii\Web\User\Event\AfterLogout;
15
use Yiisoft\Yii\Web\User\Event\BeforeLogin;
16
use Yiisoft\Yii\Web\User\Event\BeforeLogout;
17
18
class User implements AuthenticationKeyInterface
19
{
20
    private const SESSION_AUTH_ID = '__auth_id';
21
    private const SESSION_AUTH_EXPIRE = '__auth_expire';
22
    private const SESSION_AUTH_ABSOLUTE_EXPIRE = '__auth_absolute_expire';
23
24
    private IdentityRepositoryInterface $identityRepository;
25
    private EventDispatcherInterface $eventDispatcher;
26
27
    private ?AccessCheckerInterface $accessChecker = null;
28
    private ?IdentityInterface $identity = null;
29
    private ?SessionInterface $session = null;
30
31
    public function __construct(
32
        IdentityRepositoryInterface $identityRepository,
33
        EventDispatcherInterface $eventDispatcher
34
    ) {
35
        $this->identityRepository = $identityRepository;
36
        $this->eventDispatcher = $eventDispatcher;
37
    }
38
39
    /**
40
     * @var int|null the number of seconds in which the user will be logged out automatically if he
41
     * remains inactive. If this property is not set, the user will be logged out after
42
     * the current session expires (c.f. [[Session::timeout]]).
43
     */
44
    public ?int $authTimeout = null;
45
46
    /**
47
     * @var int|null the number of seconds in which the user will be logged out automatically
48
     * regardless of activity.
49
     * Note that this will not work if [[enableAutoLogin]] is `true`.
50
     */
51
    public ?int $absoluteAuthTimeout = null;
52
53
    /**
54
     * @var array MIME types for which this component should redirect to the [[loginUrl]].
55
     */
56
    public array $acceptableRedirectTypes = ['text/html', 'application/xhtml+xml'];
57
58
    /**
59
     * Set session to persist authentication status across multiple requests.
60
     * If not set, authentication has to be performed on each request, which is often the case
61
     * for stateless application such as RESTful API.
62
     *
63
     * @param SessionInterface $session
64
     */
65
    public function setSession(SessionInterface $session): void
66
    {
67
        $this->session = $session;
68
    }
69
70
    public function setAccessChecker(AccessCheckerInterface $accessChecker): void
71
    {
72
        $this->accessChecker = $accessChecker;
73
    }
74
75
    /**
76
     * Returns the identity object associated with the currently logged-in user.
77
     * When [[enableSession]] is true, this method may attempt to read the user's authentication data
78
     * stored in session and reconstruct the corresponding identity object, if it has not done so before.
79
     * @param bool $autoRenew whether to automatically renew authentication status if it has not been done so before.
80
     * This is only useful when [[enableSession]] is true.
81
     * @return IdentityInterface the identity object associated with the currently logged-in user.
82
     * @throws \Throwable
83
     * @see logout()
84
     * @see login()
85
     */
86
    public function getIdentity($autoRenew = true): IdentityInterface
87
    {
88
        if ($this->identity !== null) {
89
            return $this->identity;
90
        }
91
        if ($this->session === null || !$autoRenew) {
92
            return new GuestIdentity();
93
        }
94
        try {
95
            $this->renewAuthStatus();
96
        } catch (\Throwable $e) {
97
            $this->identity = null;
98
            throw $e;
99
        }
100
        return $this->identity;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->identity returns the type null which is incompatible with the type-hinted return Yiisoft\Auth\IdentityInterface.
Loading history...
101
    }
102
103
    /**
104
     * Sets the user identity object.
105
     *
106
     * Note that this method does not deal with session or cookie. You should usually use [[switchIdentity()]]
107
     * to change the identity of the current user.
108
     *
109
     * @param IdentityInterface|null $identity the identity object associated with the currently logged user.
110
     * Use {{@see GuestIdentity}} to indicate that the current user is a guest.
111
     */
112
    public function setIdentity(IdentityInterface $identity): void
113
    {
114
        $this->identity = $identity;
115
    }
116
117
    /**
118
     * Return the auth key value
119
     *
120
     * @return string Auth key value
121
     */
122
    public function getAuthKey(): string
123
    {
124
        return 'ABCD1234';
125
    }
126
127
    /**
128
     * Validate auth key
129
     *
130
     * @param String $authKey Auth key to validate
131
     * @return bool True if is valid
132
     */
133
    public function validateAuthKey($authKey): bool
134
    {
135
        return $authKey === 'ABCD1234';
136
    }
137
138
    /**
139
     * Sends an identity cookie.
140
     *
141
     * @param IdentityInterface $identity
142
     * @param int $duration number of seconds that the user can remain in logged-in status.
143
     */
144
    protected function sendIdentityCookie(IdentityInterface $identity, int $duration): void
145
    {
146
        $data = json_encode(
147
            [
148
                $identity->getId(),
149
                $this->getAuthKey(),
150
                $duration,
151
            ],
152
            JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
153
        );
154
155
        $expireDateTime = new \DateTimeImmutable();
156
        $expireDateTime->setTimestamp(time() + $duration);
157
        $cookieIdentity = (new Cookie('remember', $data))->expireAt($expireDateTime);
158
        $response = new Response();
159
        $cookieIdentity->addToResponse($response);
160
    }
161
162
    /**
163
     * Logs in a user.
164
     *
165
     * After logging in a user:
166
     * - the user's identity information is obtainable from the [[identity]] property
167
     *
168
     * If [[enableSession]] is `true`:
169
     * - the identity information will be stored in session and be available in the next requests
170
     * - in case of `$duration == 0`: as long as the session remains active or till the user closes the browser
171
     * - in case of `$duration > 0`: as long as the session remains active or as long as the cookie
172
     *   remains valid by it's `$duration` in seconds when [[enableAutoLogin]] is set `true`.
173
     *
174
     * If [[enableSession]] is `false`:
175
     * - the `$duration` parameter will be ignored
176
     *
177
     * @param IdentityInterface $identity the user identity (which should already be authenticated)
178
     * @param int $duration number of seconds that the user can remain in logged-in status, defaults to `0`
179
     * @return bool whether the user is logged in
180
     */
181
    public function login(IdentityInterface $identity, int $duration = 0): bool
182
    {
183
        if ($this->beforeLogin($identity, $duration)) {
184
            $this->switchIdentity($identity);
185
            $this->afterLogin($identity, $duration);
186
            $this->sendIdentityCookie($identity, $duration);
187
        }
188
        return !$this->isGuest();
189
    }
190
191
    /**
192
     * Logs in a user by the given access token.
193
     * This method will first authenticate the user by calling [[IdentityInterface::findIdentityByAccessToken()]]
194
     * with the provided access token. If successful, it will call [[login()]] to log in the authenticated user.
195
     * If authentication fails or [[login()]] is unsuccessful, it will return null.
196
     * @param string $token the access token
197
     * @param string $type the type of the token. The value of this parameter depends on the implementation.
198
     * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
199
     * @return IdentityInterface|null the identity associated with the given access token. Null is returned if
200
     * the access token is invalid or [[login()]] is unsuccessful.
201
     */
202
    public function loginByAccessToken(string $token, string $type = null): ?IdentityInterface
203
    {
204
        $identity = $this->identityRepository->findIdentityByToken($token, $type);
0 ignored issues
show
Bug introduced by
It seems like $type can also be of type null; however, parameter $type of Yiisoft\Auth\IdentityRep...::findIdentityByToken() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

204
        $identity = $this->identityRepository->findIdentityByToken($token, /** @scrutinizer ignore-type */ $type);
Loading history...
205
        if ($identity && $this->login($identity)) {
206
            return $identity;
207
        }
208
        return null;
209
    }
210
211
    /**
212
     * Logs out the current user.
213
     * This will remove authentication-related session data.
214
     * If `$destroySession` is true, all session data will be removed.
215
     * @param bool $destroySession whether to destroy the whole session. Defaults to true.
216
     * This parameter is ignored if [[enableSession]] is false.
217
     * @return bool whether the user is logged out
218
     * @throws \Throwable
219
     */
220
    public function logout($destroySession = true): bool
221
    {
222
        $identity = $this->getIdentity();
223
        if ($this->isGuest()) {
224
            return false;
225
        }
226
        if ($this->beforeLogout($identity)) {
227
            $this->switchIdentity(new GuestIdentity());
228
            if ($destroySession && $this->session) {
229
                $this->session->destroy();
230
            }
231
232
            // Remove the cookie
233
            $expireDateTime = new \DateTimeImmutable();
234
            $expireDateTime->modify("-1 day");
235
            (new Cookie('remember', ""))->expireAt($expireDateTime);
236
237
            $this->afterLogout($identity);
238
        }
239
        return $this->isGuest();
240
    }
241
242
    /**
243
     * Returns a value indicating whether the user is a guest (not authenticated).
244
     * @return bool whether the current user is a guest.
245
     * @see getIdentity()
246
     */
247
    public function isGuest(): bool
248
    {
249
        return $this->getIdentity() instanceof GuestIdentity;
250
    }
251
252
    /**
253
     * Returns a value that uniquely represents the user.
254
     * @return string the unique identifier for the user. If `null`, it means the user is a guest.
255
     * @throws \Throwable
256
     * @see getIdentity()
257
     */
258
    public function getId(): ?string
259
    {
260
        return $this->getIdentity()->getId();
261
    }
262
263
    /**
264
     * This method is called before logging in a user.
265
     * The default implementation will trigger the [[EVENT_BEFORE_LOGIN]] event.
266
     * If you override this method, make sure you call the parent implementation
267
     * so that the event is triggered.
268
     * @param IdentityInterface $identity the user identity information
269
     * @param int $duration number of seconds that the user can remain in logged-in status.
270
     * If 0, it means login till the user closes the browser or the session is manually destroyed.
271
     * @return bool whether the user should continue to be logged in
272
     */
273
    protected function beforeLogin(IdentityInterface $identity, int $duration): bool
274
    {
275
        $event = new BeforeLogin($identity, $duration);
276
        $this->eventDispatcher->dispatch($event);
277
        return $event->isValid();
278
    }
279
280
    /**
281
     * This method is called after the user is successfully logged in.
282
     * The default implementation will trigger the [[EVENT_AFTER_LOGIN]] event.
283
     * If you override this method, make sure you call the parent implementation
284
     * so that the event is triggered.
285
     * @param IdentityInterface $identity the user identity information
286
     * @param int $duration number of seconds that the user can remain in logged-in status.
287
     * If 0, it means login till the user closes the browser or the session is manually destroyed.
288
     */
289
    protected function afterLogin(IdentityInterface $identity, int $duration): void
290
    {
291
        $this->eventDispatcher->dispatch(new AfterLogin($identity, $duration));
292
    }
293
294
    /**
295
     * This method is invoked when calling [[logout()]] to log out a user.
296
     * The default implementation will trigger the [[EVENT_BEFORE_LOGOUT]] event.
297
     * If you override this method, make sure you call the parent implementation
298
     * so that the event is triggered.
299
     * @param IdentityInterface $identity the user identity information
300
     * @return bool whether the user should continue to be logged out
301
     */
302
    protected function beforeLogout(IdentityInterface $identity): bool
303
    {
304
        $event = new BeforeLogout($identity);
305
        $this->eventDispatcher->dispatch($event);
306
        return $event->isValid();
307
    }
308
309
    /**
310
     * This method is invoked right after a user is logged out via [[logout()]].
311
     * The default implementation will trigger the [[EVENT_AFTER_LOGOUT]] event.
312
     * If you override this method, make sure you call the parent implementation
313
     * so that the event is triggered.
314
     * @param IdentityInterface $identity the user identity information
315
     */
316
    protected function afterLogout(IdentityInterface $identity): void
317
    {
318
        $this->eventDispatcher->dispatch(new AfterLogout($identity));
319
    }
320
321
    /**
322
     * Switches to a new identity for the current user.
323
     *
324
     * When [[enableSession]] is true, this method may use session and/or cookie to store the user identity information,
325
     * according to the value of `$duration`. Please refer to [[login()]] for more details.
326
     *
327
     * This method is mainly called by [[login()]], [[logout()]] and [[loginByCookie()]]
328
     * when the current user needs to be associated with the corresponding identity information.
329
     *
330
     * @param IdentityInterface $identity the identity information to be associated with the current user.
331
     * In order to indicate that the user is guest, use {{@see GuestIdentity}}.
332
     */
333
    public function switchIdentity(IdentityInterface $identity): void
334
    {
335
        $this->setIdentity($identity);
336
        if ($this->session === null) {
337
            return;
338
        }
339
340
        $this->session->regenerateID();
341
342
        $this->session->remove(self::SESSION_AUTH_ID);
343
        $this->session->remove(self::SESSION_AUTH_EXPIRE);
344
345
        if ($identity->getId() === null) {
346
            return;
347
        }
348
        $this->session->set(self::SESSION_AUTH_ID, $identity->getId());
349
        if ($this->authTimeout !== null) {
350
            $this->session->set(self::SESSION_AUTH_EXPIRE, time() + $this->authTimeout);
351
        }
352
        if ($this->absoluteAuthTimeout !== null) {
353
            $this->session->set(self::SESSION_AUTH_ABSOLUTE_EXPIRE, time() + $this->absoluteAuthTimeout);
354
        }
355
    }
356
357
    /**
358
     * Updates the authentication status using the information from session and cookie.
359
     *
360
     * This method will try to determine the user identity using a session variable.
361
     *
362
     * If [[authTimeout]] is set, this method will refresh the timer.
363
     *
364
     * If the user identity cannot be determined by session, this method will try to [[loginByCookie()|login by cookie]]
365
     * if [[enableAutoLogin]] is true.
366
     * @throws \Throwable
367
     */
368
    protected function renewAuthStatus(): void
369
    {
370
        $id = $this->session->get(self::SESSION_AUTH_ID);
0 ignored issues
show
Bug introduced by
The method get() does not exist on null. ( Ignorable by Annotation )

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

370
        /** @scrutinizer ignore-call */ 
371
        $id = $this->session->get(self::SESSION_AUTH_ID);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
371
372
        $identity = null;
373
        if ($id !== null) {
374
            $identity = $this->identityRepository->findIdentity($id);
375
        }
376
        if ($identity === null) {
377
            $identity = new GuestIdentity();
378
        }
379
        $this->setIdentity($identity);
380
381
        if (!($identity instanceof GuestIdentity) && ($this->authTimeout !== null || $this->absoluteAuthTimeout !== null)) {
382
            $expire = $this->authTimeout !== null ? $this->session->get(self::SESSION_AUTH_ABSOLUTE_EXPIRE) : null;
383
            $expireAbsolute = $this->absoluteAuthTimeout !== null ? $this->session->get(self::SESSION_AUTH_ABSOLUTE_EXPIRE) : null;
384
            if (($expire !== null && $expire < time()) || ($expireAbsolute !== null && $expireAbsolute < time())) {
385
                $this->logout(false);
386
            } elseif ($this->authTimeout !== null) {
387
                $this->session->set(self::SESSION_AUTH_EXPIRE, time() + $this->authTimeout);
388
            }
389
        }
390
    }
391
392
    /**
393
     * Checks if the user can perform the operation as specified by the given permission.
394
     *
395
     * Note that you must provide access checker via {{@see User::setAccessChecker()}} in order to use this method.
396
     * Otherwise it will always return false.
397
     *
398
     * @param string $permissionName the name of the permission (e.g. "edit post") that needs access check.
399
     * @param array $params name-value pairs that would be passed to the rules associated
400
     * with the roles and permissions assigned to the user.
401
     * @return bool whether the user can perform the operation as specified by the given permission.
402
     * @throws \Throwable
403
     */
404
    public function can(string $permissionName, array $params = []): bool
405
    {
406
        if ($this->accessChecker === null) {
407
            return false;
408
        }
409
410
        return $this->accessChecker->userHasPermission($this->getId(), $permissionName, $params);
411
    }
412
}
413