User.php 32 KB

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