User::renewAuthStatus()   F
last analyzed

Complexity

Conditions 21
Paths 1872

Size

Total Lines 42
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 27
CRAP Score 21.02

Importance

Changes 0
Metric Value
cc 21
eloc 28
nc 1872
nop 0
dl 0
loc 42
ccs 27
cts 28
cp 0.9643
crap 21.02
rs 0
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * @link https://www.yiiframework.com/
5
 * @copyright Copyright (c) 2008 Yii Software LLC
6
 * @license https://www.yiiframework.com/license/
7
 */
8
9
namespace yii\web;
10
11
use Yii;
12
use yii\base\Component;
13
use yii\base\InvalidConfigException;
14
use yii\base\InvalidValueException;
15
use yii\di\Instance;
16
use yii\rbac\CheckAccessInterface;
17
18
/**
19
 * User is the class for the `user` application component that manages the user authentication status.
20
 *
21
 * You may use [[isGuest]] to determine whether the current user is a guest or not.
22
 * If the user is a guest, the [[identity]] property would return `null`. Otherwise, it would
23
 * be an instance of [[IdentityInterface]].
24
 *
25
 * You may call various methods to change the user authentication status:
26
 *
27
 * - [[login()]]: sets the specified identity and remembers the authentication status in session and cookie;
28
 * - [[logout()]]: marks the user as a guest and clears the relevant information from session and cookie;
29
 * - [[setIdentity()]]: changes the user identity without touching session or cookie
30
 *   (this is best used in stateless RESTful API implementation).
31
 *
32
 * Note that User only maintains the user authentication status. It does NOT handle how to authenticate
33
 * a user. The logic of how to authenticate a user should be done in the class implementing [[IdentityInterface]].
34
 * You are also required to set [[identityClass]] with the name of this class.
35
 *
36
 * User is configured as an application component in [[\yii\web\Application]] by default.
37
 * You can access that instance via `Yii::$app->user`.
38
 *
39
 * You can modify its configuration by adding an array to your application config under `components`
40
 * as it is shown in the following example:
41
 *
42
 * ```php
43
 * 'user' => [
44
 *     'identityClass' => 'app\models\User', // User must implement the IdentityInterface
45
 *     'enableAutoLogin' => true,
46
 *     // 'loginUrl' => ['user/login'],
47
 *     // ...
48
 * ]
49
 * ```
50
 *
51
 * @property-read string|int|null $id The unique identifier for the user. If `null`, it means the user is a
52
 * guest.
53
 * @property IdentityInterface|null $identity The identity object associated with the currently logged-in
54
 * user. `null` is returned if the user is not logged in (not authenticated).
55
 * @property-read bool $isGuest Whether the current user is a guest.
56
 * @property string $returnUrl The URL that the user should be redirected to after login. Note that the type
57
 * of this property differs in getter and setter. See [[getReturnUrl()]] and [[setReturnUrl()]] for details.
58
 *
59
 * @author Qiang Xue <[email protected]>
60
 * @since 2.0
61
 */
