User.php 21.8 KB
Newer Older
Qiang Xue committed
1 2 3 4 5 6 7 8 9
<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace yii\web;

Qiang Xue committed
10
use Yii;
Qiang Xue committed
11
use yii\base\Component;
Qiang Xue committed
12
use yii\base\InvalidConfigException;
Qiang Xue committed
13 14

/**
15
 * User is the class for the "user" application component that manages the user authentication status.
Qiang Xue committed
16
 *
17 18 19
 * You may use [[isGuest]] to determine whether the current user is a guest or not.
 * If the user is a guest, the [[identity]] property would return null. Otherwise, it would
 * be an instance of [[IdentityInterface]].
Qiang Xue committed
20
 *
21 22 23 24 25 26 27 28 29 30
 * You may call various methods to change the user authentication status:
 *
 * - [[login()]]: sets the specified identity and remembers the authentication status in session and cookie.
 * - [[logout()]]: marks the user as a guest and clears the relevant information from session and cookie.
 * - [[setIdentity()]]: changes the user identity without touching session or cookie.
 *   This is best used in stateless RESTful API implementation.
 *
 * Note that User only maintains the user authentication status. It does NOT handle how to authenticate
 * a user. The logic of how to authenticate a user should be done in the class implementing [[IdentityInterface]].
 * You are also required to set [[identityClass]] with the name of this class.
Qiang Xue committed
31
 *
32
 * User is configured as an application component in [[\yii\web\Application]] by default.
33 34 35 36 37 38 39 40 41 42 43 44 45 46
 * You can access that instance via `Yii::$app->user`.
 *
 * You can modify its configuration by adding an array to your application config under `components`
 * as it is shown in the following example:
 *
 * ~~~
 * 'user' => [
 *     'identityClass' => 'app\models\User', // User must implement the IdentityInterface
 *     'enableAutoLogin' => true,
 *     // 'loginUrl' => ['user/login'],
 *     // ...
 * ]
 * ~~~
 *
47
 * @property string|integer $id The unique identifier for the user. If null, it means the user is a guest.
48
 * This property is read-only.
Qiang Xue committed
49 50
 * @property IdentityInterface $identity The identity object associated with the currently logged user. Null
 * is returned if the user is not logged in (not authenticated).
51
 * @property boolean $isGuest Whether the current user is a guest. This property is read-only.
52 53
 * @property string $returnUrl The URL that the user should be redirected to after login. Note that the type
 * of this property differs in getter and setter. See [[getReturnUrl()]] and [[setReturnUrl()]] for details.
54
 *
Qiang Xue committed
55 56 57 58 59
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class User extends Component
{
Qiang Xue committed
60 61 62 63 64 65
	const EVENT_BEFORE_LOGIN = 'beforeLogin';
	const EVENT_AFTER_LOGIN = 'afterLogin';
	const EVENT_BEFORE_LOGOUT = 'beforeLogout';
	const EVENT_AFTER_LOGOUT = 'afterLogout';

	/**
Qiang Xue committed
66
	 * @var string the class name of the [[identity]] object.
Qiang Xue committed
67 68
	 */
	public $identityClass;
Qiang Xue committed
69 70 71
	/**
	 * @var boolean whether to enable cookie-based login. Defaults to false.
	 */
Qiang Xue committed
72
	public $enableAutoLogin = false;
Qiang Xue committed
73
	/**
74
	 * @var string|array the URL for login when [[loginRequired()]] is called.
Qiang Xue committed
75
	 * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
76
	 * The first element of the array should be the route to the login action, and the rest of
Qiang Xue committed
77
	 * the name-value pairs are GET parameters used to construct the login URL. For example,
78
	 *
Qiang Xue committed
79
	 * ~~~
Alexander Makarov committed
80
	 * ['site/login', 'ref' => 1]
Qiang Xue committed
81 82 83
	 * ~~~
	 *
	 * If this property is null, a 403 HTTP exception will be raised when [[loginRequired()]] is called.
Qiang Xue committed
84
	 */
Alexander Makarov committed
85
	public $loginUrl = ['site/login'];
