Passed
Push — master ( 9dbdd9...d5a428 )
by Alexander
04:15
created

framework/web/User.php (1 issue)

1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\web;
9
10
use Yii;
11
use yii\base\Component;
12
use yii\base\InvalidConfigException;
13
use yii\base\InvalidValueException;
14
use yii\di\Instance;
15
use yii\rbac\CheckAccessInterface;
16
17
/**
18
 * User is the class for the `user` application component that manages the user authentication status.
19
 *
20
 * You may use [[isGuest]] to determine whether the current user is a guest or not.
21
 * If the user is a guest, the [[identity]] property would return `null`. Otherwise, it would
22
 * be an instance of [[IdentityInterface]].
23
 *
24
 * You may call various methods to change the user authentication status:
25
 *
26
 * - [[login()]]: sets the specified identity and remembers the authentication status in session and cookie;
27
 * - [[logout()]]: marks the user as a guest and clears the relevant information from session and cookie;
28
 * - [[setIdentity()]]: changes the user identity without touching session or cookie
29
 *   (this is best used in stateless RESTful API implementation).
30
 *
31
 * Note that User only maintains the user authentication status. It does NOT handle how to authenticate
32
 * a user. The logic of how to authenticate a user should be done in the class implementing [[IdentityInterface]].
33
 * You are also required to set [[identityClass]] with the name of this class.
34
 *
35
 * User is configured as an application component in [[\yii\web\Application]] by default.
36
 * You can access that instance via `Yii::$app->user`.
37
 *
38
 * You can modify its configuration by adding an array to your application config under `components`
39
 * as it is shown in the following example:
40
 *
41
 * ```php
42
 * 'user' => [
43
 *     'identityClass' => 'app\models\User', // User must implement the IdentityInterface
44
 *     'enableAutoLogin' => true,
45
 *     // 'loginUrl' => ['user/login'],
46
 *     // ...
47
 * ]
48
 * ```
49
 *
50
 * @property-read string|int $id The unique identifier for the user. If `null`, it means the user is a guest.
51
 * This property is read-only.
52
 * @property IdentityInterface|null $identity The identity object associated with the currently logged-in
53
 * user. `null` is returned if the user is not logged in (not authenticated).
54
 * @property-read bool $isGuest Whether the current user is a guest. This property is read-only.
55
 * @property string $returnUrl The URL that the user should be redirected to after login. Note that the type
56
 * of this property differs in getter and setter. See [[getReturnUrl()]] and [[setReturnUrl()]] for details.
57
 *
58
 * @author Qiang Xue <[email protected]>
59
 * @since 2.0
60
 */
