User.php 15.2 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\HttpException;
Qiang Xue committed
13
use yii\base\InvalidConfigException;
Qiang Xue committed
14 15

/**
16
 * User is the class for the "user" application component that manages the user authentication status.
Qiang Xue committed
17 18 19 20 21 22 23
 *
 * In particular, [[User::isGuest]] returns a value indicating whether the current user is a guest or not.
 * Through methods [[login()]] and [[logout()]], you can change the user authentication status.
 *
 * User works with a class implementing the [[Identity]] interface. This class implements
 * the actual user authentication logic and is often backed by a user database table.
 *
Qiang Xue committed
24 25 26 27 28
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class User extends Component
{
Qiang Xue committed
29 30 31 32 33 34
	const EVENT_BEFORE_LOGIN = 'beforeLogin';
	const EVENT_AFTER_LOGIN = 'afterLogin';
	const EVENT_BEFORE_LOGOUT = 'beforeLogout';
	const EVENT_AFTER_LOGOUT = 'afterLogout';

	/**
Qiang Xue committed
35
	 * @var string the class name of the [[identity]] object.
Qiang Xue committed
36 37
	 */
	public $identityClass;
Qiang Xue committed
38 39 40
	/**
	 * @var boolean whether to enable cookie-based login. Defaults to false.
	 */
Qiang Xue committed
41
	public $enableAutoLogin = false;
Qiang Xue committed
42
	/**
Qiang Xue committed
43 44 45 46 47 48 49 50 51 52
	 * @var string|array the URL for login when [[loginRequired()]] is called. 
	 * 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 to the login action, and the rest of 
	 * the name-value pairs are GET parameters used to construct the login URL. For example,
	 * 
	 * ~~~
	 * array('site/login', 'ref' => 1)
	 * ~~~
	 *
	 * If this property is null, a 403 HTTP exception will be raised when [[loginRequired()]] is called.
Qiang Xue committed
53
	 */
Qiang Xue committed
54
	public $loginUrl = array('site/login');
Qiang Xue committed
55
	/**
Qiang Xue committed
56 57
	 * @var array the configuration of the identity cookie. This property is used only when [[enableAutoLogin]] is true.
	 * @see Cookie
Qiang Xue committed
58
	 */
Qiang Xue committed
59
	public $identityCookie = array('name' => '_identity', 'httponly' => true);
Qiang Xue committed
60
	/**
Qiang Xue committed
61 62 63
	 * @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
64 65 66 67
	 */
	public $authTimeout;
	/**
	 * @var boolean whether to automatically renew the identity cookie each time a page is requested.
Qiang Xue committed
68
	 * This property is effective only when [[enableAutoLogin]] is true.
Qiang Xue committed
69 70 71
	 * 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
72
	 * @see enableAutoLogin
Qiang Xue committed
73
	 */
Qiang Xue committed
74
	public $autoRenewCookie = true;
Qiang Xue committed
75 76 77 78 79 80 81 82 83 84 85 86 87
	/**
	 * @var string the session variable name used to store the value of [[id]].
	 */
	public $idVar = '__id';
	/**
	 * @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.
	 */
	public $authTimeoutVar = '__expire';
	/**
	 * @var string the session variable name used to store the value of [[returnUrl]].
	 */
	public $returnUrlVar = '__returnUrl';
Qiang Xue committed
88 89 90 91 92 93 94 95


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

97 98 99
		if ($this->identityClass === null) {
			throw new InvalidConfigException('User::identityClass must be set.');
		}
Qiang Xue committed
100 101 102 103
		if ($this->enableAutoLogin && !isset($this->identityCookie['name'])) {
			throw new InvalidConfigException('User::identityCookie must contain the "name" element.');
		}

Qiang Xue committed
104
		Yii::$app->getSession()->open();
Qiang Xue committed
105 106 107 108 109 110 111 112 113 114 115 116

		$this->renewAuthStatus();

		if ($this->enableAutoLogin) {
			if ($this->getIsGuest()) {
				$this->loginByCookie();
			} elseif ($this->autoRenewCookie) {
				$this->renewIdentityCookie();
			}
		}
	}

117 118
	private $_identity = false;

Qiang Xue committed
119
	/**
120 121 122 123 124
	 * Returns the identity object associated with the currently logged user.
	 * @return Identity the identity object associated with the currently logged user.
	 * Null is returned if the user is not logged in (not authenticated).
	 * @see login
	 * @see logout
Qiang Xue committed
125
	 */
