User.php 28.1 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8 9
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\web;

Qiang Xue committed
10
use Yii;
Qiang Xue committed
11
use yii\base\Component;
Qiang Xue committed
12
use yii\base\InvalidConfigException;
13
use yii\base\InvalidValueException;
Qiang Xue committed
14 15

/**
16
 * User is the class for the "user" application component that manages the user authentication status.
Qiang Xue committed
17
 *
18 19 20
 * You may use [[isGuest]] to determine whether the current user is a guest or not.
 * If the user is a guest, the [[identity]] property would return null. Otherwise, it would
 * be an instance of [[IdentityInterface]].
Qiang Xue committed
21
 *
22 23 24 25 26 27 28 29 30 31
 * You may call various methods to change the user authentication status:
 *
 * - [[login()]]: sets the specified identity and remembers the authentication status in session and cookie.
 * - [[logout()]]: marks the user as a guest and clears the relevant information from session and cookie.
 * - [[setIdentity()]]: changes the user identity without touching session or cookie.
 *   This is best used in stateless RESTful API implementation.
 *
 * Note that User only maintains the user authentication status. It does NOT handle how to authenticate
 * a user. The logic of how to authenticate a user should be done in the class implementing [[IdentityInterface]].
 * You are also required to set [[identityClass]] with the name of this class.
Qiang Xue committed
32
 *
33
 * User is configured as an application component in [[\yii\web\Application]] by default.
34 35 36 37 38 39 40 41 42 43 44 45 46 47
 * You can access that instance via `Yii::$app->user`.
 *
 * You can modify its configuration by adding an array to your application config under `components`
 * as it is shown in the following example:
 *
 * ~~~
 * 'user' => [
 *     'identityClass' => 'app\models\User', // User must implement the IdentityInterface
 *     'enableAutoLogin' => true,
 *     // 'loginUrl' => ['user/login'],
 *     // ...
 * ]
 * ~~~
 *
48
 * @property string|integer $id The unique identifier for the user. If null, it means the user is a guest.
49
 * This property is read-only.
50 51
 * @property IdentityInterface|null $identity The identity object associated with the currently logged-in
 * user. `null` is returned if the user is not logged in (not authenticated).
52
 * @property boolean $isGuest Whether the current user is a guest. This property is read-only.
53 54
 * @property string $returnUrl The URL that the user should be redirected to after login. Note that the type
 * of this property differs in getter and setter. See [[getReturnUrl()]] and [[setReturnUrl()]] for details.
55
 *
Qiang Xue committed
56 57 58 59 60
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class User extends Component
{
61 62 63 64 65 66 67 68 69 70 71
    const EVENT_BEFORE_LOGIN = 'beforeLogin';
    const EVENT_AFTER_LOGIN = 'afterLogin';
    const EVENT_BEFORE_LOGOUT = 'beforeLogout';
    const EVENT_AFTER_LOGOUT = 'afterLogout';

    /**
     * @var string the class name of the [[identity]] object.
     */
    public $identityClass;
    /**
     * @var boolean whether to enable cookie-based login. Defaults to false.
72
     * Note that this property will be ignored if [[enableSession]] is false.
73 74
     */
    public $enableAutoLogin = false;
75 76 77 78 79 80
    /**
     * @var boolean whether to use session to persist authentication status across multiple requests.
     * You set this property to be false if your application is stateless, which is often the case
     * for RESTful APIs.
     */
    public $enableSession = true;
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    /**
     * @var string|array the URL for login when [[loginRequired()]] is called.
     * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
     * The first element of the array should be the route to the login action, and the rest of
     * the name-value pairs are GET parameters used to construct the login URL. For example,
     *
     * ~~~
     * ['site/login', 'ref' => 1]
     * ~~~
     *
     * If this property is null, a 403 HTTP exception will be raised when [[loginRequired()]] is called.
     */
    public $loginUrl = ['site/login'];
    /**
     * @var array the configuration of the identity cookie. This property is used only when [[enableAutoLogin]] is true.
     * @see Cookie
     */
    public $identityCookie = ['name' => '_identity', 'httpOnly' => true];
    /**
     * @var integer the number of seconds in which the user will be logged out automatically if he
     * remains inactive. If this property is not set, the user will be logged out after
     * the current session expires (c.f. [[Session::timeout]]).
103
     * Note that this will not work if [[enableAutoLogin]] is true.
104 105
     */
    public $authTimeout;