61
class User extends Component
62
{
63
    const EVENT_BEFORE_LOGIN = 'beforeLogin';
64
    const EVENT_AFTER_LOGIN = 'afterLogin';
65
    const EVENT_BEFORE_LOGOUT = 'beforeLogout';
66
    const EVENT_AFTER_LOGOUT = 'afterLogout';
67
68
    /**
69
     * @var string the class name of the [[identity]] object.
70
     */
71
    public $identityClass;
72
    /**
73
     * @var bool whether to enable cookie-based login. Defaults to `false`.
74
     * Note that this property will be ignored if [[enableSession]] is `false`.
75
     */
76
    public $enableAutoLogin = false;
77
    /**
78
     * @var bool whether to use session to persist authentication status across multiple requests.
79
     * You set this property to be `false` if your application is stateless, which is often the case
80
     * for RESTful APIs.
81
     */
82
    public $enableSession = true;
83
    /**
84
     * @var string|array the URL for login when [[loginRequired()]] is called.
85
     * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
86
     * The first element of the array should be the route to the login action, and the rest of
87
     * the name-value pairs are GET parameters used to construct the login URL. For example,
88
     *
89
     * ```php
90
     * ['site/login', 'ref' => 1]
91
     * ```
92
     *
93
     * If this property is `null`, a 403 HTTP exception will be raised when [[loginRequired()]] is called.
94
     */
95
    public $loginUrl = ['site/login'];
96
    /**
97
     * @var array the configuration of the identity cookie. This property is used only when [[enableAutoLogin]] is `true`.
98
     * @see Cookie
99
     */
100
    public $identityCookie = ['name' => '_identity', 'httpOnly' => true];
101
    /**
102
     * @var int the number of seconds in which the user will be logged out automatically if he
103
     * remains inactive. If this property is not set, the user will be logged out after
104
     * the current session expires (c.f. [[Session::timeout]]).
105
     * Note that this will not work if [[enableAutoLogin]] is `true`.
106
     */
107
    public $authTimeout;
108
    /**
109
     * @var CheckAccessInterface|string|array The access checker object to use for checking access or the application
110
     * component ID of the access checker.
111
     * If not set the application auth manager will be used.
112
     * @since 2.0.9
113
     */
114
    public $accessChecker;
115
    /**
116
     * @var int the number of seconds in which the user will be logged out automatically
117
     * regardless of activity.
118
     * Note that this will not work if [[enableAutoLogin]] is `true`.
119
     */
120
    public $absoluteAuthTimeout;
121
    /**
122
     * @var bool whether to automatically renew the identity cookie each time a page is requested.
123
     * This property is effective only when [[enableAutoLogin]] is `true`.
124
     * When this is `false`, the identity cookie will expire after the specified duration since the user
125
     * is initially logged in. When this is `true`, the identity cookie will expire after the specified duration
126
     * since the user visits the site the last time.
127
     * @see enableAutoLogin
128
     */
129
    public $autoRenewCookie = true;
130
    /**
131
     * @var string the session variable name used to store the value of [[id]].
132
     */
133
    public $idParam = '__id';
134
    /**
135
     * @var string the session variable name used to store authentication key.
136
     * @since 2.0.41
137
     */
138
    public $authKeyParam = '__authKey';
139
    /**
140
     * @var string the session variable name used to store the value of expiration timestamp of the authenticated state.
141
     * This is used when [[authTimeout]] is set.
142
     */
143
    public $authTimeoutParam = '__expire';
144
    /**
145
     * @var string the session variable name used to store the value of absolute expiration timestamp of the authenticated state.
146
     * This is used when [[absoluteAuthTimeout]] is set.
147
     */
148
    public $absoluteAuthTimeoutParam = '__absoluteExpire';
149
    /**
150
     * @var string the session variable name used to store the value of [[returnUrl]].
151
     */
152
    public $returnUrlParam = '__returnUrl';
153
    /**
154
     * @var array MIME types for which this component should redirect to the [[loginUrl]].
155
     * @since 2.0.8
156
     */
157
    public $acceptableRedirectTypes = ['text/html', 'application/xhtml+xml'];
158
159
    private $_access = [];
160
161
162
    /**
163
     * Initializes the application component.
164
     */
165 105
    public function init()
166
    {
167 105
        parent::init();
168
169 105
        if ($this->identityClass === null) {
170
            throw new InvalidConfigException('User::identityClass must be set.');
171
        }
172 105
        if ($this->enableAutoLogin && !isset($this->identityCookie['name'])) {
173
            throw new InvalidConfigException('User::identityCookie must contain the "name" element.');
174
        }
175 105
        if ($this->accessChecker !== null) {
176 1
            $this->accessChecker = Instance::ensure($this->accessChecker, '\yii\rbac\CheckAccessInterface');
177
        }
178 105
    }
179
180
    private $_identity = false;
181
182
    /**
183
     * Returns the identity object associated with the currently logged-in user.
184
     * When [[enableSession]] is true, this method may attempt to read the user's authentication data
185
     * stored in session and reconstruct the corresponding identity object, if it has not done so before.
186
     * @param bool $autoRenew whether to automatically renew authentication status if it has not been done so before.
187
     * This is only useful when [[enableSession]] is true.
188
     * @return IdentityInterface|null the identity object associated with the currently logged-in user.
189
     * `null` is returned if the user is not logged in (not authenticated).
190
     * @see login()
191
     * @see logout()
192
     */
193 94
    public function getIdentity($autoRenew = true)
194
    {
195 94
        if ($this->_identity === false) {
196 41
            if ($this->enableSession && $autoRenew) {
197
                try {
198 39
                    $this->_identity = null;
199 39
                    $this->renewAuthStatus();
200 1
                } catch (\Exception $e) {
201 1
                    $this->_identity = false;
202 1
                    throw $e;
203
                } catch (\Throwable $e) {
204
                    $this->_identity = false;
205 38
                    throw $e;
206
                }
207
            } else {
208 2
                return null;
209
            }
210
        }
211
212 91
        return $this->_identity;
213
    }
214
215
    /**
216
     * Sets the user identity object.
217
     *
218
     * Note that this method does not deal with session or cookie. You should usually use [[switchIdentity()]]
219
     * to change the identity of the current user.
220
     *
221
     * @param IdentityInterface|null $identity the identity object associated with the currently logged user.
222
     * If null, it means the current user will be a guest without any associated identity.
223
     * @throws InvalidValueException if `$identity` object does not implement [[IdentityInterface]].
224
     */
225 91
    public function setIdentity($identity)
226
    {
227 91
        if ($identity instanceof IdentityInterface) {
228 59
            $this->_identity = $identity;
229 43
        } elseif ($identity === null) {
230 43
            $this->_identity = null;
231
        } else {
232 1
            throw new InvalidValueException('The identity object must implement IdentityInterface.');
233
        }
234 91
        $this->_access = [];
235 91
    }
236
237
    /**
238
     * Logs in a user.
239
     *
240
     * After logging in a user:
241
     * - the user's identity information is obtainable from the [[identity]] property
242
     *
243
     * If [[enableSession]] is `true`:
244
     * - the identity information will be stored in session and be available in the next requests
245
     * - in case of `$duration == 0`: as long as the session remains active or till the user closes the browser
246
     * - in case of `$duration > 0`: as long as the session remains active or as long as the cookie
247
     *   remains valid by it's `$duration` in seconds when [[enableAutoLogin]] is set `true`.
248
     *
249
     * If [[enableSession]] is `false`:
250
     * - the `$duration` parameter will be ignored
251
     *
252
     * @param IdentityInterface $identity the user identity (which should already be authenticated)
253
     * @param int $duration number of seconds that the user can remain in logged-in status, defaults to `0`
254
     * @return bool whether the user is logged in
255
     */
256 40
    public function login(IdentityInterface $identity, $duration = 0)
257
    {
258 40
        if ($this->beforeLogin($identity, false, $duration)) {
259 40
            $this->switchIdentity($identity, $duration);
260 40
            $id = $identity->getId();
261 40
            $ip = Yii::$app->getRequest()->getUserIP();
262 40
            if ($this->enableSession) {
263 40
                $log = "User '$id' logged in from $ip with duration $duration.";
264
            } else {
265
                $log = "User '$id' logged in from $ip. Session not enabled.";
266
            }
267
268 40
            $this->regenerateCsrfToken();
269
270 40
            Yii::info($log, __METHOD__);
271 40
            $this->afterLogin($identity, false, $duration);
272
        }
273
274 40
        return !$this->getIsGuest();
275
    }
276
277
    /**
278
     * Regenerates CSRF token
279
     *
280
     * @since 2.0.14.2
281
     */
282 40
    protected function regenerateCsrfToken()
283
    {
284 40
        $request = Yii::$app->getRequest();
285 40
        if ($request->enableCsrfCookie || $this->enableSession) {
286 40
            $request->getCsrfToken(true);
287
        }
288 40
    }
289
290
    /**
291
     * Logs in a user by the given access token.
292
     * This method will first authenticate the user by calling [[IdentityInterface::findIdentityByAccessToken()]]
293
     * with the provided access token. If successful, it will call [[login()]] to log in the authenticated user.
294
     * If authentication fails or [[login()]] is unsuccessful, it will return null.
295
     * @param string $token the access token
296
     * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
297
     * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
298
     * @return IdentityInterface|null the identity associated with the given access token. Null is returned if
299
     * the access token is invalid or [[login()]] is unsuccessful.
300
     */
301 42
    public function loginByAccessToken($token, $type = null)
302
    {
303
        /* @var $class IdentityInterface */
304 42
        $class = $this->identityClass;
305 42
        $identity = $class::findIdentityByAccessToken($token, $type);
306 42
        if ($identity && $this->login($identity)) {
307 27
            return $identity;
308
        }
309
310 15
        return null;
311
    }
312
313
    /**
314
     * Logs in a user by cookie.
315
     *
316
     * This method attempts to log in a user using the ID and authKey information
317
     * provided by the [[identityCookie|identity cookie]].
318
     */
319 2
    protected function loginByCookie()
320
    {
321 2
        $data = $this->getIdentityAndDurationFromCookie();
322 2
        if (isset($data['identity'], $data['duration'])) {
323 1
            $identity = $data['identity'];
324 1
            $duration = $data['duration'];
325 1
            if ($this->beforeLogin($identity, true, $duration)) {
326 1
                $this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);
327 1
                $id = $identity->getId();
328 1
                $ip = Yii::$app->getRequest()->getUserIP();
329 1
                Yii::info("User '$id' logged in from $ip via cookie.", __METHOD__);
330 1
                $this->afterLogin($identity, true, $duration);
331
            }
332
        }
333 2
    }