62
class User extends Component
63
{
64
    const EVENT_BEFORE_LOGIN = 'beforeLogin';
65
    const EVENT_AFTER_LOGIN = 'afterLogin';
66
    const EVENT_BEFORE_LOGOUT = 'beforeLogout';
67
    const EVENT_AFTER_LOGOUT = 'afterLogout';
68
69
    /**
70
     * @var string the class name of the [[identity]] object.
71
     */
72
    public $identityClass;
73
    /**
74
     * @var bool whether to enable cookie-based login. Defaults to `false`.
75
     * Note that this property will be ignored if [[enableSession]] is `false`.
76
     */
77
    public $enableAutoLogin = false;
78
    /**
79
     * @var bool whether to use session to persist authentication status across multiple requests.
80
     * You set this property to be `false` if your application is stateless, which is often the case
81
     * for RESTful APIs.
82
     */
83
    public $enableSession = true;
84
    /**
85
     * @var string|array|null the URL for login when [[loginRequired()]] is called.
86
     * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
87
     * The first element of the array should be the route to the login action, and the rest of
88
     * the name-value pairs are GET parameters used to construct the login URL. For example,
89
     *
90
     * ```php
91
     * ['site/login', 'ref' => 1]
92
     * ```
93
     *
94
     * If this property is `null`, a 403 HTTP exception will be raised when [[loginRequired()]] is called.
95
     */
96
    public $loginUrl = ['site/login'];
97
    /**
98
     * @var array the configuration of the identity cookie. This property is used only when [[enableAutoLogin]] is `true`.
99
     * @see Cookie
100
     */
101
    public $identityCookie = ['name' => '_identity', 'httpOnly' => true];
102
    /**
103
     * @var int|null the number of seconds in which the user will be logged out automatically if the user
104
     * remains inactive. If this property is not set, the user will be logged out after
105
     * the current session expires (c.f. [[Session::timeout]]).
106
     * Note that this will not work if [[enableAutoLogin]] is `true`.
107
     */
108
    public $authTimeout;
109
    /**
110
     * @var CheckAccessInterface|string|array|null The access checker object to use for checking access or the application
111
     * component ID of the access checker.
112
     * If not set the application auth manager will be used.
113
     * @since 2.0.9
114
     */
115
    public $accessChecker;
116
    /**
117
     * @var int|null the number of seconds in which the user will be logged out automatically
118
     * regardless of activity.
119
     * Note that this will not work if [[enableAutoLogin]] is `true`.
120
     */
121
    public $absoluteAuthTimeout;
122
    /**
123
     * @var bool whether to automatically renew the identity cookie each time a page is requested.
124
     * This property is effective only when [[enableAutoLogin]] is `true`.
125
     * When this is `false`, the identity cookie will expire after the specified duration since the user
126
     * is initially logged in. When this is `true`, the identity cookie will expire after the specified duration
127
     * since the user visits the site the last time.
128
     * @see enableAutoLogin
129
     */
130
    public $autoRenewCookie = true;
131
    /**
132
     * @var string the session variable name used to store the value of [[id]].
133
     */
134
    public $idParam = '__id';
135
    /**
136
     * @var string the session variable name used to store authentication key.
137
     * @since 2.0.41
138
     */
139
    public $authKeyParam = '__authKey';
140
    /**
141
     * @var string the session variable name used to store the value of expiration timestamp of the authenticated state.
142
     * This is used when [[authTimeout]] is set.
143
     */
144
    public $authTimeoutParam = '__expire';
145
    /**
146
     * @var string the session variable name used to store the value of absolute expiration timestamp of the authenticated state.
147
     * This is used when [[absoluteAuthTimeout]] is set.
148
     */
149
    public $absoluteAuthTimeoutParam = '__absoluteExpire';
150
    /**
151
     * @var string the session variable name used to store the value of [[returnUrl]].
152
     */
153
    public $returnUrlParam = '__returnUrl';
154
    /**
155
     * @var array MIME types for which this component should redirect to the [[loginUrl]].
156
     * @since 2.0.8
157
     */
158
    public $acceptableRedirectTypes = ['text/html', 'application/xhtml+xml'];
159
160
    private $_access = [];
161
162
163
    /**
164
     * Initializes the application component.
165
     */
166 115
    public function init()
167
    {
168 115
        parent::init();
169
170 115
        if ($this->identityClass === null) {
171
            throw new InvalidConfigException('User::identityClass must be set.');
172
        }
173 115
        if ($this->enableAutoLogin && !isset($this->identityCookie['name'])) {
174
            throw new InvalidConfigException('User::identityCookie must contain the "name" element.');
175
        }
176 115
        if ($this->accessChecker !== null) {
177 1
            $this->accessChecker = Instance::ensure($this->accessChecker, '\yii\rbac\CheckAccessInterface');
178
        }
179
    }
180
181
    private $_identity = false;
182
183
    /**
184
     * Returns the identity object associated with the currently logged-in user.
185
     * When [[enableSession]] is true, this method may attempt to read the user's authentication data
186
     * stored in session and reconstruct the corresponding identity object, if it has not done so before.
187
     * @param bool $autoRenew whether to automatically renew authentication status if it has not been done so before.
188
     * This is only useful when [[enableSession]] is true.
189
     * @return IdentityInterface|null the identity object associated with the currently logged-in user.
190
     * `null` is returned if the user is not logged in (not authenticated).
191
     * @see login()
192
     * @see logout()
193
     */
194 96
    public function getIdentity($autoRenew = true)
195
    {
196 96
        if ($this->_identity === false) {
197 40
            if ($this->enableSession && $autoRenew) {
198
                try {
199 38
                    $this->_identity = null;
200 38
                    $this->renewAuthStatus();
201 1
                } catch (\Exception $e) {
202 1
                    $this->_identity = false;
203 1
                    throw $e;
204
                } catch (\Throwable $e) {
205
                    $this->_identity = false;
206 37
                    throw $e;
207
                }
208
            } else {
209 2
                return null;
210
            }
211
        }
212
213 93
        return $this->_identity;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->_identity also could return the type true which is incompatible with the documented return type null|yii\web\IdentityInterface.
Loading history...
214
    }
215
216
    /**
217
     * Sets the user identity object.
218
     *
219
     * Note that this method does not deal with session or cookie. You should usually use [[switchIdentity()]]
220
     * to change the identity of the current user.
221
     *
222
     * @param IdentityInterface|null $identity the identity object associated with the currently logged user.
223
     * If null, it means the current user will be a guest without any associated identity.
224
     * @throws InvalidValueException if `$identity` object does not implement [[IdentityInterface]].
225
     */
226 93
    public function setIdentity($identity)
227
    {
228 93
        if ($identity instanceof IdentityInterface) {
229 62
            $this->_identity = $identity;
230 42
        } elseif ($identity === null) {
0 ignored issues
show
introduced by
The condition $identity === null is always true.
Loading history...
231 42
            $this->_identity = null;
232
        } else {
233 1
            throw new InvalidValueException('The identity object must implement IdentityInterface.');
234
        }
235 93
        $this->_access = [];
236
    }
237
238
    /**
239
     * Logs in a user.
240
     *
241
     * After logging in a user:
242
     * - the user's identity information is obtainable from the [[identity]] property
243
     *
244
     * If [[enableSession]] is `true`:
245
     * - the identity information will be stored in session and be available in the next requests
246
     * - in case of `$duration == 0`: as long as the session remains active or till the user closes the browser
247
     * - in case of `$duration > 0`: as long as the session remains active or as long as the cookie
248
     *   remains valid by it's `$duration` in seconds when [[enableAutoLogin]] is set `true`.
249
     *
250
     * If [[enableSession]] is `false`:
251
     * - the `$duration` parameter will be ignored
252
     *
253
     * @param IdentityInterface $identity the user identity (which should already be authenticated)
254
     * @param int $duration number of seconds that the user can remain in logged-in status, defaults to `0`
255
     * @return bool whether the user is logged in
256
     */
257 43
    public function login(IdentityInterface $identity, $duration = 0)
258
    {
259 43
        if ($this->beforeLogin($identity, false, $duration)) {
260 43
            $this->switchIdentity($identity, $duration);
261 43
            $id = $identity->getId();
262 43
            $ip = Yii::$app->getRequest()->getUserIP();
0 ignored issues
show
Bug introduced by
The method getUserIP() does not exist on yii\console\Request. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

262
            $ip = Yii::$app->getRequest()->/** @scrutinizer ignore-call */ getUserIP();
Loading history...
263 43
            if ($this->enableSession) {
264 43
                $log = "User '$id' logged in from $ip with duration $duration.";
265
            } else {
266
                $log = "User '$id' logged in from $ip. Session not enabled.";
267
            }
268
269 43
            $this->regenerateCsrfToken();
270
271 43
            Yii::info($log, __METHOD__);
272 43
            $this->afterLogin($identity, false, $duration);
273
        }
274
275 43
        return !$this->getIsGuest();
276
    }
277
278
    /**
279
     * Regenerates CSRF token
280
     *
281
     * @since 2.0.14.2
282
     */
283 43
    protected function regenerateCsrfToken()
284
    {
285 43
        $request = Yii::$app->getRequest();
286 43
        if ($request->enableCsrfCookie || $this->enableSession) {
0 ignored issues
show
Bug Best Practice introduced by
The property enableCsrfCookie does not exist on yii\console\Request. Since you implemented __get, consider adding a @property annotation.
Loading history...
287 43
            $request->getCsrfToken(true);
0 ignored issues
show
Bug introduced by
The method getCsrfToken() does not exist on yii\console\Request. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

287
            $request->/** @scrutinizer ignore-call */ 
288
                      getCsrfToken(true);
Loading history...
288
        }
289
    }
290
291
    /**
292
     * Logs in a user by the given access token.
293
     * This method will first authenticate the user by calling [[IdentityInterface::findIdentityByAccessToken()]]
294
     * with the provided access token. If successful, it will call [[login()]] to log in the authenticated user.
295
     * If authentication fails or [[login()]] is unsuccessful, it will return null.
296
     * @param string $token the access token
297
     * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
298
     * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
299
     * @return IdentityInterface|null the identity associated with the given access token. Null is returned if
300
     * the access token is invalid or [[login()]] is unsuccessful.
301
     */
302 42
    public function loginByAccessToken($token, $type = null)
303
    {
304
        /* @var $class IdentityInterface */
305 42
        $class = $this->identityClass;
306 42
        $identity = $class::findIdentityByAccessToken($token, $type);
307 42
        if ($identity && $this->login($identity)) {
308 27
            return $identity;
309
        }
310
311 15
        return null;
312
    }
313
314
    /**
315
     * Logs in a user by cookie.
316
     *
317
     * This method attempts to log in a user using the ID and authKey information
318
     * provided by the [[identityCookie|identity cookie]].
319
     */
320 2
    protected function loginByCookie()
321
    {
322 2
        $data = $this->getIdentityAndDurationFromCookie();
323 2
        if (isset($data['identity'], $data['duration'])) {
324 1
            $identity = $data['identity'];
325 1
            $duration = $data['duration'];
326 1
            if ($this->beforeLogin($identity, true, $duration)) {
327 1
                $this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);
328 1
                $id = $identity->getId();
329 1
                $ip = Yii::$app->getRequest()->getUserIP();
330 1
                Yii::info("User '$id' logged in from $ip via cookie.", __METHOD__);
331 1
                $this->afterLogin($identity, true, $duration);
332
            }
333
        }
334
    }