106 107 108 109 110 111
    /**
     * @var integer the number of seconds in which the user will be logged out automatically
     * regardless of activity.
     * Note that this will not work if [[enableAutoLogin]] is true.
     */
    public $absoluteAuthTimeout;
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    /**
     * @var boolean whether to automatically renew the identity cookie each time a page is requested.
     * This property is effective only when [[enableAutoLogin]] is true.
     * When this is false, the identity cookie will expire after the specified duration since the user
     * is initially logged in. When this is true, the identity cookie will expire after the specified duration
     * since the user visits the site the last time.
     * @see enableAutoLogin
     */
    public $autoRenewCookie = true;
    /**
     * @var string the session variable name used to store the value of [[id]].
     */
    public $idParam = '__id';
    /**
     * @var string the session variable name used to store the value of expiration timestamp of the authenticated state.
     * This is used when [[authTimeout]] is set.
     */
    public $authTimeoutParam = '__expire';
130 131 132 133
    /**
     * @var string the session variable name used to store the value of absolute expiration timestamp of the authenticated state.
     * This is used when [[absoluteAuthTimeout]] is set.
     */
134
    public $absoluteAuthTimeoutParam = '__absoluteExpire';
135 136 137 138 139 140 141
    /**
     * @var string the session variable name used to store the value of [[returnUrl]].
     */
    public $returnUrlParam = '__returnUrl';

    private $_access = [];

142

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
    /**
     * Initializes the application component.
     */
    public function init()
    {
        parent::init();

        if ($this->identityClass === null) {
            throw new InvalidConfigException('User::identityClass must be set.');
        }
        if ($this->enableAutoLogin && !isset($this->identityCookie['name'])) {
            throw new InvalidConfigException('User::identityCookie must contain the "name" element.');
        }
    }

    private $_identity = false;

    /**
     * Returns the identity object associated with the currently logged-in user.
162 163
     * When [[enableSession]] is true, this method may attempt to read the user's authentication data
     * stored in session and reconstruct the corresponding identity object, if it has not done so before.
164 165
     * @param boolean $autoRenew whether to automatically renew authentication status if it has not been done so before.
     * This is only useful when [[enableSession]] is true.
166 167
     * @return IdentityInterface|null the identity object associated with the currently logged-in user.
     * `null` is returned if the user is not logged in (not authenticated).
168 169 170
     * @see login()
     * @see logout()
     */
171
    public function getIdentity($autoRenew = true)
172 173
    {
        if ($this->_identity === false) {
174
            if ($this->enableSession && $autoRenew) {
175
                $this->_identity = null;
176 177 178 179 180 181 182 183 184 185 186 187
                $this->renewAuthStatus();
            } else {
                return null;
            }
        }

        return $this->_identity;
    }

    /**
     * Sets the user identity object.
     *
188 189
     * Note that this method does not deal with session or cookie. You should usually use [[switchIdentity()]]
     * to change the identity of the current user.
190
     *
191
     * @param IdentityInterface|null $identity the identity object associated with the currently logged user.
192
     * If null, it means the current user will be a guest without any associated identity.
193
     * @throws InvalidValueException if `$identity` object does not implement [[IdentityInterface]].
194 195 196
     */
    public function setIdentity($identity)
    {
197 198 199
        if ($identity instanceof IdentityInterface) {
            $this->_identity = $identity;
            $this->_access = [];
Qiang Xue committed
200 201
        } elseif ($identity === null) {
            $this->_identity = null;
202 203 204
        } else {
            throw new InvalidValueException('The identity object must implement IdentityInterface.');
        }
205 206 207 208 209
    }

    /**
     * Logs in a user.
     *
210 211 212
     * After logging in a user, you may obtain the user's identity information from the [[identity]] property.
     * If [[enableSession]] is true, you may even get the identity information in the next requests without
     * calling this method again.
213 214 215 216 217 218 219 220 221 222
     *
     * The login status is maintained according to the `$duration` parameter:
     *
     * - `$duration == 0`: the identity information will be stored in session and will be available
     *   via [[identity]] as long as the session remains active.
     * - `$duration > 0`: the identity information will be stored in session. If [[enableAutoLogin]] is true,
     *   it will also be stored in a cookie which will expire in `$duration` seconds. As long as
     *   the cookie remains valid or the session is active, you may obtain the user identity information
     *   via [[identity]].
     *
223 224 225
     * Note that if [[enableSession]] is false, the `$duration` parameter will be ignored as it is meaningless
     * in this case.
     *
226 227 228 229
     * @param IdentityInterface $identity the user identity (which should already be authenticated)
     * @param integer $duration number of seconds that the user can remain in logged-in status.
     * Defaults to 0, meaning login till the user closes the browser or the session is manually destroyed.
     * If greater than 0 and [[enableAutoLogin]] is true, cookie-based login will be supported.
230
     * Note that if [[enableSession]] is false, this parameter will be ignored.
231
     * @return boolean whether the user is logged in
232
     */