334
335
    /**
336
     * Logs out the current user.
337
     * This will remove authentication-related session data.
338
     * If `$destroySession` is true, all session data will be removed.
339
     * @param bool $destroySession whether to destroy the whole session. Defaults to true.
340
     * This parameter is ignored if [[enableSession]] is false.
341
     * @return bool whether the user is logged out
342
     */
343 1
    public function logout($destroySession = true)
344
    {
345 1
        $identity = $this->getIdentity();
346 1
        if ($identity !== null && $this->beforeLogout($identity)) {
347 1
            $this->switchIdentity(null);
348 1
            $id = $identity->getId();
349 1
            $ip = Yii::$app->getRequest()->getUserIP();
350 1
            Yii::info("User '$id' logged out from $ip.", __METHOD__);
351 1
            if ($destroySession && $this->enableSession) {
352
                Yii::$app->getSession()->destroy();
353
            }
354 1
            $this->afterLogout($identity);
355
        }
356
357 1
        return $this->getIsGuest();
358
    }
359
360
    /**
361
     * Returns a value indicating whether the user is a guest (not authenticated).
362
     * @return bool whether the current user is a guest.
363
     * @see getIdentity()
364
     */
365 41
    public function getIsGuest()
366
    {
367 41
        return $this->getIdentity() === null;
368
    }