Qiang Xue committed
86
	/**
Qiang Xue committed
87 88
	 * @var array the configuration of the identity cookie. This property is used only when [[enableAutoLogin]] is true.
	 * @see Cookie
Qiang Xue committed
89
	 */
Alexander Makarov committed
90
	public $identityCookie = ['name' => '_identity', 'httpOnly' => true];
Qiang Xue committed
91
	/**
Qiang Xue committed
92 93 94
	 * @var integer the number of seconds in which the user will be logged out automatically if he
	 * remains inactive. If this property is not set, the user will be logged out after
	 * the current session expires (c.f. [[Session::timeout]]).
Qiang Xue committed
95 96 97 98
	 */
	public $authTimeout;
	/**
	 * @var boolean whether to automatically renew the identity cookie each time a page is requested.
Qiang Xue committed
99
	 * This property is effective only when [[enableAutoLogin]] is true.
Qiang Xue committed
100 101 102
	 * When this is false, the identity cookie will expire after the specified duration since the user
	 * is initially logged in. When this is true, the identity cookie will expire after the specified duration
	 * since the user visits the site the last time.
Qiang Xue committed
103
	 * @see enableAutoLogin
Qiang Xue committed
104
	 */
Qiang Xue committed
105
	public $autoRenewCookie = true;
Qiang Xue committed
106 107 108
	/**
	 * @var string the session variable name used to store the value of [[id]].
	 */
109
	public $idParam = '__id';
Qiang Xue committed
110 111 112 113
	/**
	 * @var string the session variable name used to store the value of expiration timestamp of the authenticated state.
	 * This is used when [[authTimeout]] is set.
	 */
114
	public $authTimeoutParam = '__expire';
Qiang Xue committed
115 116 117
	/**
	 * @var string the session variable name used to store the value of [[returnUrl]].
	 */
118
	public $returnUrlParam = '__returnUrl';
Qiang Xue committed
119

Alexander Makarov committed
120
	private $_access = [];
121

Qiang Xue committed
122 123 124 125 126 127 128

	/**
	 * Initializes the application component.
	 */
	public function init()
	{
		parent::init();
Qiang Xue committed
129

130 131 132
		if ($this->identityClass === null) {
			throw new InvalidConfigException('User::identityClass must be set.');
		}
Qiang Xue committed
133 134 135 136 137
		if ($this->enableAutoLogin && !isset($this->identityCookie['name'])) {
			throw new InvalidConfigException('User::identityCookie must contain the "name" element.');
		}
	}

138 139
	private $_identity = false;

Qiang Xue committed
140
	/**
141 142 143 144 145
	 * Returns the identity object associated with the currently logged-in user.
	 * @param boolean $checkSession whether to check the session if the identity has never been determined before.
	 * If the identity is already determined (e.g., by calling [[setIdentity()]] or [[login()]]),
	 * then this parameter has no effect.
	 * @return IdentityInterface the identity object associated with the currently logged-in user.
146
	 * Null is returned if the user is not logged in (not authenticated).
Taras Gudz committed
147 148
	 * @see login()
	 * @see logout()
Qiang Xue committed
149
	 */
150
	public function getIdentity($checkSession = true)