233
    public function login(IdentityInterface $identity, $duration = 0)
234 235 236 237 238
    {
        if ($this->beforeLogin($identity, false, $duration)) {
            $this->switchIdentity($identity, $duration);
            $id = $identity->getId();
            $ip = Yii::$app->getRequest()->getUserIP();
239 240 241 242 243 244
            if ($this->enableSession) {
                $log = "User '$id' logged in from $ip with duration $duration.";
            } else {
                $log = "User '$id' logged in from $ip. Session not enabled.";
            }
            Yii::info($log, __METHOD__);
245 246 247 248 249 250 251 252
            $this->afterLogin($identity, false, $duration);
        }

        return !$this->getIsGuest();
    }

    /**
     * Logs in a user by the given access token.
253 254 255
     * This method will first authenticate the user by calling [[IdentityInterface::findIdentityByAccessToken()]]
     * with the provided access token. If successful, it will call [[login()]] to log in the authenticated user.
     * If authentication fails or [[login()]] is unsuccessful, it will return null.
256
     * @param string $token the access token
257 258
     * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
     * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
259 260
     * @return IdentityInterface|null the identity associated with the given access token. Null is returned if
     * the access token is invalid or [[login()]] is unsuccessful.
261
     */
262
    public function loginByAccessToken($token, $type = null)
263
    {
264
        /* @var $class IdentityInterface */
265
        $class = $this->identityClass;
266
        $identity = $class::findIdentityByAccessToken($token, $type);
267 268 269 270 271
        if ($identity && $this->login($identity)) {
            return $identity;
        } else {
            return null;
        }
272 273 274 275 276 277
    }

    /**
     * Logs in a user by cookie.
     *
     * This method attempts to log in a user using the ID and authKey information
278
     * provided by the [[identityCookie|identity cookie]].
279 280 281
     */
    protected function loginByCookie()
    {
282 283 284 285 286 287
        $value = Yii::$app->getRequest()->getCookies()->getValue($this->identityCookie['name']);
        if ($value === null) {
            return;
        }

        $data = json_decode($value, true);
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
        if (count($data) !== 3 || !isset($data[0], $data[1], $data[2])) {
            return;
        }

        list ($id, $authKey, $duration) = $data;
        /* @var $class IdentityInterface */
        $class = $this->identityClass;
        $identity = $class::findIdentity($id);
        if ($identity === null) {
            return;
        } elseif (!$identity instanceof IdentityInterface) {
            throw new InvalidValueException("$class::findIdentity() must return an object implementing IdentityInterface.");
        }

        if ($identity->validateAuthKey($authKey)) {
            if ($this->beforeLogin($identity, true, $duration)) {
                $this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);
                $ip = Yii::$app->getRequest()->getUserIP();
                Yii::info("User '$id' logged in from $ip via cookie.", __METHOD__);
                $this->afterLogin($identity, true, $duration);
308
            }
309 310
        } else {
            Yii::warning("Invalid auth key attempted for user '$id': $authKey", __METHOD__);
311 312 313 314 315 316 317 318
        }
    }

    /**
     * Logs out the current user.
     * This will remove authentication-related session data.
     * If `$destroySession` is true, all session data will be removed.
     * @param boolean $destroySession whether to destroy the whole session. Defaults to true.
319
     * This parameter is ignored if [[enableSession]] is false.
320
     * @return boolean whether the user is logged out
321 322 323 324 325 326 327 328 329
     */
    public function logout($destroySession = true)
    {
        $identity = $this->getIdentity();
        if ($identity !== null && $this->beforeLogout($identity)) {
            $this->switchIdentity(null);
            $id = $identity->getId();
            $ip = Yii::$app->getRequest()->getUserIP();
            Yii::info("User '$id' logged out from $ip.", __METHOD__);
330
            if ($destroySession && $this->enableSession) {
331 332 333 334
                Yii::$app->getSession()->destroy();
            }
            $this->afterLogout($identity);
        }
335

336
        return $this->getIsGuest();
337 338 339 340 341
    }

    /**
     * Returns a value indicating whether the user is a guest (not authenticated).
     * @return boolean whether the current user is a guest.
342
     * @see getIdentity()
343
     */