369
370
    /**
371
     * Returns a value that uniquely represents the user.
372
     * @return string|int the unique identifier for the user. If `null`, it means the user is a guest.
373
     * @see getIdentity()
374
     */
375 84
    public function getId()
376
    {
377 84
        $identity = $this->getIdentity();
378
379 84
        return $identity !== null ? $identity->getId() : null;
380
    }
381
382
    /**
383
     * Returns the URL that the browser should be redirected to after successful login.
384
     *
385
     * This method reads the return URL from the session. It is usually used by the login action which
386
     * may call this method to redirect the browser to where it goes after successful authentication.
387
     *
388
     * @param string|array $defaultUrl the default return URL in case it was not set previously.
389
     * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
390
     * Please refer to [[setReturnUrl()]] on accepted format of the URL.
391
     * @return string the URL that the user should be redirected to after login.
392
     * @see loginRequired()
393
     */
394 2
    public function getReturnUrl($defaultUrl = null)
395
    {
396 2
        $url = Yii::$app->getSession()->get($this->returnUrlParam, $defaultUrl);
397 2
        if (is_array($url)) {
398
            if (isset($url[0])) {
399
                return Yii::$app->getUrlManager()->createUrl($url);
400
            }
401
402
            $url = null;
403
        }
404
405 2
        return $url === null ? Yii::$app->getHomeUrl() : $url;
406
    }
407
408
    /**
409
     * Remembers the URL in the session so that it can be retrieved back later by [[getReturnUrl()]].
410
     * @param string|array $url the URL that the user should be redirected to after login.
411
     * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
412
     * The first element of the array should be the route, and the rest of
413
     * the name-value pairs are GET parameters used to construct the URL. For example,
414
     *
415
     * ```php
416
     * ['admin/index', 'ref' => 1]
417
     * ```
418
     */
419 2
    public function setReturnUrl($url)
420
    {
421 2
        Yii::$app->getSession()->set($this->returnUrlParam, $url);
422 2
    }