335
336
    /**
337
     * Logs out the current user.
338
     * This will remove authentication-related session data.
339
     * If `$destroySession` is true, all session data will be removed.
340
     * @param bool $destroySession whether to destroy the whole session. Defaults to true.
341
     * This parameter is ignored if [[enableSession]] is false.
342
     * @return bool whether the user is logged out
343
     */
344 1
    public function logout($destroySession = true)
345
    {
346 1
        $identity = $this->getIdentity();
347 1
        if ($identity !== null && $this->beforeLogout($identity)) {
348 1
            $this->switchIdentity(null);
349 1
            $id = $identity->getId();
350 1
            $ip = Yii::$app->getRequest()->getUserIP();
351 1
            Yii::info("User '$id' logged out from $ip.", __METHOD__);
352 1
            if ($destroySession && $this->enableSession) {
353
                Yii::$app->getSession()->destroy();
0 ignored issues
show
Bug introduced by
The method getSession() does not exist on yii\console\Application. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

353
                Yii::$app->/** @scrutinizer ignore-call */ 
354
                           getSession()->destroy();
Loading history...
354
            }
355 1
            $this->afterLogout($identity);
356
        }
357
358 1
        return $this->getIsGuest();
359
    }
360
361
    /**
362
     * Returns a value indicating whether the user is a guest (not authenticated).
363
     * @return bool whether the current user is a guest.
364
     * @see getIdentity()
365
     */