126
	public function getIdentity()
Qiang Xue committed
127
	{
128 129 130 131 132 133
		if ($this->_identity === false) {
			$id = $this->getId();
			if ($id === null) {
				$this->_identity = null;
			} else {
				/** @var $class Identity */
Qiang Xue committed
134
				$class = Yii::import($this->identityClass);
135 136
				$this->_identity = $class::findIdentity($id);
			}
Qiang Xue committed
137
		}
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
		return $this->_identity;
	}

	/**
	 * Sets the identity object.
	 * This method should be mainly be used by the User component or its child class
	 * to maintain the identity object.
	 *
	 * You should normally update the user identity via methods [[login()]], [[logout()]]
	 * or [[switchIdentity()]].
	 *
	 * @param Identity $identity the identity object associated with the currently logged user.
	 */
	public function setIdentity($identity)
	{
		$this->_identity = $identity;
Qiang Xue committed
154 155 156 157 158
	}

	/**
	 * Logs in a user.
	 *
Qiang Xue committed
159 160 161 162
	 * This method stores the necessary session information to keep track
	 * of the user identity information. If `$duration` is greater than 0
	 * and [[enableAutoLogin]] is true, it will also send out an identity
	 * cookie to support cookie-based login.
Qiang Xue committed
163
	 *
Qiang Xue committed
164
	 * @param Identity $identity the user identity (which should already be authenticated)
Qiang Xue committed
165 166 167
	 * @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
168 169 170 171
	 * @return boolean whether the user is logged in
	 */
	public function login($identity, $duration = 0)
	{
Qiang Xue committed
172
		if ($this->beforeLogin($identity, false)) {
173
			$this->switchIdentity($identity, $duration);
Qiang Xue committed
174
			$this->afterLogin($identity, false);
Qiang Xue committed
175 176 177 178
		}
		return !$this->getIsGuest();
	}

Qiang Xue committed
179
	/**
Qiang Xue committed
180 181 182 183
	 * 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
184 185 186 187 188 189 190 191 192 193 194 195
	 */
	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;
				/** @var $class Identity */
				$class = $this->identityClass;
				$identity = $class::findIdentity($id);
Qiang Xue committed
196 197
				if ($identity !== null && $identity->validateAuthKey($authKey)) {
					if ($this->beforeLogin($identity, true)) {
198
						$this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);
Qiang Xue committed
199
						$this->afterLogin($identity, true);
200
					}
Qiang Xue committed
201 202
				} elseif ($identity !== null) {
					Yii::warning("Invalid auth key attempted for user '$id': $authKey", __METHOD__);
Qiang Xue committed
203 204 205 206 207
				}
			}
		}
	}

Qiang Xue committed
208 209 210
	/**
	 * Logs out the current user.
	 * This will remove authentication-related session data.
Qiang Xue committed
211 212
	 * 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
213 214 215
	 */
	public function logout($destroySession = true)
	{
216
		$identity = $this->getIdentity();
Qiang Xue committed
217 218
		if ($identity !== null && $this->beforeLogout($identity)) {
			$this->switchIdentity(null);
Qiang Xue committed
219
			if ($destroySession) {
Qiang Xue committed
220
				Yii::$app->getSession()->destroy();
Qiang Xue committed
221
			}
Qiang Xue committed
222
 			$this->afterLogout($identity);
Qiang Xue committed
223 224 225 226 227
		}
	}

	/**
	 * Returns a value indicating whether the user is a guest (not authenticated).
Qiang Xue committed
228
	 * @return boolean whether the current user is a guest.
Qiang Xue committed
229 230 231
	 */
	public function getIsGuest()
	{
232
		return $this->getIdentity() === null;
Qiang Xue committed
233 234 235 236
	}

	/**
	 * Returns a value that uniquely represents the user.
Qiang Xue committed
237
	 * @return string|integer the unique identifier for the user. If null, it means the user is a guest.
Qiang Xue committed
238 239 240
	 */
	public function getId()
	{
Qiang Xue committed
241
		return Yii::$app->getSession()->get($this->idVar);
Qiang Xue committed
242 243 244 245 246 247
	}

	/**
	 * 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
248 249 250
	 * @param string|array $defaultUrl the default return URL in case it was not set previously.
	 * If this is null, it means [[Application::homeUrl]] will be redirected to.
	 * Please refer to [[\yii\helpers\Html::url()]] on acceptable URL formats.
Qiang Xue committed
251 252 253 254 255
	 * @return string the URL that the user should be redirected to after login.
	 * @see loginRequired
	 */
	public function getReturnUrl($defaultUrl = null)
	{
Qiang Xue committed
256 257
		$url = Yii::$app->getSession()->get($this->returnUrlVar, $defaultUrl);
		return $url === null ? Yii::$app->getHomeUrl() : $url;
Qiang Xue committed
258 259 260
	}

	/**
Qiang Xue committed
261 262
	 * @param string|array $url the URL that the user should be redirected to after login.
	 * Please refer to [[\yii\helpers\Html::url()]] on acceptable URL formats.
Qiang Xue committed
263
	 */