423
424
    /**
425
     * Redirects the user browser to the login page.
426
     *
427
     * Before the redirection, the current URL (if it's not an AJAX url) will be kept as [[returnUrl]] so that
428
     * the user browser may be redirected back to the current page after successful login.
429
     *
430
     * Make sure you set [[loginUrl]] so that the user browser can be redirected to the specified login URL after
431
     * calling this method.
432
     *
433
     * Note that when [[loginUrl]] is set, calling this method will NOT terminate the application execution.
434
     *
435
     * @param bool $checkAjax whether to check if the request is an AJAX request. When this is true and the request
436
     * is an AJAX request, the current URL (for AJAX request) will NOT be set as the return URL.
437
     * @param bool $checkAcceptHeader whether to check if the request accepts HTML responses. Defaults to `true`. When this is true and
438
     * the request does not accept HTML responses the current URL will not be SET as the return URL. Also instead of
439
     * redirecting the user an ForbiddenHttpException is thrown. This parameter is available since version 2.0.8.
440
     * @return Response the redirection response if [[loginUrl]] is set
441
     * @throws ForbiddenHttpException the "Access Denied" HTTP exception if [[loginUrl]] is not set or a redirect is
442
     * not applicable.
443
     */
444 2
    public function loginRequired($checkAjax = true, $checkAcceptHeader = true)
445
    {
446 2
        $request = Yii::$app->getRequest();
447 2
        $canRedirect = !$checkAcceptHeader || $this->checkRedirectAcceptable();
448 2
        if ($this->enableSession
449 2
            && $request->getIsGet()
450 2
            && (!$checkAjax || !$request->getIsAjax())
451 2
            && $canRedirect
452
        ) {
453 1
            $this->setReturnUrl($request->getAbsoluteUrl());
0 ignored issues
show
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

453
            $this->setReturnUrl($request->/** @scrutinizer ignore-call */ getAbsoluteUrl());
Loading history...
454
        }
455 2
        if ($this->loginUrl !== null && $canRedirect) {
456 1
            $loginUrl = (array) $this->loginUrl;
457 1
            if ($loginUrl[0] !== Yii::$app->requestedRoute) {
458 1
                return Yii::$app->getResponse()->redirect($this->loginUrl);
459
            }
460
        }
461 2
        throw new ForbiddenHttpException(Yii::t('yii', 'Login Required'));
462
    }
463
464
    /**
465
     * This method is called before logging in a user.
466
     * The default implementation will trigger the [[EVENT_BEFORE_LOGIN]] event.
467
     * If you override this method, make sure you call the parent implementation
468
     * so that the event is triggered.
469
     * @param IdentityInterface $identity the user identity information
470
     * @param bool $cookieBased whether the login is cookie-based
471
     * @param int $duration number of seconds that the user can remain in logged-in status.
472
     * If 0, it means login till the user closes the browser or the session is manually destroyed.
473
     * @return bool whether the user should continue to be logged in
474
     */
475 40
    protected function beforeLogin($identity, $cookieBased, $duration)
476
    {
477 40
        $event = new UserEvent([
478 40
            'identity' => $identity,
479 40
            'cookieBased' => $cookieBased,
480 40
            'duration' => $duration,
481
        ]);
482 40
        $this->trigger(self::EVENT_BEFORE_LOGIN, $event);
483
484 40
        return $event->isValid;
485
    }
486
487
    /**
488
     * This method is called after the user is successfully logged in.
489
     * The default implementation will trigger the [[EVENT_AFTER_LOGIN]] event.
490
     * If you override this method, make sure you call the parent implementation
491
     * so that the event is triggered.
492
     * @param IdentityInterface $identity the user identity information
493
     * @param bool $cookieBased whether the login is cookie-based
494
     * @param int $duration number of seconds that the user can remain in logged-in status.
495
     * If 0, it means login till the user closes the browser or the session is manually destroyed.
496
     */
497 40
    protected function afterLogin($identity, $cookieBased, $duration)
498
    {
499 40
        $this->trigger(self::EVENT_AFTER_LOGIN, new UserEvent([
500 40
            'identity' => $identity,
501 40
            'cookieBased' => $cookieBased,
502 40
            'duration' => $duration,
503
        ]));
504 40
    }