Qiang Xue committed
151
	{
152
		if ($this->_identity === false) {
153 154
			if ($checkSession) {
				$this->renewAuthStatus();
155
			} else {
156
				return null;
157
			}
Qiang Xue committed
158
		}
159 160 161 162
		return $this->_identity;
	}

	/**
163 164 165 166 167
	 * Sets the user identity object.
	 *
	 * This method does nothing else except storing the specified identity object in the internal variable.
	 * For this reason, this method is best used when the user authentication status should not be maintained
	 * by session.
168
	 *
169 170 171
	 * This method is also called by other more sophisticated methods, such as [[login()]], [[logout()]],
	 * [[switchIdentity()]]. Those methods will try to use session and cookie to maintain the user authentication
	 * status.
172
	 *
173
	 * @param IdentityInterface $identity the identity object associated with the currently logged user.
174 175 176 177
	 */
	public function setIdentity($identity)
	{
		$this->_identity = $identity;
178
		$this->_access = [];
Qiang Xue committed
179 180 181 182 183
	}

	/**
	 * Logs in a user.
	 *
184 185 186 187 188 189 190 191 192 193
	 * By logging in a user, you may obtain the user identity information each time through [[identity]].
	 *
	 * The login status is maintained according to the `$duration` parameter:
	 *
	 * - `$duration == 0`: the identity information will be stored in session and will be available
	 *   via [[identity]] as long as the session remains active.
	 * - `$duration > 0`: the identity information will be stored in session. If [[enableAutoLogin]] is true,
	 *   it will also be stored in a cookie which will expire in `$duration` seconds. As long as
	 *   the cookie remains valid or the session is active, you may obtain the user identity information
	 *   via [[identity]].
Qiang Xue committed
194
	 *
195
	 * @param IdentityInterface $identity the user identity (which should already be authenticated)
Qiang Xue committed
196 197 198
	 * @param integer $duration number of seconds that the user can remain in logged-in status.
	 * Defaults to 0, meaning login till the user closes the browser or the session is manually destroyed.
	 * If greater than 0 and [[enableAutoLogin]] is true, cookie-based login will be supported.
Qiang Xue committed
199 200 201 202
	 * @return boolean whether the user is logged in
	 */
	public function login($identity, $duration = 0)
	{
203
		if ($this->beforeLogin($identity, false, $duration)) {
204
			$this->switchIdentity($identity, $duration);
205 206
			$id = $identity->getId();
			$ip = Yii::$app->getRequest()->getUserIP();
207 208
			Yii::info("User '$id' logged in from $ip with duration $duration.", __METHOD__);
			$this->afterLogin($identity, false, $duration);
Qiang Xue committed
209 210 211 212
		}
		return !$this->getIsGuest();
	}

213 214 215 216 217 218 219 220 221
	/**
	 * Logs in a user by the given access token.
	 * Note that unlike [[login()]], this method will NOT start a session to remember the user authentication status.
	 * Also if the access token is invalid, the user will remain as a guest.
	 * @param string $token the access token
	 * @return IdentityInterface the identity associated with the given access token. Null is returned if
	 * the access token is invalid.
	 */
	public function loginByAccessToken($token)
Qiang Xue committed
222 223 224
	{
		/** @var IdentityInterface $class */
		$class = $this->identityClass;
225
		$identity = $class::findIdentityByAccessToken($token);
Qiang Xue committed
226 227 228 229
		$this->setIdentity($identity);
		return $identity;
	}

Qiang Xue committed
230
	/**
Qiang Xue committed
231 232 233 234
	 * Logs in a user by cookie.
	 *
	 * This method attempts to log in a user using the ID and authKey information
	 * provided by the given cookie.
Qiang Xue committed
235 236 237 238 239 240 241 242 243
	 */
	protected function loginByCookie()
	{
		$name = $this->identityCookie['name'];
		$value = Yii::$app->getRequest()->getCookies()->getValue($name);
		if ($value !== null) {
			$data = json_decode($value, true);
			if (count($data) === 3 && isset($data[0], $data[1], $data[2])) {
				list ($id, $authKey, $duration) = $data;
slavcodev committed
244
				/** @var IdentityInterface $class */
Qiang Xue committed
245 246
				$class = $this->identityClass;
				$identity = $class::findIdentity($id);
Qiang Xue committed
247
				if ($identity !== null && $identity->validateAuthKey($authKey)) {
248
					if ($this->beforeLogin($identity, true, $duration)) {
249
						$this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);
250 251
						$ip = Yii::$app->getRequest()->getUserIP();
						Yii::info("User '$id' logged in from $ip via cookie.", __METHOD__);
252
						$this->afterLogin($identity, true, $duration);
253
					}
Qiang Xue committed
254 255
				} elseif ($identity !== null) {
					Yii::warning("Invalid auth key attempted for user '$id': $authKey", __METHOD__);
Qiang Xue committed
256 257 258 259 260
				}
			}
		}
	}