366 44
    public function getIsGuest()
367
    {
368 44
        return $this->getIdentity() === null;
369
    }
370
371
    /**
372
     * Returns a value that uniquely represents the user.
373
     * @return string|int|null the unique identifier for the user. If `null`, it means the user is a guest.
374
     * @see getIdentity()
375
     */
376 84
    public function getId()
377
    {
378 84
        $identity = $this->getIdentity();
379
380 84
        return $identity !== null ? $identity->getId() : null;
381
    }
382
383
    /**
384
     * Returns the URL that the browser should be redirected to after successful login.
385
     *
386
     * This method reads the return URL from the session. It is usually used by the login action which
387
     * may call this method to redirect the browser to where it goes after successful authentication.
388
     *
389
     * @param string|array|null $defaultUrl the default return URL in case it was not set previously.
390
     * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
391
     * Please refer to [[setReturnUrl()]] on accepted format of the URL.
392
     * @return string the URL that the user should be redirected to after login.
393
     * @see loginRequired()
394
     */
395 3
    public function getReturnUrl($defaultUrl = null)
396
    {
397 3
        $url = Yii::$app->getSession()->get($this->returnUrlParam, $defaultUrl);
398 3
        if (is_array($url)) {
399
            if (isset($url[0])) {
400
                return Yii::$app->getUrlManager()->createUrl($url);
401
            }
402
403
            $url = null;
404
        }
405
406 3
        return $url === null ? Yii::$app->getHomeUrl() : $url;
0 ignored issues
show
Bug introduced by
The method getHomeUrl() does not exist on yii\console\Application. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

406
        return $url === null ? Yii::$app->/** @scrutinizer ignore-call */ getHomeUrl() : $url;
Loading history...
407
    }
408
409
    /**
410
     * Remembers the URL in the session so that it can be retrieved back later by [[getReturnUrl()]].
411
     * @param string|array $url the URL that the user should be redirected to after login.
412
     * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
413
     * The first element of the array should be the route, and the rest of
414
     * the name-value pairs are GET parameters used to construct the URL. For example,
415
     *
416
     * ```php
417
     * ['admin/index', 'ref' => 1]
418
     * ```
419
     */
420 3
    public function setReturnUrl($url)
421
    {
422 3
        Yii::$app->getSession()->set($this->returnUrlParam, $url);
423
    }
424
425
    /**
426
     * Redirects the user browser to the login page.
427
     *
428
     * Before the redirection, the current URL (if it's not an AJAX url) will be kept as [[returnUrl]] so that
429
     * the user browser may be redirected back to the current page after successful login.
430
     *
431
     * Make sure you set [[loginUrl]] so that the user browser can be redirected to the specified login URL after
432
     * calling this method.
433
     *
434
     * Note that when [[loginUrl]] is set, calling this method will NOT terminate the application execution.
435
     *
436
     * @param bool $checkAjax whether to check if the request is an AJAX request. When this is true and the request
437
     * is an AJAX request, the current URL (for AJAX request) will NOT be set as the return URL.
438
     * @param bool $checkAcceptHeader whether to check if the request accepts HTML responses. Defaults to `true`. When this is true and
439
     * the request does not accept HTML responses the current URL will not be SET as the return URL. Also instead of
440
     * redirecting the user an ForbiddenHttpException is thrown. This parameter is available since version 2.0.8.
441
     * @return Response the redirection response if [[loginUrl]] is set
442
     * @throws ForbiddenHttpException the "Access Denied" HTTP exception if [[loginUrl]] is not set or a redirect is
443
     * not applicable.
444
     */