505
506
    /**
507
     * This method is invoked when calling [[logout()]] to log out a user.
508
     * The default implementation will trigger the [[EVENT_BEFORE_LOGOUT]] event.
509
     * If you override this method, make sure you call the parent implementation
510
     * so that the event is triggered.
511
     * @param IdentityInterface $identity the user identity information
512
     * @return bool whether the user should continue to be logged out
513
     */
514 1
    protected function beforeLogout($identity)
515
    {
516 1
        $event = new UserEvent([
517 1
            'identity' => $identity,
518
        ]);
519 1
        $this->trigger(self::EVENT_BEFORE_LOGOUT, $event);
520
521 1
        return $event->isValid;
522
    }
523
524
    /**
525
     * This method is invoked right after a user is logged out via [[logout()]].
526
     * The default implementation will trigger the [[EVENT_AFTER_LOGOUT]] event.
527
     * If you override this method, make sure you call the parent implementation
528
     * so that the event is triggered.
529
     * @param IdentityInterface $identity the user identity information
530
     */
531 1
    protected function afterLogout($identity)
532
    {
533 1
        $this->trigger(self::EVENT_AFTER_LOGOUT, new UserEvent([
534 1
            'identity' => $identity,
535
        ]));
536 1
    }
537
538
    /**
539
     * Renews the identity cookie.
540
     * This method will set the expiration time of the identity cookie to be the current time
541
     * plus the originally specified cookie duration.
542
     */
543
    protected function renewIdentityCookie()
544
    {
545
        $name = $this->identityCookie['name'];
546
        $value = Yii::$app->getRequest()->getCookies()->getValue($name);
547
        if ($value !== null) {
548
            $data = json_decode($value, true);
549
            if (is_array($data) && isset($data[2])) {
550
                $cookie = Yii::createObject(array_merge($this->identityCookie, [
551
                    'class' => 'yii\web\Cookie',
552
                    'value' => $value,
553
                    'expire' => time() + (int) $data[2],
554
                ]));
555
                Yii::$app->getResponse()->getCookies()->add($cookie);
556
            }
557
        }
558
    }
559
560
    /**
561
     * Sends an identity cookie.
562
     * This method is used when [[enableAutoLogin]] is true.
563
     * It saves [[id]], [[IdentityInterface::getAuthKey()|auth key]], and the duration of cookie-based login
564
     * information in the cookie.
565
     * @param IdentityInterface $identity
566
     * @param int $duration number of seconds that the user can remain in logged-in status.
567
     * @see loginByCookie()
568
     */
569 2
    protected function sendIdentityCookie($identity, $duration)
