User.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  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|int $id The unique identifier for the user. If `null`, it means the user is a guest. This
  47. * 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 bool $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 bool 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 bool 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 int 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 int 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 bool 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 bool $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:
  210. * - the user's identity information is obtainable from the [[identity]] property
  211. *
  212. * If [[enableSession]] is `true`:
  213. * - the identity information will be stored in session and be available in the next requests
  214. * - in case of `$duration == 0`: as long as the session remains active or till the user closes the browser
  215. * - in case of `$duration > 0`: as long as the session remains active or as long as the cookie
  216. * remains valid by it's `$duration` in seconds when [[enableAutoLogin]] is set `true`.
  217. *
  218. * If [[enableSession]] is `false`:
  219. * - the `$duration` parameter will be ignored
  220. *
  221. * @param IdentityInterface $identity the user identity (which should already be authenticated)
  222. * @param int $duration number of seconds that the user can remain in logged-in status, defaults to `0`
  223. * @return bool whether the user is logged in
  224. */
  225. public function login(IdentityInterface $identity, $duration = 0)
  226. {
  227. if ($this->beforeLogin($identity, false, $duration)) {
  228. $this->switchIdentity($identity, $duration);
  229. $id = $identity->getId();
  230. $ip = Yii::$app->getRequest()->getUserIP();
  231. if ($this->enableSession) {
  232. $log = "User '$id' logged in from $ip with duration $duration.";
  233. } else {
  234. $log = "User '$id' logged in from $ip. Session not enabled.";
  235. }
  236. Yii::info($log, __METHOD__);
  237. $this->afterLogin($identity, false, $duration);
  238. }
  239. return !$this->getIsGuest();
  240. }
  241. /**
  242. * Logs in a user by the given access token.
  243. * This method will first authenticate the user by calling [[IdentityInterface::findIdentityByAccessToken()]]
  244. * with the provided access token. If successful, it will call [[login()]] to log in the authenticated user.
  245. * If authentication fails or [[login()]] is unsuccessful, it will return null.
  246. * @param string $token the access token
  247. * @param mixed $type the type of the token. The value of this parameter depends on the implementation.
  248. * For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
  249. * @return IdentityInterface|null the identity associated with the given access token. Null is returned if
  250. * the access token is invalid or [[login()]] is unsuccessful.
  251. */
  252. public function loginByAccessToken($token, $type = null)
  253. {
  254. /* @var $class IdentityInterface */
  255. $class = $this->identityClass;
  256. $identity = $class::findIdentityByAccessToken($token, $type);
  257. if ($identity && $this->login($identity)) {
  258. return $identity;
  259. } else {
  260. return null;
  261. }
  262. }
  263. /**
  264. * Logs in a user by cookie.
  265. *
  266. * This method attempts to log in a user using the ID and authKey information
  267. * provided by the [[identityCookie|identity cookie]].
  268. */
  269. protected function loginByCookie()
  270. {
  271. $data = $this->getIdentityAndDurationFromCookie();
  272. if (isset($data['identity'], $data['duration'])) {
  273. $identity = $data['identity'];
  274. $duration = $data['duration'];
  275. if ($this->beforeLogin($identity, true, $duration)) {
  276. $this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);
  277. $id = $identity->getId();
  278. $ip = Yii::$app->getRequest()->getUserIP();
  279. Yii::info("User '$id' logged in from $ip via cookie.", __METHOD__);
  280. $this->afterLogin($identity, true, $duration);
  281. }
  282. }
  283. }
  284. /**
  285. * Logs out the current user.
  286. * This will remove authentication-related session data.
  287. * If `$destroySession` is true, all session data will be removed.
  288. * @param bool $destroySession whether to destroy the whole session. Defaults to true.
  289. * This parameter is ignored if [[enableSession]] is false.
  290. * @return bool whether the user is logged out
  291. */
  292. public function logout($destroySession = true)
  293. {
  294. $identity = $this->getIdentity();
  295. if ($identity !== null && $this->beforeLogout($identity)) {
  296. $this->switchIdentity(null);
  297. $id = $identity->getId();
  298. $ip = Yii::$app->getRequest()->getUserIP();
  299. Yii::info("User '$id' logged out from $ip.", __METHOD__);
  300. if ($destroySession && $this->enableSession) {
  301. Yii::$app->getSession()->destroy();
  302. }
  303. $this->afterLogout($identity);
  304. }
  305. return $this->getIsGuest();
  306. }
  307. /**
  308. * Returns a value indicating whether the user is a guest (not authenticated).
  309. * @return bool whether the current user is a guest.
  310. * @see getIdentity()
  311. */
  312. public function getIsGuest()
  313. {
  314. return $this->getIdentity() === null;
  315. }
  316. /**
  317. * Returns a value that uniquely represents the user.
  318. * @return string|int the unique identifier for the user. If `null`, it means the user is a guest.
  319. * @see getIdentity()
  320. */
  321. public function getId()
  322. {
  323. $identity = $this->getIdentity();
  324. return $identity !== null ? $identity->getId() : null;
  325. }
  326. /**
  327. * Returns the URL that the browser should be redirected to after successful login.
  328. *
  329. * This method reads the return URL from the session. It is usually used by the login action which
  330. * may call this method to redirect the browser to where it goes after successful authentication.
  331. *
  332. * @param string|array $defaultUrl the default return URL in case it was not set previously.
  333. * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
  334. * Please refer to [[setReturnUrl()]] on accepted format of the URL.
  335. * @return string the URL that the user should be redirected to after login.
  336. * @see loginRequired()
  337. */
  338. public function getReturnUrl($defaultUrl = null)
  339. {
  340. $url = Yii::$app->getSession()->get($this->returnUrlParam, $defaultUrl);
  341. if (is_array($url)) {
  342. if (isset($url[0])) {
  343. return Yii::$app->getUrlManager()->createUrl($url);
  344. } else {
  345. $url = null;
  346. }
  347. }
  348. return $url === null ? Yii::$app->getHomeUrl() : $url;
  349. }
  350. /**
  351. * Remembers the URL in the session so that it can be retrieved back later by [[getReturnUrl()]].
  352. * @param string|array $url the URL that the user should be redirected to after login.
  353. * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
  354. * The first element of the array should be the route, and the rest of
  355. * the name-value pairs are GET parameters used to construct the URL. For example,
  356. *
  357. * ```php
  358. * ['admin/index', 'ref' => 1]
  359. * ```
  360. */
  361. public function setReturnUrl($url)
  362. {
  363. Yii::$app->getSession()->set($this->returnUrlParam, $url);
  364. }
  365. /**
  366. * Redirects the user browser to the login page.
  367. *
  368. * Before the redirection, the current URL (if it's not an AJAX url) will be kept as [[returnUrl]] so that
  369. * the user browser may be redirected back to the current page after successful login.
  370. *
  371. * Make sure you set [[loginUrl]] so that the user browser can be redirected to the specified login URL after
  372. * calling this method.
  373. *
  374. * Note that when [[loginUrl]] is set, calling this method will NOT terminate the application execution.
  375. *
  376. * @param bool $checkAjax whether to check if the request is an AJAX request. When this is true and the request
  377. * is an AJAX request, the current URL (for AJAX request) will NOT be set as the return URL.
  378. * @param bool $checkAcceptHeader whether to check if the request accepts HTML responses. Defaults to `true`. When this is true and
  379. * the request does not accept HTML responses the current URL will not be SET as the return URL. Also instead of
  380. * redirecting the user an ForbiddenHttpException is thrown. This parameter is available since version 2.0.8.
  381. * @return Response the redirection response if [[loginUrl]] is set
  382. * @throws ForbiddenHttpException the "Access Denied" HTTP exception if [[loginUrl]] is not set or a redirect is
  383. * not applicable.
  384. */
  385. public function loginRequired($checkAjax = true, $checkAcceptHeader = true)
  386. {
  387. $request = Yii::$app->getRequest();
  388. $canRedirect = !$checkAcceptHeader || $this->checkRedirectAcceptable();
  389. if ($this->enableSession
  390. && $request->getIsGet()
  391. && (!$checkAjax || !$request->getIsAjax())
  392. && $canRedirect
  393. ) {
  394. $this->setReturnUrl($request->getUrl());
  395. }
  396. if ($this->loginUrl !== null && $canRedirect) {
  397. $loginUrl = (array) $this->loginUrl;
  398. if ($loginUrl[0] !== Yii::$app->requestedRoute) {
  399. return Yii::$app->getResponse()->redirect($this->loginUrl);
  400. }
  401. }
  402. throw new ForbiddenHttpException(Yii::t('yii', 'Login Required'));
  403. }
  404. /**
  405. * This method is called before logging in a user.
  406. * The default implementation will trigger the [[EVENT_BEFORE_LOGIN]] event.
  407. * If you override this method, make sure you call the parent implementation
  408. * so that the event is triggered.
  409. * @param IdentityInterface $identity the user identity information
  410. * @param bool $cookieBased whether the login is cookie-based
  411. * @param int $duration number of seconds that the user can remain in logged-in status.
  412. * If 0, it means login till the user closes the browser or the session is manually destroyed.
  413. * @return bool whether the user should continue to be logged in
  414. */
  415. protected function beforeLogin($identity, $cookieBased, $duration)
  416. {
  417. $event = new UserEvent([
  418. 'identity' => $identity,
  419. 'cookieBased' => $cookieBased,
  420. 'duration' => $duration,
  421. ]);
  422. $this->trigger(self::EVENT_BEFORE_LOGIN, $event);
  423. return $event->isValid;
  424. }
  425. /**
  426. * This method is called after the user is successfully logged in.
  427. * The default implementation will trigger the [[EVENT_AFTER_LOGIN]] event.
  428. * If you override this method, make sure you call the parent implementation
  429. * so that the event is triggered.
  430. * @param IdentityInterface $identity the user identity information
  431. * @param bool $cookieBased whether the login is cookie-based
  432. * @param int $duration number of seconds that the user can remain in logged-in status.
  433. * If 0, it means login till the user closes the browser or the session is manually destroyed.
  434. */
  435. protected function afterLogin($identity, $cookieBased, $duration)
  436. {
  437. $this->trigger(self::EVENT_AFTER_LOGIN, new UserEvent([
  438. 'identity' => $identity,
  439. 'cookieBased' => $cookieBased,
  440. 'duration' => $duration,
  441. ]));
  442. }
  443. /**
  444. * This method is invoked when calling [[logout()]] to log out a user.
  445. * The default implementation will trigger the [[EVENT_BEFORE_LOGOUT]] event.
  446. * If you override this method, make sure you call the parent implementation
  447. * so that the event is triggered.
  448. * @param IdentityInterface $identity the user identity information
  449. * @return bool whether the user should continue to be logged out
  450. */
  451. protected function beforeLogout($identity)
  452. {
  453. $event = new UserEvent([
  454. 'identity' => $identity,
  455. ]);
  456. $this->trigger(self::EVENT_BEFORE_LOGOUT, $event);
  457. return $event->isValid;
  458. }
  459. /**
  460. * This method is invoked right after a user is logged out via [[logout()]].
  461. * The default implementation will trigger the [[EVENT_AFTER_LOGOUT]] event.
  462. * If you override this method, make sure you call the parent implementation
  463. * so that the event is triggered.
  464. * @param IdentityInterface $identity the user identity information
  465. */
  466. protected function afterLogout($identity)
  467. {
  468. $this->trigger(self::EVENT_AFTER_LOGOUT, new UserEvent([
  469. 'identity' => $identity,
  470. ]));
  471. }
  472. /**
  473. * Renews the identity cookie.
  474. * This method will set the expiration time of the identity cookie to be the current time
  475. * plus the originally specified cookie duration.
  476. */
  477. protected function renewIdentityCookie()
  478. {
  479. $name = $this->identityCookie['name'];
  480. $value = Yii::$app->getRequest()->getCookies()->getValue($name);
  481. if ($value !== null) {
  482. $data = json_decode($value, true);
  483. if (is_array($data) && isset($data[2])) {
  484. $cookie = new Cookie($this->identityCookie);
  485. $cookie->value = $value;
  486. $cookie->expire = time() + (int) $data[2];
  487. Yii::$app->getResponse()->getCookies()->add($cookie);
  488. }
  489. }
  490. }
  491. /**
  492. * Sends an identity cookie.
  493. * This method is used when [[enableAutoLogin]] is true.
  494. * It saves [[id]], [[IdentityInterface::getAuthKey()|auth key]], and the duration of cookie-based login
  495. * information in the cookie.
  496. * @param IdentityInterface $identity
  497. * @param int $duration number of seconds that the user can remain in logged-in status.
  498. * @see loginByCookie()
  499. */
  500. protected function sendIdentityCookie($identity, $duration)
  501. {
  502. $cookie = new Cookie($this->identityCookie);
  503. $cookie->value = json_encode([
  504. $identity->getId(),
  505. $identity->getAuthKey(),
  506. $duration,
  507. ], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  508. $cookie->expire = time() + $duration;
  509. Yii::$app->getResponse()->getCookies()->add($cookie);
  510. }
  511. /**
  512. * Determines if an identity cookie has a valid format and contains a valid auth key.
  513. * This method is used when [[enableAutoLogin]] is true.
  514. * This method attempts to authenticate a user using the information in the identity cookie.
  515. * @return array|null Returns an array of 'identity' and 'duration' if valid, otherwise null.
  516. * @see loginByCookie()
  517. * @since 2.0.9
  518. */
  519. protected function getIdentityAndDurationFromCookie()
  520. {
  521. $value = Yii::$app->getRequest()->getCookies()->getValue($this->identityCookie['name']);
  522. if ($value === null) {
  523. return null;
  524. }
  525. $data = json_decode($value, true);
  526. if (count($data) == 3) {
  527. list ($id, $authKey, $duration) = $data;
  528. /* @var $class IdentityInterface */
  529. $class = $this->identityClass;
  530. $identity = $class::findIdentity($id);
  531. if ($identity !== null) {
  532. if (!$identity instanceof IdentityInterface) {
  533. throw new InvalidValueException("$class::findIdentity() must return an object implementing IdentityInterface.");
  534. } elseif (!$identity->validateAuthKey($authKey)) {
  535. Yii::warning("Invalid auth key attempted for user '$id': $authKey", __METHOD__);
  536. } else {
  537. return ['identity' => $identity, 'duration' => $duration];
  538. }
  539. }
  540. }
  541. $this->removeIdentityCookie();
  542. return null;
  543. }
  544. /**
  545. * Removes the identity cookie.
  546. * This method is used when [[enableAutoLogin]] is true.
  547. * @since 2.0.9
  548. */
  549. protected function removeIdentityCookie()
  550. {
  551. Yii::$app->getResponse()->getCookies()->remove(new Cookie($this->identityCookie));
  552. }
  553. /**
  554. * Switches to a new identity for the current user.
  555. *
  556. * When [[enableSession]] is true, this method may use session and/or cookie to store the user identity information,
  557. * according to the value of `$duration`. Please refer to [[login()]] for more details.
  558. *
  559. * This method is mainly called by [[login()]], [[logout()]] and [[loginByCookie()]]
  560. * when the current user needs to be associated with the corresponding identity information.
  561. *
  562. * @param IdentityInterface|null $identity the identity information to be associated with the current user.
  563. * If null, it means switching the current user to be a guest.
  564. * @param int $duration number of seconds that the user can remain in logged-in status.
  565. * This parameter is used only when `$identity` is not null.
  566. */
  567. public function switchIdentity($identity, $duration = 0)
  568. {
  569. $this->setIdentity($identity);
  570. if (!$this->enableSession) {
  571. return;
  572. }
  573. /* Ensure any existing identity cookies are removed. */
  574. if ($this->enableAutoLogin) {
  575. $this->removeIdentityCookie();
  576. }
  577. $session = Yii::$app->getSession();
  578. if (!YII_ENV_TEST) {
  579. $session->regenerateID(true);
  580. }
  581. $session->remove($this->idParam);
  582. $session->remove($this->authTimeoutParam);
  583. if ($identity) {
  584. $session->set($this->idParam, $identity->getId());
  585. if ($this->authTimeout !== null) {
  586. $session->set($this->authTimeoutParam, time() + $this->authTimeout);
  587. }
  588. if ($this->absoluteAuthTimeout !== null) {
  589. $session->set($this->absoluteAuthTimeoutParam, time() + $this->absoluteAuthTimeout);
  590. }
  591. if ($duration > 0 && $this->enableAutoLogin) {
  592. $this->sendIdentityCookie($identity, $duration);
  593. }
  594. }
  595. }
  596. /**
  597. * Updates the authentication status using the information from session and cookie.
  598. *
  599. * This method will try to determine the user identity using the [[idParam]] session variable.
  600. *
  601. * If [[authTimeout]] is set, this method will refresh the timer.
  602. *
  603. * If the user identity cannot be determined by session, this method will try to [[loginByCookie()|login by cookie]]
  604. * if [[enableAutoLogin]] is true.
  605. */
  606. protected function renewAuthStatus()
  607. {
  608. $session = Yii::$app->getSession();
  609. $id = $session->getHasSessionId() || $session->getIsActive() ? $session->get($this->idParam) : null;
  610. if ($id === null) {
  611. $identity = null;
  612. } else {
  613. /* @var $class IdentityInterface */
  614. $class = $this->identityClass;
  615. $identity = $class::findIdentity($id);
  616. }
  617. $this->setIdentity($identity);
  618. if ($identity !== null && ($this->authTimeout !== null || $this->absoluteAuthTimeout !== null)) {
  619. $expire = $this->authTimeout !== null ? $session->get($this->authTimeoutParam) : null;
  620. $expireAbsolute = $this->absoluteAuthTimeout !== null ? $session->get($this->absoluteAuthTimeoutParam) : null;
  621. if ($expire !== null && $expire < time() || $expireAbsolute !== null && $expireAbsolute < time()) {
  622. $this->logout(false);
  623. } elseif ($this->authTimeout !== null) {
  624. $session->set($this->authTimeoutParam, time() + $this->authTimeout);
  625. }
  626. }
  627. if ($this->enableAutoLogin) {
  628. if ($this->getIsGuest()) {
  629. $this->loginByCookie();
  630. } elseif ($this->autoRenewCookie) {
  631. $this->renewIdentityCookie();
  632. }
  633. }
  634. }
  635. /**
  636. * Checks if the user can perform the operation as specified by the given permission.
  637. *
  638. * Note that you must configure "authManager" application component in order to use this method.
  639. * Otherwise it will always return false.
  640. *
  641. * @param string $permissionName the name of the permission (e.g. "edit post") that needs access check.
  642. * @param array $params name-value pairs that would be passed to the rules associated
  643. * with the roles and permissions assigned to the user.
  644. * @param bool $allowCaching whether to allow caching the result of access check.
  645. * When this parameter is true (default), if the access check of an operation was performed
  646. * before, its result will be directly returned when calling this method to check the same
  647. * operation. If this parameter is false, this method will always call
  648. * [[\yii\rbac\CheckAccessInterface::checkAccess()]] to obtain the up-to-date access result. Note that this
  649. * caching is effective only within the same request and only works when `$params = []`.
  650. * @return bool whether the user can perform the operation as specified by the given permission.
  651. */
  652. public function can($permissionName, $params = [], $allowCaching = true)
  653. {
  654. if ($allowCaching && empty($params) && isset($this->_access[$permissionName])) {
  655. return $this->_access[$permissionName];
  656. }
  657. if (($accessChecker = $this->getAccessChecker()) === null) {
  658. return false;
  659. }
  660. $access = $accessChecker->checkAccess($this->getId(), $permissionName, $params);
  661. if ($allowCaching && empty($params)) {
  662. $this->_access[$permissionName] = $access;
  663. }
  664. return $access;
  665. }
  666. /**
  667. * Checks if the `Accept` header contains a content type that allows redirection to the login page.
  668. * The login page is assumed to serve `text/html` or `application/xhtml+xml` by default. You can change acceptable
  669. * content types by modifying [[acceptableRedirectTypes]] property.
  670. * @return bool whether this request may be redirected to the login page.
  671. * @see acceptableRedirectTypes
  672. * @since 2.0.8
  673. */
  674. protected function checkRedirectAcceptable()
  675. {
  676. $acceptableTypes = Yii::$app->getRequest()->getAcceptableContentTypes();
  677. if (empty($acceptableTypes) || count($acceptableTypes) === 1 && array_keys($acceptableTypes)[0] === '*/*') {
  678. return true;
  679. }
  680. foreach ($acceptableTypes as $type => $params) {
  681. if (in_array($type, $this->acceptableRedirectTypes, true)) {
  682. return true;
  683. }
  684. }
  685. return false;
  686. }
  687. /**
  688. * Returns auth manager associated with the user component.
  689. *
  690. * By default this is the `authManager` application component.
  691. * You may override this method to return a different auth manager instance if needed.
  692. * @return \yii\rbac\ManagerInterface
  693. * @since 2.0.6
  694. * @deprecated since version 2.0.9, to be removed in 2.1. Use [[getAccessChecker()]] instead.
  695. */
  696. protected function getAuthManager()
  697. {
  698. return Yii::$app->getAuthManager();
  699. }
  700. /**
  701. * Returns the access checker used for checking access.
  702. * @return CheckAccessInterface
  703. * @since 2.0.9
  704. */
  705. protected function getAccessChecker()
  706. {
  707. return $this->accessChecker !== null ? $this->accessChecker : $this->getAuthManager();
  708. }
  709. }