User.php 33 KB

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