Qiang Xue committed
264
	public function setReturnUrl($url)
Qiang Xue committed
265
	{
Qiang Xue committed
266
		Yii::$app->getSession()->set($this->returnUrlVar, $url);
Qiang Xue committed
267 268 269 270 271
	}

	/**
	 * 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
272 273
	 * 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
274 275 276 277 278 279
	 * so that the user browser can be redirected to the specified login URL after
	 * calling this method.
	 * After calling this method, the current request processing will be terminated.
	 */
	public function loginRequired()
	{
Qiang Xue committed
280 281 282 283 284 285
		$request = Yii::$app->getRequest();
		if (!$request->getIsAjaxRequest()) {
			$this->setReturnUrl($request->getUrl());
		}
		if ($this->loginUrl !== null) {
			Yii::$app->getResponse()->redirect($this->loginUrl);
Qiang Xue committed
286
		} else {
Qiang Xue committed
287
			throw new HttpException(403, Yii::t('yii|Login Required'));
Qiang Xue committed
288 289 290 291 292
		}
	}

	/**
	 * This method is called before logging in a user.
Qiang Xue committed
293 294 295 296 297 298
	 * 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.
	 * @param Identity $identity the user identity information
	 * @param boolean $cookieBased whether the login is cookie-based
	 * @return boolean whether the user should continue to be logged in
Qiang Xue committed
299
	 */
Qiang Xue committed
300
	protected function beforeLogin($identity, $cookieBased)
Qiang Xue committed
301
	{
Qiang Xue committed
302 303
		$event = new UserEvent(array(
			'identity' => $identity,
Qiang Xue committed
304
			'cookieBased' => $cookieBased,
Qiang Xue committed
305 306 307
		));
		$this->trigger(self::EVENT_BEFORE_LOGIN, $event);
		return $event->isValid;
Qiang Xue committed
308 309 310 311
	}

	/**
	 * This method is called after the user is successfully logged in.
Qiang Xue committed
312 313 314 315 316
	 * 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.
	 * @param Identity $identity the user identity information
	 * @param boolean $cookieBased whether the login is cookie-based
Qiang Xue committed
317
	 */
Qiang Xue committed
318
	protected function afterLogin($identity, $cookieBased)
Qiang Xue committed
319
	{
Qiang Xue committed
320 321
		$this->trigger(self::EVENT_AFTER_LOGIN, new UserEvent(array(
			'identity' => $identity,
Qiang Xue committed
322
			'cookieBased' => $cookieBased,
Qiang Xue committed
323
		)));
Qiang Xue committed
324 325 326
	}

	/**
Qiang Xue committed
327 328 329 330 331 332
	 * 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.
	 * @param Identity $identity the user identity information
	 * @return boolean whether the user should continue to be logged out
Qiang Xue committed
333
	 */
Qiang Xue committed
334
	protected function beforeLogout($identity)
Qiang Xue committed
335
	{
Qiang Xue committed
336 337 338 339 340
		$event = new UserEvent(array(
			'identity' => $identity,
		));
		$this->trigger(self::EVENT_BEFORE_LOGOUT, $event);
		return $event->isValid;
Qiang Xue committed
341 342 343
	}

	/**
Qiang Xue committed
344 345 346 347 348
	 * 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.
	 * @param Identity $identity the user identity information
Qiang Xue committed
349
	 */
Qiang Xue committed
350
	protected function afterLogout($identity)