570
    {
571 2
        $cookie = Yii::createObject(array_merge($this->identityCookie, [
572 2
            'class' => 'yii\web\Cookie',
573 2
            'value' => json_encode([
574 2
                $identity->getId(),
575 2
                $identity->getAuthKey(),
576 2
                $duration,
577 2
            ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
578 2
            'expire' => time() + $duration,
579
        ]));
580 2
        Yii::$app->getResponse()->getCookies()->add($cookie);
581 2
    }
582
583
    /**
584
     * Determines if an identity cookie has a valid format and contains a valid auth key.
585
     * This method is used when [[enableAutoLogin]] is true.
586
     * This method attempts to authenticate a user using the information in the identity cookie.
587
     * @return array|null Returns an array of 'identity' and 'duration' if valid, otherwise null.
588
     * @see loginByCookie()
589
     * @since 2.0.9
590
     */
591 2
    protected function getIdentityAndDurationFromCookie()
592
    {
593 2
        $value = Yii::$app->getRequest()->getCookies()->getValue($this->identityCookie['name']);
594 2
        if ($value === null) {
595
            return null;
596
        }
597 2
        $data = json_decode($value, true);
598 2
        if (is_array($data) && count($data) == 3) {
599 1
            list($id, $authKey, $duration) = $data;
600
            /* @var $class IdentityInterface */
601 1
            $class = $this->identityClass;
602 1
            $identity = $class::findIdentity($id);
603 1
            if ($identity !== null) {
604 1
                if (!$identity instanceof IdentityInterface) {
605
                    throw new InvalidValueException("$class::findIdentity() must return an object implementing IdentityInterface.");
606 1
                } elseif (!$identity->validateAuthKey($authKey)) {
607
                    $ip = Yii::$app->getRequest()->getUserIP();
608
                    Yii::warning("Invalid cookie auth key attempted for user '$id' from $ip: $authKey", __METHOD__);
609
                } else {
610 1
                    return ['identity' => $identity, 'duration' => $duration];
611
                }
612
            }
613
        }
614 2
        $this->removeIdentityCookie();
615 2
        return null;
616
    }
617
618
    /**
619
     * Removes the identity cookie.
620
     * This method is used when [[enableAutoLogin]] is true.
621
     * @since 2.0.9
622
     */
623 2
    protected function removeIdentityCookie()
624
    {
625 2
        Yii::$app->getResponse()->getCookies()->remove(Yii::createObject(array_merge($this->identityCookie, [
626 2
            'class' => 'yii\web\Cookie',
627
        ])));
628 2
    }
629
630
    /**
631
     * Switches to a new identity for the current user.
632
     *
633
     * When [[enableSession]] is true, this method may use session and/or cookie to store the user identity information,
634
     * according to the value of `$duration`. Please refer to [[login()]] for more details.
635
     *
636
     * This method is mainly called by [[login()]], [[logout()]] and [[loginByCookie()]]
637
     * when the current user needs to be associated with the corresponding identity information.
638
     *
639
     * @param IdentityInterface|null $identity the identity information to be associated with the current user.
640
     * If null, it means switching the current user to be a guest.
641
     * @param int $duration number of seconds that the user can remain in logged-in status.
642
     * This parameter is used only when `$identity` is not null.
643
     */
644 40
    public function switchIdentity($identity, $duration = 0)
645
    {
646 40
        $this->setIdentity($identity);
647
648 40
        if (!$this->enableSession) {
649
            return;
650
        }
651
652
        /* Ensure any existing identity cookies are removed. */
653 40
        if ($this->enableAutoLogin && ($this->autoRenewCookie || $identity === null)) {
654 1
            $this->removeIdentityCookie();
655
        }
656
657 40
        $session = Yii::$app->getSession();
658 40
        if (!YII_ENV_TEST) {
659
            $session->regenerateID(true);
660
        }
661 40
        $session->remove($this->idParam);
662 40
        $session->remove($this->authTimeoutParam);
663 40
        $session->remove($this->authKeyParam);
664
665 40
        if ($identity) {
666 40
            $session->set($this->idParam, $identity->getId());
667 40
            $session->set($this->authKeyParam, $identity->getAuthKey());
668 40
            if ($this->authTimeout !== null) {
669 2
                $session->set($this->authTimeoutParam, time() + $this->authTimeout);
670
            }
671 40
            if ($this->absoluteAuthTimeout !== null) {
672
                $session->set($this->absoluteAuthTimeoutParam, time() + $this->absoluteAuthTimeout);
673
            }
674 40
            if ($this->enableAutoLogin && $duration > 0) {
675 2
                $this->sendIdentityCookie($identity, $duration);
676
            }
677
        }
678 40
    }
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 39
    protected function renewAuthStatus()
691
    {
692 39
        $session = Yii::$app->getSession();
693 39
        $id = $session->getHasSessionId() || $session->getIsActive() ? $session->get($this->idParam) : null;
694
695 39
        if ($id === null) {
696 31
            $identity = null;
697
        } else {
698
            /* @var $class IdentityInterface */
699 9
            $class = $this->identityClass;
700 9
            $identity = $class::findIdentity($id);
701
        }
702
703 38
        if ($identity !== null) {
704 5
            $authKey = $session->get($this->authKeyParam);
705 5
            if ($authKey !== null && !$identity->validateAuthKey($authKey)) {
706 1
                $identity = null;
707 1
                $ip = Yii::$app->getRequest()->getUserIP();
708 1
                Yii::warning("Invalid session auth key attempted for user '$id' from $ip: $authKey", __METHOD__);
709
            }
710
        }
711
712 38
        $this->setIdentity($identity);
713
714 38
        if ($identity !== null && ($this->authTimeout !== null || $this->absoluteAuthTimeout !== null)) {
715 2
            $expire = $this->authTimeout !== null ? $session->get($this->authTimeoutParam) : null;
716 2
            $expireAbsolute = $this->absoluteAuthTimeout !== null ? $session->get($this->absoluteAuthTimeoutParam) : null;
717 2
            if ($expire !== null && $expire < time() || $expireAbsolute !== null && $expireAbsolute < time()) {
718 1
                $this->logout(false);
719 2
            } elseif ($this->authTimeout !== null) {
720 2
                $session->set($this->authTimeoutParam, time() + $this->authTimeout);
721
            }
722
        }
723
724 38
        if ($this->enableAutoLogin) {
725 2
            if ($this->getIsGuest()) {
726 2
                $this->loginByCookie();
727 1
            } elseif ($this->autoRenewCookie) {
728
                $this->renewIdentityCookie();
729
            }
730
        }
731 38
    }
732
733
    /**
734
     * Checks if the user can perform the operation as specified by the given permission.
735
     *
736
     * Note that you must configure "authManager" application component in order to use this method.
737
     * Otherwise it will always return false.
738
     *
739
     * @param string $permissionName the name of the permission (e.g. "edit post") that needs access check.
740
     * @param array $params name-value pairs that would be passed to the rules associated
741
     * with the roles and permissions assigned to the user.
742
     * @param bool $allowCaching whether to allow caching the result of access check.
743
     * When this parameter is true (default), if the access check of an operation was performed
744
     * before, its result will be directly returned when calling this method to check the same
745
     * operation. If this parameter is false, this method will always call
746
     * [[\yii\rbac\CheckAccessInterface::checkAccess()]] to obtain the up-to-date access result. Note that this
747
     * caching is effective only within the same request and only works when `$params = []`.
748
     * @return bool whether the user can perform the operation as specified by the given permission.
749
     */
750 23
    public function can($permissionName, $params = [], $allowCaching = true)
751
    {
752 23
        if ($allowCaching && empty($params) && isset($this->_access[$permissionName])) {
753
            return $this->_access[$permissionName];
754
        }
755 23
        if (($accessChecker = $this->getAccessChecker()) === null) {
756
            return false;
757
        }
758 23
        $access = $accessChecker->checkAccess($this->getId(), $permissionName, $params);
759 23
        if ($allowCaching && empty($params)) {
760 10
            $this->_access[$permissionName] = $access;
761
        }
762
763 23
        return $access;
764
    }
765
766
    /**
767
     * Checks if the `Accept` header contains a content type that allows redirection to the login page.
768
     * The login page is assumed to serve `text/html` or `application/xhtml+xml` by default. You can change acceptable
769
     * content types by modifying [[acceptableRedirectTypes]] property.
770
     * @return bool whether this request may be redirected to the login page.
771
     * @see acceptableRedirectTypes
772
     * @since 2.0.8
773
     */
774 2
    public function checkRedirectAcceptable()
775
    {
776 2
        $acceptableTypes = Yii::$app->getRequest()->getAcceptableContentTypes();
777 2
        if (empty($acceptableTypes) || (count($acceptableTypes) === 1 && array_keys($acceptableTypes)[0] === '*/*')) {
778 1
            return true;
779
        }
780
781 2
        foreach ($acceptableTypes as $type => $params) {
782 2
            if (in_array($type, $this->acceptableRedirectTypes, true)) {
783 2
                return true;
784
            }
785
        }
786
787 2
        return false;
788
    }
789
790
    /**
791
     * Returns auth manager associated with the user component.
792
     *
793
     * By default this is the `authManager` application component.
794
     * You may override this method to return a different auth manager instance if needed.
795
     * @return \yii\rbac\ManagerInterface
796
     * @since 2.0.6
797
     * @deprecated since version 2.0.9, to be removed in 2.1. Use [[getAccessChecker()]] instead.
798
     */
799
    protected function getAuthManager()
800
    {
801
        return Yii::$app->getAuthManager();
802
    }
803
804
    /**
805
     * Returns the access checker used for checking access.
806
     * @return CheckAccessInterface
807
     * @since 2.0.9
808
     */
809 23
    protected function getAccessChecker()
810
    {
811 23
        return $this->accessChecker !== null ? $this->accessChecker : $this->getAuthManager();
812
    }
813
}
814