You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

670 lines
28KB

  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. namespace yii\web;
  8. use Yii;
  9. use yii\base\Component;
  10. use yii\base\InvalidConfigException;
  11. use yii\base\InvalidValueException;
  12. /**
  13. * User is the class for the "user" application component that manages the user authentication status.
  14. *
  15. * You may use [[isGuest]] to determine whether the current user is a guest or not.
  16. * If the user is a guest, the [[identity]] property would return null. Otherwise, it would
  17. * be an instance of [[IdentityInterface]].
  18. *
  19. * You may call various methods to change the user authentication status:
  20. *
  21. * - [[login()]]: sets the specified identity and remembers the authentication status in session and cookie.
  22. * - [[logout()]]: marks the user as a guest and clears the relevant information from session and cookie.
  23. * - [[setIdentity()]]: changes the user identity without touching session or cookie.
  24. * This is best used in stateless RESTful API implementation.
  25. *
  26. * Note that User only maintains the user authentication status. It does NOT handle how to authenticate
  27. * a user. The logic of how to authenticate a user should be done in the class implementing [[IdentityInterface]].
  28. * You are also required to set [[identityClass]] with the name of this class.
  29. *
  30. * User is configured as an application component in [[\yii\web\Application]] by default.
  31. * You can access that instance via `Yii::$app->user`.
  32. *
  33. * You can modify its configuration by adding an array to your application config under `components`
  34. * as it is shown in the following example:
  35. *
  36. * ~~~
  37. * 'user' => [
  38. * 'identityClass' => 'app\models\User', // User must implement the IdentityInterface
  39. * 'enableAutoLogin' => true,
  40. * // 'loginUrl' => ['user/login'],
  41. * // ...
  42. * ]
  43. * ~~~
  44. *
  45. * @property string|integer $id The unique identifier for the user. If null, it means the user is a guest.
  46. * This property is read-only.
  47. * @property IdentityInterface|null $identity The identity object associated with the currently logged-in
  48. * user. `null` is returned if the user is not logged in (not authenticated).
  49. * @property boolean $isGuest Whether the current user is a guest. This property is read-only.
  50. * @property string $returnUrl The URL that the user should be redirected to after login. Note that the type
  51. * of this property differs in getter and setter. See [[getReturnUrl()]] and [[setReturnUrl()]] for details.
  52. *
  53. * @author Qiang Xue <qiang.xue@gmail.com>
  54. * @since 2.0
  55. */
  56. class User extends Component
  57. {
  58. const EVENT_BEFORE_LOGIN = 'beforeLogin';
  59. const EVENT_AFTER_LOGIN = 'afterLogin';
  60. const EVENT_BEFORE_LOGOUT = 'beforeLogout';
  61. const EVENT_AFTER_LOGOUT = 'afterLogout';
  62. /**
  63. * @var string the class name of the [[identity]] object.
  64. */
  65. public $identityClass;
  66. /**
  67. * @var boolean whether to enable cookie-based login. Defaults to false.
  68. * Note that this property will be ignored if [[enableSession]] is false.
  69. */
  70. public $enableAutoLogin = false;
  71. /**
  72. * @var boolean whether to use session to persist authentication status across multiple requests.
  73. * You set this property to be false if your application is stateless, which is often the case
  74. * for RESTful APIs.
  75. */
  76. public $enableSession = true;
  77. /**
  78. * @var string|array the URL for login when [[loginRequired()]] is called.
  79. * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
  80. * The first element of the array should be the route to the login action, and the rest of
  81. * the name-value pairs are GET parameters used to construct the login URL. For example,
  82. *
  83. * ~~~
  84. * ['site/login', 'ref' => 1]
  85. * ~~~
  86. *
  87. * If this property is null, a 403 HTTP exception will be raised when [[loginRequired()]] is called.
  88. */
  89. public $loginUrl = ['site/login'];
  90. /**
  91. * @var array the configuration of the identity cookie. This property is used only when [[enableAutoLogin]] is true.
  92. * @see Cookie
  93. */
  94. public $identityCookie = ['name' => '_identity', 'httpOnly' => true];
  95. /**
  96. * @var integer the number of seconds in which the user will be logged out automatically if he
  97. * remains inactive. If this property is not set, the user will be logged out after
  98. * the current session expires (c.f. [[Session::timeout]]).
  99. * Note that this will not work if [[enableAutoLogin]] is true.
  100. */
  101. public $authTimeout;
  102. /**
  103. * @var integer the number of seconds in which the user will be logged out automatically
  104. * regardless of activity.
  105. * Note that this will not work if [[enableAutoLogin]] is true.
  106. */
  107. public $absoluteAuthTimeout;
  108. /**
  109. * @var boolean whether to automatically renew the identity cookie each time a page is requested.
  110. * This property is effective only when [[enableAutoLogin]] is true.
  111. * When this is false, the identity cookie will expire after the specified duration since the user
  112. * is initially logged in. When this is true, the identity cookie will expire after the specified duration
  113. * since the user visits the site the last time.
  114. * @see enableAutoLogin
  115. */
  116. public $autoRenewCookie = true;
  117. /**
  118. * @var string the session variable name used to store the value of [[id]].
  119. */
  120. public $idParam = '__id';
  121. /**
  122. * @var string the session variable name used to store the value of expiration timestamp of the authenticated state.
  123. * This is used when [[authTimeout]] is set.
  124. */
  125. public $authTimeoutParam = '__expire';
  126. /**
  127. * @var string the session variable name used to store the value of absolute expiration timestamp of the authenticated state.
  128. * This is used when [[absoluteAuthTimeout]] is set.
  129. */
  130. public $absoluteAuthTimeoutParam = '__absoluteExpire';
  131. /**
  132. * @var string the session variable name used to store the value of [[returnUrl]].
  133. */
  134. public $returnUrlParam = '__returnUrl';
  135. private $_access = [];
  136. /**
  137. * Initializes the application component.
  138. */
  139. public function init()
  140. {
  141. parent::init();
  142. if ($this->identityClass === null) {
  143. throw new InvalidConfigException('User::identityClass must be set.');
  144. }
  145. if ($this->enableAutoLogin && !isset($this->identityCookie['name'])) {
  146. throw new InvalidConfigException('User::identityCookie must contain the "name" element.');
  147. }
  148. }
  149. private $_identity = false;
  150. /**
  151. * Returns the identity object associated with the currently logged-in user.
  152. * When [[enableSession]] is true, this method may attempt to read the user's authentication data
  153. * stored in session and reconstruct the corresponding identity object, if it has not done so before.
  154. * @param boolean $autoRenew whether to automatically renew authentication status if it has not been done so before.
  155. * This is only useful when [[enableSession]] is true.
  156. * @return IdentityInterface|null the identity object associated with the currently logged-in user.
  157. * `null` is returned if the user is not logged in (not authenticated).
  158. * @see login()
  159. * @see logout()
  160. */
  161. public function getIdentity($autoRenew = true)
  162. {
  163. if ($this->_identity === false) {
  164. if ($this->enableSession && $autoRenew) {
  165. $this->_identity = null;
  166. $this->renewAuthStatus();
  167. } else {
  168. return null;
  169. }
  170. }
  171. return $this->_identity;
  172. }
  173. /**
  174. * Sets the user identity object.
  175. *
  176. * Note that this method does not deal with session or cookie. You should usually use [[switchIdentity()]]
  177. * to change the identity of the current user.
  178. *
  179. * @param IdentityInterface|null $identity the identity object associated with the currently logged user.
  180. * If null, it means the current user will be a guest without any associated identity.
  181. * @throws InvalidValueException if `$identity` object does not implement [[IdentityInterface]].
  182. */
  183. public function setIdentity($identity)
  184. {
  185. if ($identity instanceof IdentityInterface) {
  186. $this->_identity = $identity;
  187. $this->_access = [];
  188. } elseif ($identity === null) {
  189. $this->_identity = null;
  190. } else {
  191. throw new InvalidValueException('The identity object must implement IdentityInterface.');
  192. }
  193. }
  194. /**
  195. * Logs in a user.
  196. *
  197. * After logging in a user, you may obtain the user's identity information from the [[identity]] property.
  198. * If [[enableSession]] is true, you may even get the identity information in the next requests without
  199. * calling this method again.
  200. *
  201. * The login status is maintained according to the `$duration` parameter:
  202. *
  203. * - `$duration == 0`: the identity information will be stored in session and will be available
  204. * via [[identity]] as long as the session remains active.
  205. * - `$duration > 0`: the identity information will be stored in session. If [[enableAutoLogin]] is true,
  206. * it will also be stored in a cookie which will expire in `$duration` seconds. As long as
  207. * the cookie remains valid or the session is active, you may obtain the user identity information
  208. * via [[identity]].
  209. *
  210. * Note that if [[enableSession]] is false, the `$duration` parameter will be ignored as it is meaningless
  211. * in this case.
  212. *
  213. * @param IdentityInterface $identity the user identity (which should already be authenticated)
  214. * @param integer $duration number of seconds that the user can remain in logged-in status.
  215. * Defaults to 0, meaning login till the user closes the browser or the session is manually destroyed.
  216. * If greater than 0 and [[enableAutoLogin]] is true, cookie-based login will be supported.
  217. * Note that if [[enableSession]] is false, this parameter will be ignored.
  218. * @return boolean whether the user is logged in
  219. */
  220. public function login(IdentityInterface $identity, $duration = 0)
  221. {
  222. if ($this->beforeLogin($identity, false, $duration)) {
  223. $this->switchIdentity($identity, $duration);
  224. $id = $identity->getId();
  225. $ip = Yii::$app->getRequest()->getUserIP();
  226. if ($this->enableSession) {
  227. $log = "User '$id' logged in from $ip with duration $duration.";
  228. } else {
  229. $log = "User '$id' logged in from $ip. Session not enabled.";
  230. }
  231. Yii::info($log, __METHOD__);
  232. $this->afterLogin($identity, false, $duration);
  233. }
  234. return !$this->getIsGuest();
  235. }
  236. /**
  237. * Logs in a user by the given access token.
  238. * This method will first authenticate the user by calling [[IdentityInterface::findIdentityByAccessToken()]]
  239. * with the provided access token. If successful, it will call [[login()]] to log in the authenticated user.
  240. * If authentication fails or [[login()]] is unsuccessful, it will return null.
  241. * @param string $token the access token
  242. * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
  243. * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
  244. * @return IdentityInterface|null the identity associated with the given access token. Null is returned if
  245. * the access token is invalid or [[login()]] is unsuccessful.
  246. */
  247. public function loginByAccessToken($token, $type = null)
  248. {
  249. /* @var $class IdentityInterface */
  250. $class = $this->identityClass;
  251. $identity = $class::findIdentityByAccessToken($token, $type);
  252. if ($identity && $this->login($identity)) {
  253. return $identity;
  254. } else {
  255. return null;
  256. }
  257. }
  258. /**
  259. * Logs in a user by cookie.
  260. *
  261. * This method attempts to log in a user using the ID and authKey information
  262. * provided by the [[identityCookie|identity cookie]].
  263. */
  264. protected function loginByCookie()
  265. {
  266. $value = Yii::$app->getRequest()->getCookies()->getValue($this->identityCookie['name']);
  267. if ($value === null) {
  268. return;
  269. }
  270. $data = json_decode($value, true);
  271. if (count($data) !== 3 || !isset($data[0], $data[1], $data[2])) {
  272. return;
  273. }
  274. list ($id, $authKey, $duration) = $data;
  275. /* @var $class IdentityInterface */
  276. $class = $this->identityClass;
  277. $identity = $class::findIdentity($id);
  278. if ($identity === null) {
  279. return;
  280. } elseif (!$identity instanceof IdentityInterface) {
  281. throw new InvalidValueException("$class::findIdentity() must return an object implementing IdentityInterface.");
  282. }
  283. if ($identity->validateAuthKey($authKey)) {
  284. if ($this->beforeLogin($identity, true, $duration)) {
  285. $this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);
  286. $ip = Yii::$app->getRequest()->getUserIP();
  287. Yii::info("User '$id' logged in from $ip via cookie.", __METHOD__);
  288. $this->afterLogin($identity, true, $duration);
  289. }
  290. } else {
  291. Yii::warning("Invalid auth key attempted for user '$id': $authKey", __METHOD__);
  292. }
  293. }
  294. /**
  295. * Logs out the current user.
  296. * This will remove authentication-related session data.
  297. * If `$destroySession` is true, all session data will be removed.
  298. * @param boolean $destroySession whether to destroy the whole session. Defaults to true.
  299. * This parameter is ignored if [[enableSession]] is false.
  300. * @return boolean whether the user is logged out
  301. */
  302. public function logout($destroySession = true)
  303. {
  304. $identity = $this->getIdentity();
  305. if ($identity !== null && $this->beforeLogout($identity)) {
  306. $this->switchIdentity(null);
  307. $id = $identity->getId();
  308. $ip = Yii::$app->getRequest()->getUserIP();
  309. Yii::info("User '$id' logged out from $ip.", __METHOD__);
  310. if ($destroySession && $this->enableSession) {
  311. Yii::$app->getSession()->destroy();
  312. }
  313. $this->afterLogout($identity);
  314. }
  315. return $this->getIsGuest();
  316. }
  317. /**
  318. * Returns a value indicating whether the user is a guest (not authenticated).
  319. * @return boolean whether the current user is a guest.
  320. * @see getIdentity()
  321. */
  322. public function getIsGuest()
  323. {
  324. return $this->getIdentity() === null;
  325. }
  326. /**
  327. * Returns a value that uniquely represents the user.
  328. * @return string|integer the unique identifier for the user. If null, it means the user is a guest.
  329. * @see getIdentity()
  330. */
  331. public function getId()
  332. {
  333. $identity = $this->getIdentity();
  334. return $identity !== null ? $identity->getId() : null;
  335. }
  336. /**
  337. * Returns the URL that the browser should be redirected to after successful login.
  338. *
  339. * This method reads the return URL from the session. It is usually used by the login action which
  340. * may call this method to redirect the browser to where it goes after successful authentication.
  341. *
  342. * @param string|array $defaultUrl the default return URL in case it was not set previously.
  343. * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
  344. * Please refer to [[setReturnUrl()]] on accepted format of the URL.
  345. * @return string the URL that the user should be redirected to after login.
  346. * @see loginRequired()
  347. */
  348. public function getReturnUrl($defaultUrl = null)
  349. {
  350. $url = Yii::$app->getSession()->get($this->returnUrlParam, $defaultUrl);
  351. if (is_array($url)) {
  352. if (isset($url[0])) {
  353. return Yii::$app->getUrlManager()->createUrl($url);
  354. } else {
  355. $url = null;
  356. }
  357. }
  358. return $url === null ? Yii::$app->getHomeUrl() : $url;
  359. }
  360. /**
  361. * Remembers the URL in the session so that it can be retrieved back later by [[getReturnUrl()]].
  362. * @param string|array $url the URL that the user should be redirected to after login.
  363. * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
  364. * The first element of the array should be the route, and the rest of
  365. * the name-value pairs are GET parameters used to construct the URL. For example,
  366. *
  367. * ~~~
  368. * ['admin/index', 'ref' => 1]
  369. * ~~~
  370. */
  371. public function setReturnUrl($url)
  372. {
  373. Yii::$app->getSession()->set($this->returnUrlParam, $url);
  374. }
  375. /**
  376. * Redirects the user browser to the login page.
  377. *
  378. * Before the redirection, the current URL (if it's not an AJAX url) will be kept as [[returnUrl]] so that
  379. * the user browser may be redirected back to the current page after successful login.
  380. *
  381. * Make sure you set [[loginUrl]] so that the user browser can be redirected to the specified login URL after
  382. * calling this method.
  383. *
  384. * Note that when [[loginUrl]] is set, calling this method will NOT terminate the application execution.
  385. *
  386. * @param boolean $checkAjax whether to check if the request is an AJAX request. When this is true and the request
  387. * is an AJAX request, the current URL (for AJAX request) will NOT be set as the return URL.
  388. * @return Response the redirection response if [[loginUrl]] is set
  389. * @throws ForbiddenHttpException the "Access Denied" HTTP exception if [[loginUrl]] is not set
  390. */
  391. public function loginRequired($checkAjax = true)
  392. {
  393. $request = Yii::$app->getRequest();
  394. if ($this->enableSession && (!$checkAjax || !$request->getIsAjax())) {
  395. $this->setReturnUrl($request->getUrl());
  396. }
  397. if ($this->loginUrl !== null) {
  398. $loginUrl = (array)$this->loginUrl;
  399. if ($loginUrl[0] !== Yii::$app->requestedRoute) {
  400. return Yii::$app->getResponse()->redirect($this->loginUrl);
  401. }
  402. }
  403. throw new ForbiddenHttpException(Yii::t('yii', 'Login Required'));
  404. }
  405. /**
  406. * This method is called before logging in a user.
  407. * The default implementation will trigger the [[EVENT_BEFORE_LOGIN]] event.
  408. * If you override this method, make sure you call the parent implementation
  409. * so that the event is triggered.
  410. * @param IdentityInterface $identity the user identity information
  411. * @param boolean $cookieBased whether the login is cookie-based
  412. * @param integer $duration number of seconds that the user can remain in logged-in status.
  413. * If 0, it means login till the user closes the browser or the session is manually destroyed.
  414. * @return boolean whether the user should continue to be logged in
  415. */
  416. protected function beforeLogin($identity, $cookieBased, $duration)
  417. {
  418. $event = new UserEvent([
  419. 'identity' => $identity,
  420. 'cookieBased' => $cookieBased,
  421. 'duration' => $duration,
  422. ]);
  423. $this->trigger(self::EVENT_BEFORE_LOGIN, $event);
  424. return $event->isValid;
  425. }
  426. /**
  427. * This method is called after the user is successfully logged in.
  428. * The default implementation will trigger the [[EVENT_AFTER_LOGIN]] event.
  429. * If you override this method, make sure you call the parent implementation
  430. * so that the event is triggered.
  431. * @param IdentityInterface $identity the user identity information
  432. * @param boolean $cookieBased whether the login is cookie-based
  433. * @param integer $duration number of seconds that the user can remain in logged-in status.
  434. * If 0, it means login till the user closes the browser or the session is manually destroyed.
  435. */
  436. protected function afterLogin($identity, $cookieBased, $duration)
  437. {
  438. $this->trigger(self::EVENT_AFTER_LOGIN, new UserEvent([
  439. 'identity' => $identity,
  440. 'cookieBased' => $cookieBased,
  441. 'duration' => $duration,
  442. ]));
  443. }
  444. /**
  445. * This method is invoked when calling [[logout()]] to log out a user.
  446. * The default implementation will trigger the [[EVENT_BEFORE_LOGOUT]] event.
  447. * If you override this method, make sure you call the parent implementation
  448. * so that the event is triggered.
  449. * @param IdentityInterface $identity the user identity information
  450. * @return boolean whether the user should continue to be logged out
  451. */
  452. protected function beforeLogout($identity)
  453. {
  454. $event = new UserEvent([
  455. 'identity' => $identity,
  456. ]);
  457. $this->trigger(self::EVENT_BEFORE_LOGOUT, $event);
  458. return $event->isValid;
  459. }
  460. /**
  461. * This method is invoked right after a user is logged out via [[logout()]].
  462. * The default implementation will trigger the [[EVENT_AFTER_LOGOUT]] event.
  463. * If you override this method, make sure you call the parent implementation
  464. * so that the event is triggered.
  465. * @param IdentityInterface $identity the user identity information
  466. */
  467. protected function afterLogout($identity)
  468. {
  469. $this->trigger(self::EVENT_AFTER_LOGOUT, new UserEvent([
  470. 'identity' => $identity,
  471. ]));
  472. }
  473. /**
  474. * Renews the identity cookie.
  475. * This method will set the expiration time of the identity cookie to be the current time
  476. * plus the originally specified cookie duration.
  477. */
  478. protected function renewIdentityCookie()
  479. {
  480. $name = $this->identityCookie['name'];
  481. $value = Yii::$app->getRequest()->getCookies()->getValue($name);
  482. if ($value !== null) {
  483. $data = json_decode($value, true);
  484. if (is_array($data) && isset($data[2])) {
  485. $cookie = new Cookie($this->identityCookie);
  486. $cookie->value = $value;
  487. $cookie->expire = time() + (int) $data[2];
  488. Yii::$app->getResponse()->getCookies()->add($cookie);
  489. }
  490. }
  491. }
  492. /**
  493. * Sends an identity cookie.
  494. * This method is used when [[enableAutoLogin]] is true.
  495. * It saves [[id]], [[IdentityInterface::getAuthKey()|auth key]], and the duration of cookie-based login
  496. * information in the cookie.
  497. * @param IdentityInterface $identity
  498. * @param integer $duration number of seconds that the user can remain in logged-in status.
  499. * @see loginByCookie()
  500. */
  501. protected function sendIdentityCookie($identity, $duration)
  502. {
  503. $cookie = new Cookie($this->identityCookie);
  504. $cookie->value = json_encode([
  505. $identity->getId(),
  506. $identity->getAuthKey(),
  507. $duration,
  508. ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  509. $cookie->expire = time() + $duration;
  510. Yii::$app->getResponse()->getCookies()->add($cookie);
  511. }
  512. /**
  513. * Switches to a new identity for the current user.
  514. *
  515. * When [[enableSession]] is true, this method may use session and/or cookie to store the user identity information,
  516. * according to the value of `$duration`. Please refer to [[login()]] for more details.
  517. *
  518. * This method is mainly called by [[login()]], [[logout()]] and [[loginByCookie()]]
  519. * when the current user needs to be associated with the corresponding identity information.
  520. *
  521. * @param IdentityInterface|null $identity the identity information to be associated with the current user.
  522. * If null, it means switching the current user to be a guest.
  523. * @param integer $duration number of seconds that the user can remain in logged-in status.
  524. * This parameter is used only when `$identity` is not null.
  525. */
  526. public function switchIdentity($identity, $duration = 0)
  527. {
  528. $this->setIdentity($identity);
  529. if (!$this->enableSession) {
  530. return;
  531. }
  532. $session = Yii::$app->getSession();
  533. if (!YII_ENV_TEST) {
  534. $session->regenerateID(true);
  535. }
  536. $session->remove($this->idParam);
  537. $session->remove($this->authTimeoutParam);
  538. if ($identity) {
  539. $session->set($this->idParam, $identity->getId());
  540. if ($this->authTimeout !== null) {
  541. $session->set($this->authTimeoutParam, time() + $this->authTimeout);
  542. }
  543. if ($this->absoluteAuthTimeout !== null) {
  544. $session->set($this->absoluteAuthTimeoutParam, time() + $this->absoluteAuthTimeout);
  545. }
  546. if ($duration > 0 && $this->enableAutoLogin) {
  547. $this->sendIdentityCookie($identity, $duration);
  548. }
  549. } elseif ($this->enableAutoLogin) {
  550. Yii::$app->getResponse()->getCookies()->remove(new Cookie($this->identityCookie));
  551. }
  552. }
  553. /**
  554. * Updates the authentication status using the information from session and cookie.
  555. *
  556. * This method will try to determine the user identity using the [[idParam]] session variable.
  557. *
  558. * If [[authTimeout]] is set, this method will refresh the timer.
  559. *
  560. * If the user identity cannot be determined by session, this method will try to [[loginByCookie()|login by cookie]]
  561. * if [[enableAutoLogin]] is true.
  562. */
  563. protected function renewAuthStatus()
  564. {
  565. $session = Yii::$app->getSession();
  566. $id = $session->getHasSessionId() || $session->getIsActive() ? $session->get($this->idParam) : null;
  567. if ($id === null) {
  568. $identity = null;
  569. } else {
  570. /* @var $class IdentityInterface */
  571. $class = $this->identityClass;
  572. $identity = $class::findIdentity($id);
  573. }
  574. $this->setIdentity($identity);
  575. if ($identity !== null && ($this->authTimeout !== null || $this->absoluteAuthTimeout !== null)) {
  576. $expire = $this->authTimeout !== null ? $session->get($this->authTimeoutParam) : null;
  577. $expireAbsolute = $this->absoluteAuthTimeout !== null ? $session->get($this->absoluteAuthTimeoutParam) : null;
  578. if ($expire !== null && $expire < time() || $expireAbsolute !== null && $expireAbsolute < time()) {
  579. $this->logout(false);
  580. } elseif ($this->authTimeout !== null) {
  581. $session->set($this->authTimeoutParam, time() + $this->authTimeout);
  582. }
  583. }
  584. if ($this->enableAutoLogin) {
  585. if ($this->getIsGuest()) {
  586. $this->loginByCookie();
  587. } elseif ($this->autoRenewCookie) {
  588. $this->renewIdentityCookie();
  589. }
  590. }
  591. }
  592. /**
  593. * Checks if the user can perform the operation as specified by the given permission.
  594. *
  595. * Note that you must configure "authManager" application component in order to use this method.
  596. * Otherwise an exception will be thrown.
  597. *
  598. * @param string $permissionName the name of the permission (e.g. "edit post") that needs access check.
  599. * @param array $params name-value pairs that would be passed to the rules associated
  600. * with the roles and permissions assigned to the user. A param with name 'user' is added to
  601. * this array, which holds the value of [[id]].
  602. * @param boolean $allowCaching whether to allow caching the result of access check.
  603. * When this parameter is true (default), if the access check of an operation was performed
  604. * before, its result will be directly returned when calling this method to check the same
  605. * operation. If this parameter is false, this method will always call
  606. * [[\yii\rbac\ManagerInterface::checkAccess()]] to obtain the up-to-date access result. Note that this
  607. * caching is effective only within the same request and only works when `$params = []`.
  608. * @return boolean whether the user can perform the operation as specified by the given permission.
  609. */
  610. public function can($permissionName, $params = [], $allowCaching = true)
  611. {
  612. $auth = Yii::$app->getAuthManager();
  613. if ($allowCaching && empty($params) && isset($this->_access[$permissionName])) {
  614. return $this->_access[$permissionName];
  615. }
  616. $access = $auth->checkAccess($this->getId(), $permissionName, $params);
  617. if ($allowCaching && empty($params)) {
  618. $this->_access[$permissionName] = $access;
  619. }
  620. return $access;
  621. }
  622. }