Qiang Xue committed
351
	{
Qiang Xue committed
352 353 354
		$this->trigger(self::EVENT_AFTER_LOGOUT, new UserEvent(array(
			'identity' => $identity,
		)));
Qiang Xue committed
355 356 357 358 359 360 361
	}

	/**
	 * 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
362
	protected function renewIdentityCookie()
Qiang Xue committed
363
	{
Qiang Xue committed
364 365 366 367 368 369 370 371 372
		$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];
				Yii::$app->getResponse()->getCookies()->add($cookie);
Qiang Xue committed
373 374 375 376 377
			}
		}
	}

	/**
Qiang Xue committed
378 379 380 381
	 * Sends an identity cookie.
	 * This method is used when [[enableAutoLogin]] is true.
	 * It saves [[id]], [[Identity::getAuthKey()|auth key]], and the duration of cookie-based login
	 * information in the cookie.
Qiang Xue committed
382
	 * @param Identity $identity
Qiang Xue committed
383
	 * @param integer $duration number of seconds that the user can remain in logged-in status.
Qiang Xue committed
384
	 * @see loginByCookie
Qiang Xue committed
385
	 */
Qiang Xue committed
386
	protected function sendIdentityCookie($identity, $duration)
Qiang Xue committed
387
	{
Qiang Xue committed
388 389 390 391
		$cookie = new Cookie($this->identityCookie);
		$cookie->value = json_encode(array(
			$identity->getId(),
			$identity->getAuthKey(),
Qiang Xue committed
392
			$duration,
Qiang Xue committed
393 394 395
		));
		$cookie->expire = time() + $duration;
		Yii::$app->getResponse()->getCookies()->add($cookie);
Qiang Xue committed
396 397 398
	}

	/**
399 400 401 402 403 404 405 406 407
	 * Switches to a new identity for the current user.
	 *
	 * This method will save necessary session information to keep track of the user authentication status.
	 * If `$duration` is provided, it will also send out appropriate identity cookie
	 * to support cookie-based login.
	 *
	 * This method is mainly called by [[login()]], [[logout()]] and [[loginByCookie()]]
	 * when the current user needs to be associated with the corresponding identity information.
	 *
Qiang Xue committed
408
	 * @param Identity $identity the identity information to be associated with the current user.
409 410 411
	 * If null, it means switching to be a guest.
	 * @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
412
	 */
413
	public function switchIdentity($identity, $duration = 0)
Qiang Xue committed
414
	{
Qiang Xue committed
415
		$session = Yii::$app->getSession();
416 417
		$session->regenerateID(true);
		$this->setIdentity($identity);
Qiang Xue committed
418 419
		$session->remove($this->idVar);
		$session->remove($this->authTimeoutVar);
Qiang Xue committed
420
		if ($identity instanceof Identity) {
421
			$session->set($this->idVar, $identity->getId());
Qiang Xue committed
422
			if ($this->authTimeout !== null) {
423 424 425 426
				$session->set($this->authTimeoutVar, time() + $this->authTimeout);
			}
			if ($duration > 0 && $this->enableAutoLogin) {
				$this->sendIdentityCookie($identity, $duration);
Qiang Xue committed
427
			}
428 429
		} elseif ($this->enableAutoLogin) {
			Yii::$app->getResponse()->getCookies()->remove(new Cookie($this->identityCookie));
Qiang Xue committed
430 431 432 433
		}
	}

	/**
Qiang Xue committed
434 435 436 437
	 * Updates the authentication status according to [[authTimeout]].
	 * This method is called during [[init()]].
	 * It will update the user's authentication status if it has not outdated yet.
	 * Otherwise, it will logout the user.
Qiang Xue committed
438
	 */
Qiang Xue committed
439
	protected function renewAuthStatus()
Qiang Xue committed
440
	{
441
		if ($this->authTimeout !== null && !$this->getIsGuest()) {
Qiang Xue committed
442
			$expire = Yii::$app->getSession()->get($this->authTimeoutVar);
Qiang Xue committed
443 444 445
			if ($expire !== null && $expire < time()) {
				$this->logout(false);
			} else {
Qiang Xue committed
446
				Yii::$app->getSession()->set($this->authTimeoutVar, time() + $this->authTimeout);
Qiang Xue committed
447 448
			}
		}
Qiang Xue committed
449 450
	}
}