445 2
    public function loginRequired($checkAjax = true, $checkAcceptHeader = true)
446
    {
447 2
        $request = Yii::$app->getRequest();
448 2
        $canRedirect = !$checkAcceptHeader || $this->checkRedirectAcceptable();
449
        if (
450 2
            $this->enableSession
451 2
            && $request->getIsGet()
0 ignored issues
show
Bug introduced by
The method getIsGet() does not exist on yii\console\Request. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

451
            && $request->/** @scrutinizer ignore-call */ getIsGet()
Loading history...
452 2
            && (!$checkAjax || !$request->getIsAjax())
0 ignored issues
show
Bug introduced by
The method getIsAjax() does not exist on yii\console\Request. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

452
            && (!$checkAjax || !$request->/** @scrutinizer ignore-call */ getIsAjax())
Loading history...
453
            && $canRedirect
454
        ) {
455 1
            $this->setReturnUrl($request->getAbsoluteUrl());
0 ignored issues
show
Bug introduced by
The method getAbsoluteUrl() does not exist on yii\console\Request. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

455
            $this->setReturnUrl($request->/** @scrutinizer ignore-call */ getAbsoluteUrl());
Loading history...
456
        }
457 2
        if ($this->loginUrl !== null && $canRedirect) {
458 1
            $loginUrl = (array) $this->loginUrl;
459 1
            if ($loginUrl[0] !== Yii::$app->requestedRoute) {
460 1
                return Yii::$app->getResponse()->redirect($this->loginUrl);
0 ignored issues
show
Bug Best Practice introduced by
The expression return Yii::app->getResp...direct($this->loginUrl) also could return the type yii\console\Response which is incompatible with the documented return type yii\web\Response.
Loading history...
Bug introduced by
The method redirect() does not exist on yii\console\Response. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

460
                return Yii::$app->getResponse()->/** @scrutinizer ignore-call */ redirect($this->loginUrl);
Loading history...
461
            }
462
        }
463 2
        throw new ForbiddenHttpException(Yii::t('yii', 'Login Required'));
464
    }
465
466
    /**
467
     * This method is called before logging in a user.
468
     * The default implementation will trigger the [[EVENT_BEFORE_LOGIN]] event.
469
     * If you override this method, make sure you call the parent implementation
470
     * so that the event is triggered.
471
     * @param IdentityInterface $identity the user identity information
472
     * @param bool $cookieBased whether the login is cookie-based
473
     * @param int $duration number of seconds that the user can remain in logged-in status.
474
     * If 0, it means login till the user closes the browser or the session is manually destroyed.
475
     * @return bool whether the user should continue to be logged in
476
     */
477 43
    protected function beforeLogin($identity, $cookieBased, $duration)
478
    {
479 43
        $event = new UserEvent([
480 43
            'identity' => $identity,
481 43
            'cookieBased' => $cookieBased,
482 43
            'duration' => $duration,
483 43
        ]);
484 43
        $this->trigger(self::EVENT_BEFORE_LOGIN, $event);
485
486 43
        return $event->isValid;
487
    }
488
489
    /**
490
     * This method is called after the user is successfully logged in.
491
     * The default implementation will trigger the [[EVENT_AFTER_LOGIN]] event.
492
     * If you override this method, make sure you call the parent implementation
493
     * so that the event is triggered.
494
     * @param IdentityInterface $identity the user identity information
495
     * @param bool $cookieBased whether the login is cookie-based
496
     * @param int $duration number of seconds that the user can remain in logged-in status.
497
     * If 0, it means login till the user closes the browser or the session is manually destroyed.
498
     */
499 43
    protected function afterLogin($identity, $cookieBased, $duration)
500
    {
501 43
        $this->trigger(self::EVENT_AFTER_LOGIN, new UserEvent([
502 43
            'identity' => $identity,
503 43
            'cookieBased' => $cookieBased,
504 43
            'duration' => $duration,
505 43
        ]));
506
    }
507
508
    /**
509
     * This method is invoked when calling [[logout()]] to log out a user.
510
     * The default implementation will trigger the [[EVENT_BEFORE_LOGOUT]] event.
511
     * If you override this method, make sure you call the parent implementation
512
     * so that the event is triggered.
513
     * @param IdentityInterface $identity the user identity information
514
     * @return bool whether the user should continue to be logged out
515
     */
516 1
    protected function beforeLogout($identity)
