User.php 34 KB

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