Qiang Xue committed
261 262 263
	/**
	 * Logs out the current user.
	 * This will remove authentication-related session data.
Qiang Xue committed
264 265
	 * If `$destroySession` is true, all session data will be removed.
	 * @param boolean $destroySession whether to destroy the whole session. Defaults to true.
Qiang Xue committed
266 267 268
	 */
	public function logout($destroySession = true)
	{
269
		$identity = $this->getIdentity();
Qiang Xue committed
270 271
		if ($identity !== null && $this->beforeLogout($identity)) {
			$this->switchIdentity(null);
272 273 274
			$id = $identity->getId();
			$ip = Yii::$app->getRequest()->getUserIP();
			Yii::info("User '$id' logged out from $ip.", __METHOD__);
Qiang Xue committed
275
			if ($destroySession) {
Qiang Xue committed
276
				Yii::$app->getSession()->destroy();
Qiang Xue committed
277
			}
resurtm committed
278
			$this->afterLogout($identity);
Qiang Xue committed
279 280 281 282 283
		}
	}

	/**
	 * Returns a value indicating whether the user is a guest (not authenticated).
Qiang Xue committed
284
	 * @return boolean whether the current user is a guest.
Qiang Xue committed
285 286 287
	 */
	public function getIsGuest()
	{
288
		return $this->getIdentity() === null;
Qiang Xue committed
289 290 291 292
	}

	/**
	 * Returns a value that uniquely represents the user.
Qiang Xue committed
293
	 * @return string|integer the unique identifier for the user. If null, it means the user is a guest.
Qiang Xue committed
294 295 296
	 */
	public function getId()
	{
297 298
		$identity = $this->getIdentity();
		return $identity !== null ? $identity->getId() : null;
Qiang Xue committed
299 300 301 302 303 304
	}

	/**
	 * Returns the URL that the user should be redirected to after successful login.
	 * This property is usually used by the login action. If the login is successful,
	 * the action should read this property and use it to redirect the user browser.
Qiang Xue committed
305
	 * @param string|array $defaultUrl the default return URL in case it was not set previously.
306 307
	 * If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to.
	 * Please refer to [[setReturnUrl()]] on accepted format of the URL.
Qiang Xue committed
308
	 * @return string the URL that the user should be redirected to after login.
Taras Gudz committed
309
	 * @see loginRequired()
Qiang Xue committed
310 311 312
	 */
	public function getReturnUrl($defaultUrl = null)
	{
313
		$url = Yii::$app->getSession()->get($this->returnUrlParam, $defaultUrl);
314 315 316 317 318 319 320 321
		if (is_array($url)) {
			if (isset($url[0])) {
				$route = array_shift($url);
				return Yii::$app->getUrlManager()->createUrl($route, $url);
			} else {
				$url = null;
			}
		}
Qiang Xue committed
322
		return $url === null ? Yii::$app->getHomeUrl() : $url;
Qiang Xue committed
323 324 325
	}

	/**
Qiang Xue committed
326
	 * @param string|array $url the URL that the user should be redirected to after login.
327 328 329 330 331
	 * If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
	 * The first element of the array should be the route, and the rest of
	 * the name-value pairs are GET parameters used to construct the URL. For example,
	 *
	 * ~~~
Alexander Makarov committed
332
	 * ['admin/index', 'ref' => 1]
333
	 * ~~~
Qiang Xue committed
334
	 */
Qiang Xue committed
335
	public function setReturnUrl($url)