517
    {
518 1
        $event = new UserEvent([
519 1
            'identity' => $identity,
520 1
        ]);
521 1
        $this->trigger(self::EVENT_BEFORE_LOGOUT, $event);
522
523 1
        return $event->isValid;
524
    }
525
526
    /**
527
     * This method is invoked right after a user is logged out via [[logout()]].
528
     * The default implementation will trigger the [[EVENT_AFTER_LOGOUT]] event.
529
     * If you override this method, make sure you call the parent implementation
530
     * so that the event is triggered.
531
     * @param IdentityInterface $identity the user identity information
532
     */
533 1
    protected function afterLogout($identity)
534
    {
535 1
        $this->trigger(self::EVENT_AFTER_LOGOUT, new UserEvent([
536 1
            'identity' => $identity,
537 1
        ]));
538
    }
539
540
    /**
541
     * Renews the identity cookie.
542
     * This method will set the expiration time of the identity cookie to be the current time
543
     * plus the originally specified cookie duration.
544
     */
545
    protected function renewIdentityCookie()
546
    {
547
        $name = $this->identityCookie['name'];
548
        $value = Yii::$app->getRequest()->getCookies()->getValue($name);
0 ignored issues
show
Bug introduced by
The method getCookies() does not exist on yii\console\Request. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

548
        $value = Yii::$app->getRequest()->/** @scrutinizer ignore-call */ getCookies()->getValue($name);
Loading history...
549
        if ($value !== null) {
550
            $data = json_decode($value, true);
551
            if (is_array($data) && isset($data[2])) {
552
                $cookie = Yii::createObject(array_merge($this->identityCookie, [
553
                    'class' => 'yii\web\Cookie',
554
                    'value' => $value,
555
                    'expire' => time() + (int) $data[2],
556
                ]));
557
                Yii::$app->getResponse()->getCookies()->add($cookie);
0 ignored issues
show
Bug introduced by
The method getCookies() does not exist on yii\console\Response. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

557
                Yii::$app->getResponse()->/** @scrutinizer ignore-call */ getCookies()->add($cookie);
Loading history...
558
            }
559
        }
560
    }
561
562
    /**
563
     * Sends an identity cookie.
564
     * This method is used when [[enableAutoLogin]] is true.
565
     * It saves [[id]], [[IdentityInterface::getAuthKey()|auth key]], and the duration of cookie-based login
566
     * information in the cookie.
567
     * @param IdentityInterface $identity
568
     * @param int $duration number of seconds that the user can remain in logged-in status.
569
     * @see loginByCookie()
570
     */
571 2
    protected function sendIdentityCookie($identity, $duration)