344
    public function getIsGuest()
345
    {
346
        return $this->getIdentity() === null;
347 348 349 350 351
    }

    /**
     * Returns a value that uniquely represents the user.
     * @return string|integer the unique identifier for the user. If null, it means the user is a guest.
352
     * @see getIdentity()
353
     */
354
    public function getId()
355
    {
356
        $identity = $this->getIdentity();
357 358 359 360 361

        return $identity !== null ? $identity->getId() : null;
    }

    /**
362 363 364 365 366
     * Returns the URL that the browser should be redirected to after successful login.
     *
     * This method reads the return URL from the session. It is usually used by the login action which
     * may call this method to redirect the browser to where it goes after successful authentication.
     *
367 368 369 370
     * @param string|array $defaultUrl the default return URL in case it was not set previously.
     * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
     * Please refer to [[setReturnUrl()]] on accepted format of the URL.
     * @return string the URL that the user should be redirected to after login.
371 372 373 374 375 376 377
     * @see loginRequired()
     */
    public function getReturnUrl($defaultUrl = null)
    {
        $url = Yii::$app->getSession()->get($this->returnUrlParam, $defaultUrl);
        if (is_array($url)) {
            if (isset($url[0])) {
378
                return Yii::$app->getUrlManager()->createUrl($url);
379 380 381 382 383 384 385 386 387
            } else {
                $url = null;
            }
        }

        return $url === null ? Yii::$app->getHomeUrl() : $url;
    }

    /**
388
     * Remembers the URL in the session so that it can be retrieved back later by [[getReturnUrl()]].
389
     * @param string|array $url the URL that the user should be redirected to after login.
390 391 392
     * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
     * The first element of the array should be the route, and the rest of
     * the name-value pairs are GET parameters used to construct the URL. For example,
393 394 395 396 397 398 399 400 401 402 403 404
     *
     * ~~~
     * ['admin/index', 'ref' => 1]
     * ~~~
     */
    public function setReturnUrl($url)
    {
        Yii::$app->getSession()->set($this->returnUrlParam, $url);
    }

    /**
     * Redirects the user browser to the login page.
405 406 407 408 409
     *
     * Before the redirection, the current URL (if it's not an AJAX url) will be kept as [[returnUrl]] so that
     * the user browser may be redirected back to the current page after successful login.
     *
     * Make sure you set [[loginUrl]] so that the user browser can be redirected to the specified login URL after
410 411 412 413
     * calling this method.
     *
     * Note that when [[loginUrl]] is set, calling this method will NOT terminate the application execution.
     *
414 415
     * @param boolean $checkAjax whether to check if the request is an AJAX request. When this is true and the request
     * is an AJAX request, the current URL (for AJAX request) will NOT be set as the return URL.
416
     * @return Response the redirection response if [[loginUrl]] is set
417 418
     * @throws ForbiddenHttpException the "Access Denied" HTTP exception if [[loginUrl]] is not set
     */
419
    public function loginRequired($checkAjax = true)