Qiang Xue committed
336
	{
337
		Yii::$app->getSession()->set($this->returnUrlParam, $url);
Qiang Xue committed
338 339 340 341 342
	}

	/**
	 * Redirects the user browser to the login page.
	 * Before the redirection, the current URL (if it's not an AJAX url) will be
Qiang Xue committed
343 344
	 * kept as [[returnUrl]] so that the user browser may be redirected back
	 * to the current page after successful login. Make sure you set [[loginUrl]]
Qiang Xue committed
345 346
	 * so that the user browser can be redirected to the specified login URL after
	 * calling this method.
Qiang Xue committed
347 348
	 *
	 * Note that when [[loginUrl]] is set, calling this method will NOT terminate the application execution.
349
	 *
350
	 * @return Response the redirection response if [[loginUrl]] is set
351
	 * @throws ForbiddenHttpException the "Access Denied" HTTP exception if [[loginUrl]] is not set
Qiang Xue committed
352 353 354
	 */
	public function loginRequired()
	{
Qiang Xue committed
355
		$request = Yii::$app->getRequest();
Qiang Xue committed
356
		if (!$request->getIsAjax()) {
Qiang Xue committed
357 358 359
			$this->setReturnUrl($request->getUrl());
		}
		if ($this->loginUrl !== null) {
360
			return Yii::$app->getResponse()->redirect($this->loginUrl);
Qiang Xue committed
361
		} else {
362
			throw new ForbiddenHttpException(Yii::t('yii', 'Login Required'));
Qiang Xue committed
363 364 365 366 367
		}
	}

	/**
	 * This method is called before logging in a user.
Qiang Xue committed
368 369 370
	 * The default implementation will trigger the [[EVENT_BEFORE_LOGIN]] event.
	 * If you override this method, make sure you call the parent implementation
	 * so that the event is triggered.
371
	 * @param IdentityInterface $identity the user identity information
Qiang Xue committed
372
	 * @param boolean $cookieBased whether the login is cookie-based
373 374
	 * @param integer $duration number of seconds that the user can remain in logged-in status.
	 * If 0, it means login till the user closes the browser or the session is manually destroyed.
Qiang Xue committed
375
	 * @return boolean whether the user should continue to be logged in
Qiang Xue committed
376
	 */
377
	protected function beforeLogin($identity, $cookieBased, $duration)
Qiang Xue committed
378
	{
Alexander Makarov committed
379
		$event = new UserEvent([
Qiang Xue committed
380
			'identity' => $identity,
Qiang Xue committed
381
			'cookieBased' => $cookieBased,
382
			'duration' => $duration,
Alexander Makarov committed
383
		]);
Qiang Xue committed
384 385
		$this->trigger(self::EVENT_BEFORE_LOGIN, $event);
		return $event->isValid;
Qiang Xue committed
386 387 388 389
	}

	/**
	 * This method is called after the user is successfully logged in.
Qiang Xue committed
390 391 392
	 * The default implementation will trigger the [[EVENT_AFTER_LOGIN]] event.
	 * If you override this method, make sure you call the parent implementation
	 * so that the event is triggered.
393
	 * @param IdentityInterface $identity the user identity information
Qiang Xue committed
394
	 * @param boolean $cookieBased whether the login is cookie-based
395 396
	 * @param integer $duration number of seconds that the user can remain in logged-in status.
	 * If 0, it means login till the user closes the browser or the session is manually destroyed.
Qiang Xue committed
397
	 */
398
	protected function afterLogin($identity, $cookieBased, $duration)
Qiang Xue committed
399
	{
Alexander Makarov committed
400
		$this->trigger(self::EVENT_AFTER_LOGIN, new UserEvent([
Qiang Xue committed
401
			'identity' => $identity,
Qiang Xue committed
402
			'cookieBased' => $cookieBased,
403
			'duration' => $duration,
Alexander Makarov committed
404
		]));
Qiang Xue committed
405 406 407
	}

	/**
Qiang Xue committed
408 409 410 411
	 * This method is invoked when calling [[logout()]] to log out a user.
	 * The default implementation will trigger the [[EVENT_BEFORE_LOGOUT]] event.
	 * If you override this method, make sure you call the parent implementation
	 * so that the event is triggered.
412
	 * @param IdentityInterface $identity the user identity information
Qiang Xue committed
413
	 * @return boolean whether the user should continue to be logged out
Qiang Xue committed
414
	 */
Qiang Xue committed
415
	protected function beforeLogout($identity)
