User.php 33 KB

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