User.php 32 KB

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