Qiang Xue committed
416
	{
Alexander Makarov committed
417
		$event = new UserEvent([
Qiang Xue committed
418
			'identity' => $identity,
Alexander Makarov committed
419
		]);
Qiang Xue committed
420 421
		$this->trigger(self::EVENT_BEFORE_LOGOUT, $event);
		return $event->isValid;
Qiang Xue committed
422 423 424
	}

	/**
Qiang Xue committed
425 426 427 428
	 * This method is invoked right after a user is logged out via [[logout()]].
	 * The default implementation will trigger the [[EVENT_AFTER_LOGOUT]] event.
	 * If you override this method, make sure you call the parent implementation
	 * so that the event is triggered.
429
	 * @param IdentityInterface $identity the user identity information
Qiang Xue committed
430
	 */
Qiang Xue committed
431
	protected function afterLogout($identity)
Qiang Xue committed
432
	{
Alexander Makarov committed
433
		$this->trigger(self::EVENT_AFTER_LOGOUT, new UserEvent([
Qiang Xue committed
434
			'identity' => $identity,
Alexander Makarov committed
435
		]));
Qiang Xue committed
436 437 438 439 440 441 442
	}

	/**
	 * Renews the identity cookie.
	 * This method will set the expiration time of the identity cookie to be the current time
	 * plus the originally specified cookie duration.
	 */
Qiang Xue committed
443
	protected function renewIdentityCookie()
Qiang Xue committed
444
	{
Qiang Xue committed
445 446 447 448 449 450 451 452
		$name = $this->identityCookie['name'];
		$value = Yii::$app->getRequest()->getCookies()->getValue($name);
		if ($value !== null) {
			$data = json_decode($value, true);
			if (is_array($data) && isset($data[2])) {
				$cookie = new Cookie($this->identityCookie);
				$cookie->value = $value;
				$cookie->expire = time() + (int)$data[2];
453
				Yii::$app->getResponse()->getCookies()->add($cookie);
Qiang Xue committed
454 455 456 457 458
			}
		}
	}

	/**
Qiang Xue committed
459 460
	 * Sends an identity cookie.
	 * This method is used when [[enableAutoLogin]] is true.
461
	 * It saves [[id]], [[IdentityInterface::getAuthKey()|auth key]], and the duration of cookie-based login
Qiang Xue committed
462
	 * information in the cookie.
463
	 * @param IdentityInterface $identity
Qiang Xue committed
464
	 * @param integer $duration number of seconds that the user can remain in logged-in status.
Taras Gudz committed
465
	 * @see loginByCookie()
Qiang Xue committed
466
	 */
Qiang Xue committed
467
	protected function sendIdentityCookie($identity, $duration)
Qiang Xue committed
468
	{
Qiang Xue committed
469
		$cookie = new Cookie($this->identityCookie);
Alexander Makarov committed
470
		$cookie->value = json_encode([
Qiang Xue committed
471 472
			$identity->getId(),
			$identity->getAuthKey(),
Qiang Xue committed
473
			$duration,
Alexander Makarov committed
474
		]);
Qiang Xue committed
475
		$cookie->expire = time() + $duration;
476
		Yii::$app->getResponse()->getCookies()->add($cookie);
Qiang Xue committed
477 478 479
	}

	/**
480 481
	 * Switches to a new identity for the current user.
	 *
482 483
	 * This method may use session and/or cookie to store the user identity information,
	 * according to the value of `$duration`. Please refer to [[login()]] for more details.
484 485 486 487
	 *
	 * This method is mainly called by [[login()]], [[logout()]] and [[loginByCookie()]]
	 * when the current user needs to be associated with the corresponding identity information.
	 *
488
	 * @param IdentityInterface $identity the identity information to be associated with the current user.
489
	 * If null, it means switching the current user to be a guest.
490 491
	 * @param integer $duration number of seconds that the user can remain in logged-in status.
	 * This parameter is used only when `$identity` is not null.
Qiang Xue committed
492
	 */
493
	public function switchIdentity($identity, $duration = 0)