420 421
    {
        $request = Yii::$app->getRequest();
422
        if ($this->enableSession && (!$checkAjax || !$request->getIsAjax())) {
423 424 425
            $this->setReturnUrl($request->getUrl());
        }
        if ($this->loginUrl !== null) {
426 427 428 429
            $loginUrl = (array)$this->loginUrl;
            if ($loginUrl[0] !== Yii::$app->requestedRoute) {
                return Yii::$app->getResponse()->redirect($this->loginUrl);
            }
430
        }
431
        throw new ForbiddenHttpException(Yii::t('yii', 'Login Required'));
432 433 434 435 436 437 438
    }

    /**
     * This method is called before logging in a user.
     * The default implementation will trigger the [[EVENT_BEFORE_LOGIN]] event.
     * If you override this method, make sure you call the parent implementation
     * so that the event is triggered.
439 440 441 442 443
     * @param IdentityInterface $identity the user identity information
     * @param boolean $cookieBased whether the login is cookie-based
     * @param integer $duration number of seconds that the user can remain in logged-in status.
     * If 0, it means login till the user closes the browser or the session is manually destroyed.
     * @return boolean whether the user should continue to be logged in
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
     */
    protected function beforeLogin($identity, $cookieBased, $duration)
    {
        $event = new UserEvent([
            'identity' => $identity,
            'cookieBased' => $cookieBased,
            'duration' => $duration,
        ]);
        $this->trigger(self::EVENT_BEFORE_LOGIN, $event);

        return $event->isValid;
    }

    /**
     * This method is called after the user is successfully logged in.
     * The default implementation will trigger the [[EVENT_AFTER_LOGIN]] event.
     * If you override this method, make sure you call the parent implementation
     * so that the event is triggered.
462 463 464 465
     * @param IdentityInterface $identity the user identity information
     * @param boolean $cookieBased whether the login is cookie-based
     * @param integer $duration number of seconds that the user can remain in logged-in status.
     * If 0, it means login till the user closes the browser or the session is manually destroyed.
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
     */
    protected function afterLogin($identity, $cookieBased, $duration)
    {
        $this->trigger(self::EVENT_AFTER_LOGIN, new UserEvent([
            'identity' => $identity,
            'cookieBased' => $cookieBased,
            'duration' => $duration,
        ]));
    }

    /**
     * This method is invoked when calling [[logout()]] to log out a user.
     * The default implementation will trigger the [[EVENT_BEFORE_LOGOUT]] event.
     * If you override this method, make sure you call the parent implementation
     * so that the event is triggered.
481 482
     * @param IdentityInterface $identity the user identity information
     * @return boolean whether the user should continue to be logged out
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
     */
    protected function beforeLogout($identity)
    {
        $event = new UserEvent([
            'identity' => $identity,
        ]);
        $this->trigger(self::EVENT_BEFORE_LOGOUT, $event);

        return $event->isValid;
    }

    /**
     * This method is invoked right after a user is logged out via [[logout()]].
     * The default implementation will trigger the [[EVENT_AFTER_LOGOUT]] event.
     * If you override this method, make sure you call the parent implementation
     * so that the event is triggered.
     * @param IdentityInterface $identity the user identity information
     */
    protected function afterLogout($identity)
    {
        $this->trigger(self::EVENT_AFTER_LOGOUT, new UserEvent([
            'identity' => $identity,
        ]));
    }

    /**
     * Renews the identity cookie.
     * This method will set the expiration time of the identity cookie to be the current time
     * plus the originally specified cookie duration.
     */
    protected function renewIdentityCookie()
    {
        $name = $this->identityCookie['name'];
        $value = Yii::$app->getRequest()->getCookies()->getValue($name);
        if ($value !== null) {
            $data = json_decode($value, true);
            if (is_array($data) && isset($data[2])) {
                $cookie = new Cookie($this->identityCookie);
                $cookie->value = $value;
                $cookie->expire = time() + (int) $data[2];
                Yii::$app->getResponse()->getCookies()->add($cookie);
            }
        }
    }

    /**
     * Sends an identity cookie.
     * This method is used when [[enableAutoLogin]] is true.
     * It saves [[id]], [[IdentityInterface::getAuthKey()|auth key]], and the duration of cookie-based login
     * information in the cookie.
     * @param IdentityInterface $identity
534
     * @param integer $duration number of seconds that the user can remain in logged-in status.
535 536 537 538 539 540 541 542 543
     * @see loginByCookie()
     */
    protected function sendIdentityCookie($identity, $duration)
    {
        $cookie = new Cookie($this->identityCookie);
        $cookie->value = json_encode([
            $identity->getId(),
            $identity->getAuthKey(),
            $duration,
544
        ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
545 546 547 548 549 550 551
        $cookie->expire = time() + $duration;
        Yii::$app->getResponse()->getCookies()->add($cookie);
    }

    /**
     * Switches to a new identity for the current user.
     *
552
     * When [[enableSession]] is true, this method may use session and/or cookie to store the user identity information,
553 554 555 556 557
     * according to the value of `$duration`. Please refer to [[login()]] for more details.
     *
     * This method is mainly called by [[login()]], [[logout()]] and [[loginByCookie()]]
     * when the current user needs to be associated with the corresponding identity information.
     *
558
     * @param IdentityInterface|null $identity the identity information to be associated with the current user.
559 560 561
     * If null, it means switching the current user to be a guest.
     * @param integer $duration number of seconds that the user can remain in logged-in status.
     * This parameter is used only when `$identity` is not null.
562 563 564
     */
    public function switchIdentity($identity, $duration = 0)
    {
565 566 567 568 569 570
        $this->setIdentity($identity);

        if (!$this->enableSession) {
            return;
        }

571 572 573 574 575 576
        $session = Yii::$app->getSession();
        if (!YII_ENV_TEST) {
            $session->regenerateID(true);
        }
        $session->remove($this->idParam);
        $session->remove($this->authTimeoutParam);
577

Qiang Xue committed
578
        if ($identity) {
579 580 581 582
            $session->set($this->idParam, $identity->getId());
            if ($this->authTimeout !== null) {
                $session->set($this->authTimeoutParam, time() + $this->authTimeout);
            }
583 584 585
            if ($this->absoluteAuthTimeout !== null) {
                $session->set($this->absoluteAuthTimeoutParam, time() + $this->absoluteAuthTimeout);
            }
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
            if ($duration > 0 && $this->enableAutoLogin) {
                $this->sendIdentityCookie($identity, $duration);
            }
        } elseif ($this->enableAutoLogin) {
            Yii::$app->getResponse()->getCookies()->remove(new Cookie($this->identityCookie));
        }
    }

    /**
     * Updates the authentication status using the information from session and cookie.
     *
     * This method will try to determine the user identity using the [[idParam]] session variable.
     *
     * If [[authTimeout]] is set, this method will refresh the timer.
     *
     * If the user identity cannot be determined by session, this method will try to [[loginByCookie()|login by cookie]]
     * if [[enableAutoLogin]] is true.
     */
    protected function renewAuthStatus()
    {
        $session = Yii::$app->getSession();
        $id = $session->getHasSessionId() || $session->getIsActive() ? $session->get($this->idParam) : null;

        if ($id === null) {
            $identity = null;
        } else {
612
            /* @var $class IdentityInterface */
613 614 615 616 617 618
            $class = $this->identityClass;
            $identity = $class::findIdentity($id);
        }

        $this->setIdentity($identity);

619
        if ($identity !== null && ($this->authTimeout !== null || $this->absoluteAuthTimeout !== null)) {
620 621 622
            $expire = $this->authTimeout !== null ? $session->get($this->authTimeoutParam) : null;
            $expireAbsolute = $this->absoluteAuthTimeout !== null ? $session->get($this->absoluteAuthTimeoutParam) : null;
            if ($expire !== null && $expire < time() || $expireAbsolute !== null && $expireAbsolute < time()) {
623
                $this->logout(false);
624
            } elseif ($this->authTimeout !== null) {
625 626 627 628 629 630 631 632 633 634 635 636 637 638
                $session->set($this->authTimeoutParam, time() + $this->authTimeout);
            }
        }

        if ($this->enableAutoLogin) {
            if ($this->getIsGuest()) {
                $this->loginByCookie();
            } elseif ($this->autoRenewCookie) {
                $this->renewIdentityCookie();
            }
        }
    }

    /**
639
     * Checks if the user can perform the operation as specified by the given permission.
Qiang Xue committed
640 641 642 643
     *
     * Note that you must configure "authManager" application component in order to use this method.
     * Otherwise an exception will be thrown.
     *
644 645 646 647
     * @param string $permissionName the name of the permission (e.g. "edit post") that needs access check.
     * @param array $params name-value pairs that would be passed to the rules associated
     * with the roles and permissions assigned to the user. A param with name 'user' is added to
     * this array, which holds the value of [[id]].
648 649 650 651
     * @param boolean $allowCaching whether to allow caching the result of access check.
     * When this parameter is true (default), if the access check of an operation was performed
     * before, its result will be directly returned when calling this method to check the same
     * operation. If this parameter is false, this method will always call
652
     * [[\yii\rbac\ManagerInterface::checkAccess()]] to obtain the up-to-date access result. Note that this
653
     * caching is effective only within the same request and only works when `$params = []`.
654
     * @return boolean whether the user can perform the operation as specified by the given permission.
655
     */
656
    public function can($permissionName, $params = [], $allowCaching = true)
657 658
    {
        $auth = Yii::$app->getAuthManager();
659 660
        if ($allowCaching && empty($params) && isset($this->_access[$permissionName])) {
            return $this->_access[$permissionName];
661
        }
662
        $access = $auth->checkAccess($this->getId(), $permissionName, $params);
663
        if ($allowCaching && empty($params)) {
664
            $this->_access[$permissionName] = $access;
665 666 667 668
        }

        return $access;
    }
Qiang Xue committed
669
}