572
    {
573 2
        $cookie = Yii::createObject(array_merge($this->identityCookie, [
574 2
            'class' => 'yii\web\Cookie',
575 2
            'value' => json_encode([
576 2
                $identity->getId(),
577 2
                $identity->getAuthKey(),
578 2
                $duration,
579 2
            ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
580 2
            'expire' => time() + $duration,
581 2
        ]));
582 2
        Yii::$app->getResponse()->getCookies()->add($cookie);
583
    }
584
585
    /**
586
     * Determines if an identity cookie has a valid format and contains a valid auth key.
587
     * This method is used when [[enableAutoLogin]] is true.
588
     * This method attempts to authenticate a user using the information in the identity cookie.
589
     * @return array|null Returns an array of 'identity' and 'duration' if valid, otherwise null.
590
     * @see loginByCookie()
591
     * @since 2.0.9
592
     */
593 2
    protected function getIdentityAndDurationFromCookie()
594
    {
595 2
        $value = Yii::$app->getRequest()->getCookies()->getValue($this->identityCookie['name']);
596 2
        if ($value === null) {
597
            return null;
598
        }
599 2
        $data = json_decode($value, true);
600 2
        if (is_array($data) && count($data) == 3) {
601 1
            list($id, $authKey, $duration) = $data;
602
            /* @var $class IdentityInterface */
603 1
            $class = $this->identityClass;
604 1
            $identity = $class::findIdentity($id);
605 1
            if ($identity !== null) {
606 1
                if (!$identity instanceof IdentityInterface) {
0 ignored issues
show
introduced by
$identity is always a sub-type of yii\web\IdentityInterface.
Loading history...
607
                    throw new InvalidValueException("$class::findIdentity() must return an object implementing IdentityInterface.");
608 1
                } elseif (!$identity->validateAuthKey($authKey)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $identity->validateAuthKey($authKey) of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
609
                    $ip = Yii::$app->getRequest()->getUserIP();
610
                    Yii::warning("Invalid cookie auth key attempted for user '$id' from $ip: $authKey", __METHOD__);
611
                } else {
612 1
                    return ['identity' => $identity, 'duration' => $duration];
613
                }
614
            }
615
        }
616 2
        $this->removeIdentityCookie();
617 2
        return null;
618
    }
619
620
    /**
621
     * Removes the identity cookie.
622
     * This method is used when [[enableAutoLogin]] is true.
623
     * @since 2.0.9
624
     */
625 2
    protected function removeIdentityCookie()
626
    {
627 2
        Yii::$app->getResponse()->getCookies()->remove(Yii::createObject(array_merge($this->identityCookie, [
628 2
            'class' => 'yii\web\Cookie',
629 2
        ])));
630
    }
631
632
    /**
633
     * Switches to a new identity for the current user.
634
     *
635
     * When [[enableSession]] is true, this method may use session and/or cookie to store the user identity information,
636
     * according to the value of `$duration`. Please refer to [[login()]] for more details.
637
     *
638
     * This method is mainly called by [[login()]], [[logout()]] and [[loginByCookie()]]
639
     * when the current user needs to be associated with the corresponding identity information.
640
     *
641
     * @param IdentityInterface|null $identity the identity information to be associated with the current user.
642
     * If null, it means switching the current user to be a guest.
643
     * @param int $duration number of seconds that the user can remain in logged-in status.
644
     * This parameter is used only when `$identity` is not null.
645
     */
646 45
    public function switchIdentity($identity, $duration = 0)
647
    {
648 45
        $this->setIdentity($identity);
649
650 45
        if (!$this->enableSession) {
651
            return;
652
        }
653
654
        /* Ensure any existing identity cookies are removed. */
655 45
        if ($this->enableAutoLogin && ($this->autoRenewCookie || $identity === null)) {
656 1
            $this->removeIdentityCookie();
657
        }
658
659 45
        $session = Yii::$app->getSession();
660 45
        $session->regenerateID(true);
661 45
        $session->remove($this->idParam);
662 45
        $session->remove($this->authTimeoutParam);
663 45
        $session->remove($this->authKeyParam);
664
665 45
        if ($identity) {
666 43
            $session->set($this->idParam, $identity->getId());
667 43
            $session->set($this->authKeyParam, $identity->getAuthKey());
668 43
            if ($this->authTimeout !== null) {
669 2
                $session->set($this->authTimeoutParam, time() + $this->authTimeout);
670
            }
671 43
            if ($this->absoluteAuthTimeout !== null) {
672
                $session->set($this->absoluteAuthTimeoutParam, time() + $this->absoluteAuthTimeout);
673
            }
674 43
            if ($this->enableAutoLogin && $duration > 0) {
675 2
                $this->sendIdentityCookie($identity, $duration);
676
            }
677
        }
678
    }
679
680
    /**
681
     * Updates the authentication status using the information from session and cookie.
682
     *
683
     * This method will try to determine the user identity using the [[idParam]] session variable.
684
     *
685
     * If [[authTimeout]] is set, this method will refresh the timer.
686
     *
687
     * If the user identity cannot be determined by session, this method will try to [[loginByCookie()|login by cookie]]
688
     * if [[enableAutoLogin]] is true.
689
     */
690 38
    protected function renewAuthStatus()
691
    {
692 38
        $session = Yii::$app->getSession();
693 38
        $id = $session->getHasSessionId() || $session->getIsActive() ? $session->get($this->idParam) : null;
694
695 38
        if ($id === null) {
696 31
            $identity = null;
697
        } else {
698
            /* @var $class IdentityInterface */
699 8
            $class = $this->identityClass;
700 8
            $identity = $class::findIdentity($id);
701 7
            if ($identity === null) {
702 2
                $this->switchIdentity(null);
703
            }
704
        }
705
706 37
        if ($identity !== null) {
707 5
            $authKey = $session->get($this->authKeyParam);
708 5
            if ($authKey !== null && !$identity->validateAuthKey($authKey)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $identity->validateAuthKey($authKey) of type boolean|null is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
709 1
                $identity = null;
710 1
                $ip = Yii::$app->getRequest()->getUserIP();
711 1
                Yii::warning("Invalid session auth key attempted for user '$id' from $ip: $authKey", __METHOD__);
712
            }
713
        }
714
715 37
        $this->setIdentity($identity);
716
717 37
        if ($identity !== null && ($this->authTimeout !== null || $this->absoluteAuthTimeout !== null)) {
718 2
            $expire = $this->authTimeout !== null ? $session->get($this->authTimeoutParam) : null;
719 2
            $expireAbsolute = $this->absoluteAuthTimeout !== null ? $session->get($this->absoluteAuthTimeoutParam) : null;
720 2
            if ($expire !== null && $expire < time() || $expireAbsolute !== null && $expireAbsolute < time()) {
0 ignored issues
show
introduced by
Consider adding parentheses for clarity. Current Interpretation: ($expire !== null && $ex...expireAbsolute < time(), Probably Intended Meaning: $expire !== null && ($ex...xpireAbsolute < time())
Loading history...
721 1
                $this->logout(false);
722 2
            } elseif ($this->authTimeout !== null) {
723 2
                $session->set($this->authTimeoutParam, time() + $this->authTimeout);
724
            }
725
        }
726
727 37
        if ($this->enableAutoLogin) {
728 2
            if ($this->getIsGuest()) {
729 2
                $this->loginByCookie();
730 1
            } elseif ($this->autoRenewCookie) {
731
                $this->renewIdentityCookie();
732
            }
733
        }
734
    }
735
736
    /**
737
     * Checks if the user can perform the operation as specified by the given permission.
738
     *
739
     * Note that you must configure "authManager" application component in order to use this method.
740
     * Otherwise it will always return false.
741
     *
742
     * @param string $permissionName the name of the permission (e.g. "edit post") that needs access check.
743
     * @param array $params name-value pairs that would be passed to the rules associated
744
     * with the roles and permissions assigned to the user.
745
     * @param bool $allowCaching whether to allow caching the result of access check.
746
     * When this parameter is true (default), if the access check of an operation was performed
747
     * before, its result will be directly returned when calling this method to check the same
748
     * operation. If this parameter is false, this method will always call
749
     * [[\yii\rbac\CheckAccessInterface::checkAccess()]] to obtain the up-to-date access result. Note that this
750
     * caching is effective only within the same request and only works when `$params = []`.
751
     * @return bool whether the user can perform the operation as specified by the given permission.
752
     */
753 23
    public function can($permissionName, $params = [], $allowCaching = true)
754
    {
755 23
        if ($allowCaching && empty($params) && isset($this->_access[$permissionName])) {
756
            return $this->_access[$permissionName];
757
        }
758 23
        if (($accessChecker = $this->getAccessChecker()) === null) {
759
            return false;
760
        }
761 23
        $access = $accessChecker->checkAccess($this->getId(), $permissionName, $params);
762 23
        if ($allowCaching && empty($params)) {
763 10
            $this->_access[$permissionName] = $access;
764
        }
765
766 23
        return $access;
767
    }
768
769
    /**
770
     * Checks if the `Accept` header contains a content type that allows redirection to the login page.
771
     * The login page is assumed to serve `text/html` or `application/xhtml+xml` by default. You can change acceptable
772
     * content types by modifying [[acceptableRedirectTypes]] property.
773
     * @return bool whether this request may be redirected to the login page.
774
     * @see acceptableRedirectTypes
775
     * @since 2.0.8
776
     */
777 2
    public function checkRedirectAcceptable()
778
    {
779 2
        $acceptableTypes = Yii::$app->getRequest()->getAcceptableContentTypes();
0 ignored issues
show
Bug introduced by
The method getAcceptableContentTypes() does not exist on yii\console\Request. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

779
        $acceptableTypes = Yii::$app->getRequest()->/** @scrutinizer ignore-call */ getAcceptableContentTypes();
Loading history...
780 2
        if (empty($acceptableTypes) || (count($acceptableTypes) === 1 && array_keys($acceptableTypes)[0] === '*/*')) {
781 1
            return true;
782
        }
783
784 2
        foreach ($acceptableTypes as $type => $params) {
785 2
            if (in_array($type, $this->acceptableRedirectTypes, true)) {
786 1
                return true;
787
            }
788
        }
789
790 2
        return false;
791
    }
792
793
    /**
794
     * Returns auth manager associated with the user component.
795
     *
796
     * By default this is the `authManager` application component.
797
     * You may override this method to return a different auth manager instance if needed.
798
     * @return \yii\rbac\ManagerInterface
799
     * @since 2.0.6
800
     * @deprecated since version 2.0.9, to be removed in 2.1. Use [[getAccessChecker()]] instead.
801
     */
802 2
    protected function getAuthManager()
803
    {
804 2
        return Yii::$app->getAuthManager();
805
    }
806
807
    /**
808
     * Returns the access checker used for checking access.
809
     * @return CheckAccessInterface
810
     * @since 2.0.9
811
     */
812 23
    protected function getAccessChecker()
813
    {
814 23
        return $this->accessChecker !== null ? $this->accessChecker : $this->getAuthManager();
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->accessChec...$this->getAuthManager() also could return the type array|string which is incompatible with the documented return type yii\rbac\CheckAccessInterface.
Loading history...
Deprecated Code introduced by
The function yii\web\User::getAuthManager() has been deprecated: since version 2.0.9, to be removed in 2.1. Use [[getAccessChecker()]] instead. ( Ignorable by Annotation )

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

814
        return $this->accessChecker !== null ? $this->accessChecker : /** @scrutinizer ignore-deprecated */ $this->getAuthManager();

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
815
    }
816
}
817