Qiang Xue committed
494
	{
Qiang Xue committed
495
		$session = Yii::$app->getSession();
496
		if (!YII_ENV_TEST) {
497 498
			$session->regenerateID(true);
		}
499
		$this->setIdentity($identity);
500 501
		$session->remove($this->idParam);
		$session->remove($this->authTimeoutParam);
502
		if ($identity instanceof IdentityInterface) {
503
			$session->set($this->idParam, $identity->getId());
Qiang Xue committed
504
			if ($this->authTimeout !== null) {
505
				$session->set($this->authTimeoutParam, time() + $this->authTimeout);
506 507 508
			}
			if ($duration > 0 && $this->enableAutoLogin) {
				$this->sendIdentityCookie($identity, $duration);
Qiang Xue committed
509
			}
510
		} elseif ($this->enableAutoLogin) {
511
			Yii::$app->getResponse()->getCookies()->remove(new Cookie($this->identityCookie));
Qiang Xue committed
512 513 514 515
		}
	}

	/**
516 517 518 519 520 521 522 523
	 * Updates the authentication status using the information from session and cookie.
	 *
	 * This method will try to determine the user identity using the [[idParam]] session variable.
	 *
	 * If [[authTimeout]] is set, this method will refresh the timer.
	 *
	 * If the user identity cannot be determined by session, this method will try to [[loginByCookie()|login by cookie]]
	 * if [[enableAutoLogin]] is true.
Qiang Xue committed
524
	 */
Qiang Xue committed
525
	protected function renewAuthStatus()
Qiang Xue committed
526
	{
527
		$session = Yii::$app->getSession();
Qiang Xue committed
528
		$id = $session->getHasSessionId() || $session->getIsActive() ? $session->get($this->idParam) : null;
529 530 531 532 533 534 535 536 537 538 539 540 541

		if ($id === null) {
			$identity = null;
		} else {
			/** @var IdentityInterface $class */
			$class = $this->identityClass;
			$identity = $class::findIdentity($id);
		}

		$this->setIdentity($identity);

		if ($this->authTimeout !== null && $identity !== null) {
			$expire = $session->get($this->authTimeoutParam);
Qiang Xue committed
542 543 544
			if ($expire !== null && $expire < time()) {
				$this->logout(false);
			} else {
545 546 547 548 549 550 551 552 553
				$session->set($this->authTimeoutParam, time() + $this->authTimeout);
			}
		}

		if ($this->enableAutoLogin) {
			if ($this->getIsGuest()) {
				$this->loginByCookie();
			} elseif ($this->autoRenewCookie) {
				$this->renewIdentityCookie();
Qiang Xue committed
554 555
			}
		}
Qiang Xue committed
556
	}
Qiang Xue committed
557 558

	/**
559 560 561 562 563 564 565 566 567 568 569
	 * Performs access check for this user.
	 * @param string $operation the name of the operation that need access check.
	 * @param array $params name-value pairs that would be passed to business rules associated
	 * with the tasks and roles assigned to the user. A param with name 'userId' is added to
	 * this array, which holds the value of [[id]] when [[DbAuthManager]] or
	 * [[PhpAuthManager]] is used.
	 * @param boolean $allowCaching whether to allow caching the result of access check.
	 * When this parameter is true (default), if the access check of an operation was performed
	 * before, its result will be directly returned when calling this method to check the same
	 * operation. If this parameter is false, this method will always call
	 * [[AuthManager::checkAccess()]] to obtain the up-to-date access result. Note that this
Alexander Makarov committed
570
	 * caching is effective only within the same request and only works when `$params = []`.
571
	 * @return boolean whether the operations can be performed by this user.
Qiang Xue committed
572
	 */
Alexander Makarov committed
573
	public function checkAccess($operation, $params = [], $allowCaching = true)
Qiang Xue committed
574 575
	{
		$auth = Yii::$app->getAuthManager();
576
		if ($auth === null) {
Qiang Xue committed
577
			return false;
Qiang Xue committed
578
		}
579 580 581 582 583 584 585 586
		if ($allowCaching && empty($params) && isset($this->_access[$operation])) {
			return $this->_access[$operation];
		}
		$access = $auth->checkAccess($this->getId(), $operation, $params);
		if ($allowCaching && empty($params)) {
			$this->_access[$operation] = $access;
		}
		return $access;
Qiang Xue committed
587
	}
Qiang Xue committed
588
}