Passed
Pull Request — master (#235)
by
unknown
02:58
created

User::loginByAccessToken()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 4
nc 2
nop 2
dl 0
loc 7
ccs 0
cts 4
cp 0
crap 12
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace Yiisoft\Yii\Web\User;
4
5
use Psr\EventDispatcher\EventDispatcherInterface;
6
use Psr\Http\Message\ResponseInterface;
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\Event\AfterLogin;
13
use Yiisoft\Yii\Web\User\Event\AfterLogout;
14
use Yiisoft\Yii\Web\User\Event\BeforeLogin;
15
use Yiisoft\Yii\Web\User\Event\BeforeLogout;
16
17
class User implements IdentityInterface
18
{
19
    private const SESSION_AUTH_ID = '__auth_id';
20
    private const SESSION_AUTH_EXPIRE = '__auth_expire';
21
    private const SESSION_AUTH_ABSOLUTE_EXPIRE = '__auth_absolute_expire';
22
23
    private IdentityRepositoryInterface $identityRepository;
24
    private EventDispatcherInterface $eventDispatcher;
25
26
    private string $identityCookie = 'remember';
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
     * @param ResponseInterface $response Response to handle
144
     */
145
    protected function sendIdentityCookie(IdentityInterface $identity, int $duration, ResponseInterface $response): void
146
    {
147
        $data = json_encode(
148
            [
149
                $identity->getId(),
150
                $this->getAuthKey(),
151
                $duration,
152
            ],
153
            JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
154
        );
155
156
        $expireDateTime = new \DateTimeImmutable();
157
        $expireDateTime->setTimestamp(time() + $duration);
158
        $cookieIdentity = (new Cookie($this->identityCookie, $data))->expireAt($expireDateTime);
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
     * @param ResponseInterface $response Response to handle
180
     * @return bool whether the user is logged in
181
     */
182
    public function login(IdentityInterface $identity, int $duration = 0, ResponseInterface $response): bool
183
    {
184
        if ($this->beforeLogin($identity, $duration)) {
185
            $this->switchIdentity($identity);
186
            $this->afterLogin($identity, $duration);
187
            $this->sendIdentityCookie($identity, $duration, $response);
188
        }
189
        return !$this->isGuest();
190
    }
191
192
    /**
193
     * Logs in a user by the given access token.
194
     * This method will first authenticate the user by calling [[IdentityInterface::findIdentityByAccessToken()]]
195
     * with the provided access token. If successful, it will call [[login()]] to log in the authenticated user.
196
     * If authentication fails or [[login()]] is unsuccessful, it will return null.
197
     * @param string $token the access token
198
     * @param string $type the type of the token. The value of this parameter depends on the implementation.
199
     * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
200
     * @return IdentityInterface|null the identity associated with the given access token. Null is returned if
201
     * the access token is invalid or [[login()]] is unsuccessful.
202
     */
203
    public function loginByAccessToken(string $token, string $type = null): ?IdentityInterface
204
    {
205
        $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

205
        $identity = $this->identityRepository->findIdentityByToken($token, /** @scrutinizer ignore-type */ $type);
Loading history...
206
        if ($identity && $this->login($identity)) {
0 ignored issues
show
Bug introduced by
The call to Yiisoft\Yii\Web\User\User::login() has too few arguments starting with response. ( Ignorable by Annotation )

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

206
        if ($identity && $this->/** @scrutinizer ignore-call */ login($identity)) {

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
207
            return $identity;
208
        }
209
        return null;
210
    }
211
212
    /**
213
     * Logs out the current user.
214
     * This will remove authentication-related session data.
215
     * If `$destroySession` is true, all session data will be removed.
216
     * @param bool $destroySession whether to destroy the whole session. Defaults to true.
217
     * This parameter is ignored if [[enableSession]] is false.
218
     * @return bool whether the user is logged out
219
     * @throws \Throwable
220
     */
221
    public function logout($destroySession = true): bool
222
    {
223
        $identity = $this->getIdentity();
224
        if ($this->isGuest()) {
225
            return false;
226
        }
227
        if ($this->beforeLogout($identity)) {
228
            $this->switchIdentity(new GuestIdentity());
229
            if ($destroySession && $this->session) {
230
                $this->session->destroy();
231
            }
232
233
            // Remove the cookie
234
            $expireDateTime = new \DateTimeImmutable();
235
            $expireDateTime->modify("-1 day");
236
            (new Cookie($this->identityCookie, ""))->expireAt($expireDateTime);
237
238
            $this->afterLogout($identity);
239
        }
240
        return $this->isGuest();
241
    }
242
243
    /**
244
     * Returns a value indicating whether the user is a guest (not authenticated).
245
     * @return bool whether the current user is a guest.
246
     * @see getIdentity()
247
     */
248
    public function isGuest(): bool
249
    {
250
        return $this->getIdentity() instanceof GuestIdentity;
251
    }
252
253
    /**
254
     * Returns a value that uniquely represents the user.
255
     * @return string the unique identifier for the user. If `null`, it means the user is a guest.
256
     * @throws \Throwable
257
     * @see getIdentity()
258
     */
259
    public function getId(): ?string
260
    {
261
        return $this->getIdentity()->getId();
262
    }
263
264
    /**
265
     * Set the name of the cookie identity
266
     * @param string $name New name of the cookie
267
     * @return this
268
     */
269
    public function setIdentityCookie(string $name): this
0 ignored issues
show
Bug introduced by
The type Yiisoft\Yii\Web\User\this was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
270
    {
271
        $new = clone $this;
272
        $new->identityCookie = $name;
273
        return $new;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $new returns the type Yiisoft\Yii\Web\User\User which is incompatible with the type-hinted return Yiisoft\Yii\Web\User\this.
Loading history...
274
    }
275
276
    /**
277
     * This method is called before logging in a user.
278
     * The default implementation will trigger the [[EVENT_BEFORE_LOGIN]] event.
279
     * If you override this method, make sure you call the parent implementation
280
     * so that the event is triggered.
281
     * @param IdentityInterface $identity the user identity information
282
     * @param int $duration number of seconds that the user can remain in logged-in status.
283
     * If 0, it means login till the user closes the browser or the session is manually destroyed.
284
     * @return bool whether the user should continue to be logged in
285
     */
286
    protected function beforeLogin(IdentityInterface $identity, int $duration): bool
287
    {
288
        $event = new BeforeLogin($identity, $duration);
289
        $this->eventDispatcher->dispatch($event);
290
        return $event->isValid();
291
    }
292
293
    /**
294
     * This method is called after the user is successfully logged in.
295
     * The default implementation will trigger the [[EVENT_AFTER_LOGIN]] event.
296
     * If you override this method, make sure you call the parent implementation
297
     * so that the event is triggered.
298
     * @param IdentityInterface $identity the user identity information
299
     * @param int $duration number of seconds that the user can remain in logged-in status.
300
     * If 0, it means login till the user closes the browser or the session is manually destroyed.
301
     */
302
    protected function afterLogin(IdentityInterface $identity, int $duration): void
303
    {
304
        $this->eventDispatcher->dispatch(new AfterLogin($identity, $duration));
305
    }
306
307
    /**
308
     * This method is invoked when calling [[logout()]] to log out a user.
309
     * The default implementation will trigger the [[EVENT_BEFORE_LOGOUT]] event.
310
     * If you override this method, make sure you call the parent implementation
311
     * so that the event is triggered.
312
     * @param IdentityInterface $identity the user identity information
313
     * @return bool whether the user should continue to be logged out
314
     */
315
    protected function beforeLogout(IdentityInterface $identity): bool
316
    {
317
        $event = new BeforeLogout($identity);
318
        $this->eventDispatcher->dispatch($event);
319
        return $event->isValid();
320
    }
321
322
    /**
323
     * This method is invoked right after a user is logged out via [[logout()]].
324
     * The default implementation will trigger the [[EVENT_AFTER_LOGOUT]] event.
325
     * If you override this method, make sure you call the parent implementation
326
     * so that the event is triggered.
327
     * @param IdentityInterface $identity the user identity information
328
     */
329
    protected function afterLogout(IdentityInterface $identity): void
330
    {
331
        $this->eventDispatcher->dispatch(new AfterLogout($identity));
332
    }
333
334
    /**
335
     * Switches to a new identity for the current user.
336
     *
337
     * When [[enableSession]] is true, this method may use session and/or cookie to store the user identity information,
338
     * according to the value of `$duration`. Please refer to [[login()]] for more details.
339
     *
340
     * This method is mainly called by [[login()]], [[logout()]] and [[loginByCookie()]]
341
     * when the current user needs to be associated with the corresponding identity information.
342
     *
343
     * @param IdentityInterface $identity the identity information to be associated with the current user.
344
     * In order to indicate that the user is guest, use {{@see GuestIdentity}}.
345
     */
346
    public function switchIdentity(IdentityInterface $identity): void
347
    {
348
        $this->setIdentity($identity);
349
        if ($this->session === null) {
350
            return;
351
        }
352
353
        $this->session->regenerateID();
354
355
        $this->session->remove(self::SESSION_AUTH_ID);
356
        $this->session->remove(self::SESSION_AUTH_EXPIRE);
357
358
        if ($identity->getId() === null) {
359
            return;
360
        }
361
        $this->session->set(self::SESSION_AUTH_ID, $identity->getId());
362
        if ($this->authTimeout !== null) {
363
            $this->session->set(self::SESSION_AUTH_EXPIRE, time() + $this->authTimeout);
364
        }
365
        if ($this->absoluteAuthTimeout !== null) {
366
            $this->session->set(self::SESSION_AUTH_ABSOLUTE_EXPIRE, time() + $this->absoluteAuthTimeout);
367
        }
368
    }
369
370
    /**
371
     * Updates the authentication status using the information from session and cookie.
372
     *
373
     * This method will try to determine the user identity using a session variable.
374
     *
375
     * If [[authTimeout]] is set, this method will refresh the timer.
376
     *
377
     * If the user identity cannot be determined by session, this method will try to [[loginByCookie()|login by cookie]]
378
     * if [[enableAutoLogin]] is true.
379
     * @throws \Throwable
380
     */
381
    protected function renewAuthStatus(): void
382
    {
383
        $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

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