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.

770 lines
32KB

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