system system.base system.caching system.caching.dependencies system.collections system.console system.db system.db.ar system.db.schema system.db.schema.cubrid system.db.schema.mssql system.db.schema.mysql system.db.schema.oci system.db.schema.pgsql system.db.schema.sqlite system.gii system.i18n system.i18n.gettext system.logging system.test system.utils system.validators system.web system.web.actions system.web.auth system.web.filters system.web.form system.web.helpers system.web.renderers system.web.services system.web.widgets system.web.widgets.captcha system.web.widgets.pagers zii.behaviors zii.widgets zii.widgets.grid zii.widgets.jui

CWebUser

system.web.auth
继承 class CWebUser » CApplicationComponent » CComponent
实现 IApplicationComponent, IWebUser
可用自 1.0
源码 framework/web/auth/CWebUser.php
CWebUser represents the persistent state for a Web application user.

CWebUser is used as an application component whose ID is 'user'. Therefore, at any place one can access the user state via Yii::app()->user.

CWebUser should be used together with an identity which implements the actual authentication algorithm.

A typical authentication process using CWebUser is as follows:
  1. The user provides information needed for authentication.
  2. An identity instance is created with the user-provided information.
  3. Call IUserIdentity::authenticate to check if the identity is valid.
  4. If valid, call CWebUser::login to login the user, and Redirect the user browser to returnUrl.
  5. If not valid, retrieve the error code or message from the identity instance and display it.


The property id and name are both identifiers for the user. The former is mainly used internally (e.g. primary key), while the latter is for display purpose (e.g. username). The id property is a unique identifier for a user that is persistent during the whole user session. It can be a username, or something else, depending on the implementation of the identity class.

Both id and name are persistent during the user session. Besides, an identity may have additional persistent data which can be accessed by calling getState. Note, when cookie-based authentication is enabled, all these persistent data will be stored in cookie. Therefore, do not store password or other sensitive data in the persistent storage. Instead, you should store them directly in session on the server side if needed.

公共属性

隐藏继承的属性

属性类型描述被定义在
absoluteAuthTimeout integer timeout in seconds after which user is logged out regardless of activity. CWebUser
allowAutoLogin boolean whether to enable cookie-based login. CWebUser
authTimeout integer timeout in seconds after which user is logged out if inactive. CWebUser
autoRenewCookie boolean whether to automatically renew the identity cookie each time a page is requested. CWebUser
autoUpdateFlash boolean whether to automatically update the validity of flash messages. CWebUser
behaviors array the behaviors that should be attached to this component. CApplicationComponent
flashes array Returns all flash messages. CWebUser
guestName string the name for a guest user. CWebUser
id mixed Returns a value that uniquely represents the user. CWebUser
identityCookie array the property values (in name-value pairs) used to initialize the identity cookie. CWebUser
isGuest boolean Returns a value indicating whether the user is a guest (not authenticated). CWebUser
isInitialized boolean Checks if this application component has been initialized. CApplicationComponent
loginRequiredAjaxResponse string value that will be echoed in case that user session has expired during an ajax call. CWebUser
loginUrl string|array the URL for login. CWebUser
name string Returns the unique identifier for the user (e.g. username). CWebUser
returnUrl string Returns the URL that the user should be redirected to after successful login. CWebUser
stateKeyPrefix string a prefix for the name of the session variables storing user session data. CWebUser

公共方法

隐藏继承的方法

方法描述被定义在
__call() Calls the named method which is not a class method. CComponent
__get() PHP magic method. CWebUser
__isset() PHP magic method. CWebUser
__set() PHP magic method. CWebUser
__unset() PHP magic method. CWebUser
asa() Returns the named behavior object. CComponent
attachBehavior() Attaches a behavior to this component. CComponent
attachBehaviors() Attaches a list of behaviors to the component. CComponent
attachEventHandler() Attaches an event handler to an event. CComponent
canGetProperty() Determines whether a property can be read. CComponent
canSetProperty() Determines whether a property can be set. CComponent
checkAccess() Performs access check for this user. CWebUser
clearStates() Clears all user identity information from persistent storage. CWebUser
detachBehavior() Detaches a behavior from the component. CComponent
detachBehaviors() Detaches all behaviors from the component. CComponent
detachEventHandler() Detaches an existing event handler. CComponent
disableBehavior() Disables an attached behavior. CComponent
disableBehaviors() Disables all behaviors attached to this component. CComponent
enableBehavior() Enables an attached behavior. CComponent
enableBehaviors() Enables all behaviors attached to this component. CComponent
evaluateExpression() Evaluates a PHP expression or callback under the context of this component. CComponent
getEventHandlers() Returns the list of attached event handlers for an event. CComponent
getFlash() Returns a flash message. CWebUser
getFlashes() Returns all flash messages. CWebUser
getId() Returns a value that uniquely represents the user. CWebUser
getIsGuest() Returns a value indicating whether the user is a guest (not authenticated). CWebUser
getIsInitialized() Checks if this application component has been initialized. CApplicationComponent
getName() Returns the unique identifier for the user (e.g. username). CWebUser
getReturnUrl() Returns the URL that the user should be redirected to after successful login. CWebUser
getState() Returns the value of a variable that is stored in user session. CWebUser
getStateKeyPrefix() Returns a prefix for the name of the session variables storing user session data. CWebUser
hasEvent() Determines whether an event is defined. CComponent
hasEventHandler() Checks whether the named event has attached handlers. CComponent
hasFlash() Determines whether the specified flash message exists CWebUser
hasProperty() Determines whether a property is defined. CComponent
hasState() Returns a value indicating whether there is a state of the specified name. CWebUser
init() Initializes the application component. CWebUser
login() Logs in a user. CWebUser
loginRequired() Redirects the user browser to the login page. CWebUser
logout() Logs out the current user. CWebUser
raiseEvent() Raises an event. CComponent
setFlash() Stores a flash message. CWebUser
setId() Sets the unique identifier for the user. If null, it means the user is a guest. CWebUser
setName() Sets the unique identifier for the user (e.g. username). CWebUser
setReturnUrl() Sets the URL that the user should be redirected to after login. CWebUser
setState() Stores a variable in user session. CWebUser
setStateKeyPrefix() Sets a prefix for the name of the session variables storing user session data. CWebUser

受保护的方法

隐藏继承的方法

方法描述被定义在
afterLogin() This method is called after the user is successfully logged in. CWebUser
afterLogout() This method is invoked right after a user is logged out. CWebUser
beforeLogin() This method is called before logging in a user. CWebUser
beforeLogout() This method is invoked when calling logout to log out a user. CWebUser
changeIdentity() Changes the current user with the specified identity information. CWebUser
createIdentityCookie() Creates a cookie to store identity information. CWebUser
loadIdentityStates() Loads identity states from an array and saves them to persistent storage. CWebUser
renewCookie() Renews the identity cookie. CWebUser
restoreFromCookie() Populates the current user object with the information obtained from cookie. CWebUser
saveIdentityStates() Retrieves identity states from persistent storage and saves them as an array. CWebUser
saveToCookie() Saves necessary user data into a cookie. CWebUser
updateAuthStatus() Updates the authentication status according to authTimeout. CWebUser
updateFlash() Updates the internal counters for flash messages. CWebUser

属性详情

absoluteAuthTimeout 属性 (自版本 v1.1.14 可用)
public integer $absoluteAuthTimeout;

timeout in seconds after which user is logged out regardless of activity.

allowAutoLogin 属性
public boolean $allowAutoLogin;

whether to enable cookie-based login. Defaults to false.

authTimeout 属性 (自版本 v1.1.7 可用)
public integer $authTimeout;

timeout in seconds after which user is logged out if inactive. If this property is not set, the user will be logged out after the current session expires (c.f. CHttpSession::timeout).

autoRenewCookie 属性 (自版本 v1.1.0 可用)
public boolean $autoRenewCookie;

whether to automatically renew the identity cookie each time a page is requested. Defaults to false. This property is effective only when allowAutoLogin is true. 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.

autoUpdateFlash 属性 (自版本 v1.1.7 可用)
public boolean $autoUpdateFlash;

whether to automatically update the validity of flash messages. Defaults to true, meaning flash messages will be valid only in the current and the next requests. If this is set false, you will be responsible for ensuring a flash message is deleted after usage. (This can be achieved by calling getFlash with the 3rd parameter being true).

flashes 属性 只读 (自版本 v1.1.3 可用)
public array getFlashes(boolean $delete=true)

Returns all flash messages. This method is similar to getFlash except that it returns all currently available flash messages.

guestName 属性
public string $guestName;

the name for a guest user. Defaults to 'Guest'. This is used by getName when the current user is a guest (not authenticated).

id 属性
public mixed getId()
public void setId(mixed $value)

Returns a value that uniquely represents the user.

identityCookie 属性
public array $identityCookie;

the property values (in name-value pairs) used to initialize the identity cookie. Any property of CHttpCookie may be initialized. This property is effective only when allowAutoLogin is true.

isGuest 属性 只读
public boolean getIsGuest()

Returns a value indicating whether the user is a guest (not authenticated).

loginRequiredAjaxResponse 属性 (自版本 v1.1.9 可用)
public string $loginRequiredAjaxResponse;

value that will be echoed in case that user session has expired during an ajax call. When a request is made and user session has expired, loginRequired redirects to loginUrl for login. If that happens during an ajax call, the complete HTML login page is returned as the result of that ajax call. That could be a problem if the ajax call expects the result to be a json array or a predefined string, as the login page is ignored in that case. To solve this, set this property to the desired return value.

If this property is set, this value will be returned as the result of the ajax call in case that the user session has expired.

参见

loginUrl 属性
public string|array $loginUrl;

the URL for login. If using array, the first element should be the route to the login action, and the rest name-value pairs are GET parameters to construct the login URL (e.g. array('/site/login')). If this property is null, a 403 HTTP exception will be raised instead.

name 属性
public string getName()
public void setName(string $value)

Returns the unique identifier for the user (e.g. username). This is the unique identifier that is mainly used for display purpose.

returnUrl 属性
public string getReturnUrl(string $defaultUrl=NULL)
public void setReturnUrl(string $value)

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.

参见

stateKeyPrefix 属性
public string getStateKeyPrefix()
public void setStateKeyPrefix(string $value)

a prefix for the name of the session variables storing user session data.

方法详情

__get() 方法
public mixed __get(string $name)
$name string property name
{return} mixed property value
源码: framework/web/auth/CWebUser.php#141 (显示)
public function __get($name)
{
    if(
$this->hasState($name))
        return 
$this->getState($name);
    else
        return 
parent::__get($name);
}

PHP magic method. This method is overridden so that persistent states can be accessed like properties.

__isset() 方法
public boolean __isset(string $name)
$name string property name
{return} boolean
源码: framework/web/auth/CWebUser.php#170 (显示)
public function __isset($name)
{
    if(
$this->hasState($name))
        return 
$this->getState($name)!==null;
    else
        return 
parent::__isset($name);
}

PHP magic method. This method is overridden so that persistent states can also be checked for null value.

__set() 方法
public void __set(string $name, mixed $value)
$name string property name
$value mixed property value
源码: framework/web/auth/CWebUser.php#156 (显示)
public function __set($name,$value)
{
    if(
$this->hasState($name))
        
$this->setState($name,$value);
    else
        
parent::__set($name,$value);
}

PHP magic method. This method is overridden so that persistent states can be set like properties.

__unset() 方法
public void __unset(string $name)
$name string property name
源码: framework/web/auth/CWebUser.php#184 (显示)
public function __unset($name)
{
    if(
$this->hasState($name))
        
$this->setState($name,null);
    else
        
parent::__unset($name);
}

PHP magic method. This method is overridden so that persistent states can also be unset.

afterLogin() 方法 (自版本 v1.1.3 可用)
protected void afterLogin(boolean $fromCookie)
$fromCookie boolean whether the login is based on cookie.
源码: framework/web/auth/CWebUser.php#424 (显示)
protected function afterLogin($fromCookie)
{
}

This method is called after the user is successfully logged in. You may override this method to do some postprocessing (e.g. log the user login IP and time; load the user permission information).

afterLogout() 方法 (自版本 v1.1.3 可用)
protected void afterLogout()
源码: framework/web/auth/CWebUser.php#446 (显示)
protected function afterLogout()
{
}

This method is invoked right after a user is logged out. You may override this method to do some extra cleanup work for the user.

beforeLogin() 方法 (自版本 v1.1.3 可用)
protected boolean beforeLogin(mixed $id, array $states, boolean $fromCookie)
$id mixed the user ID. This is the same as returned by getId().
$states array a set of name-value pairs that are provided by the user identity.
$fromCookie boolean whether the login is based on cookie
{return} boolean whether the user should be logged in
源码: framework/web/auth/CWebUser.php#412 (显示)
protected function beforeLogin($id,$states,$fromCookie)
{
    return 
true;
}

This method is called before logging in a user. You may override this method to provide additional security check. For example, when the login is cookie-based, you may want to verify that the user ID together with a random token in the states can be found in the database. This will prevent hackers from faking arbitrary identity cookies even if they crack down the server private key.

beforeLogout() 方法 (自版本 v1.1.3 可用)
protected boolean beforeLogout()
{return} boolean whether to log out the user
源码: framework/web/auth/CWebUser.php#436 (显示)
protected function beforeLogout()
{
    return 
true;
}

This method is invoked when calling logout to log out a user. If this method return false, the logout action will be cancelled. You may override this method to provide additional check before logging out a user.

changeIdentity() 方法
protected void changeIdentity(mixed $id, string $name, array $states)
$id mixed a unique identifier for the user
$name string the display name for the user
$states array identity states
源码: framework/web/auth/CWebUser.php#715 (显示)
protected function changeIdentity($id,$name,$states)
{
    
Yii::app()->getSession()->regenerateID(true);
    
$this->setId($id);
    
$this->setName($name);
    
$this->loadIdentityStates($states);
}

Changes the current user with the specified identity information. This method is called by login and restoreFromCookie when the current user needs to be populated with the corresponding identity information. Derived classes may override this method by retrieving additional user-related information. Make sure the parent implementation is called first.

checkAccess() 方法
public boolean checkAccess(string $operation, array $params=array ( ), boolean $allowCaching=true)
$operation string the name of the operation that need access check.
$params array name-value pairs that would be passed to business rules associated with the tasks and roles assigned to the user. Since version 1.1.11 a param with name 'userId' is added to this array, which holds the value of getId() when CDbAuthManager or CPhpAuthManager is used.
$allowCaching boolean 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 CAuthManager::checkAccess to obtain the up-to-date access result. Note that this caching is effective only within the same request and only works when $params=array().
{return} boolean whether the operations can be performed by this user.
源码: framework/web/auth/CWebUser.php#812 (显示)
public function checkAccess($operation,$params=array(),$allowCaching=true)
{
    if(
$allowCaching && $params===array() && isset($this->_access[$operation]))
        return 
$this->_access[$operation];

    
$access=Yii::app()->getAuthManager()->checkAccess($operation,$this->getId(),$params);
    if(
$allowCaching && $params===array())
        
$this->_access[$operation]=$access;

    return 
$access;
}

Performs access check for this user.

clearStates() 方法
public void clearStates()
源码: framework/web/auth/CWebUser.php#619 (显示)
public function clearStates()
{
    
$keys=array_keys($_SESSION);
    
$prefix=$this->getStateKeyPrefix();
    
$n=strlen($prefix);
    foreach(
$keys as $key)
    {
        if(!
strncmp($key,$prefix,$n))
            unset(
$_SESSION[$key]);
    }
}

Clears all user identity information from persistent storage. This will remove the data stored via setState.

createIdentityCookie() 方法
protected CHttpCookie createIdentityCookie(string $name)
$name string the cookie name
{return} CHttpCookie the cookie used to store identity information
源码: framework/web/auth/CWebUser.php#530 (显示)
protected function createIdentityCookie($name)
{
    
$cookie=new CHttpCookie($name,'');
    if(
is_array($this->identityCookie))
    {
        foreach(
$this->identityCookie as $name=>$value)
            
$cookie->$name=$value;
    }
    return 
$cookie;
}

Creates a cookie to store identity information.

getFlash() 方法
public mixed getFlash(string $key, mixed $defaultValue=NULL, boolean $delete=true)
$key string key identifying the flash message
$defaultValue mixed value to be returned if the flash message is not available.
$delete boolean whether to delete this flash message after accessing it. Defaults to true.
{return} mixed the message message
源码: framework/web/auth/CWebUser.php#668 (显示)
public function getFlash($key,$defaultValue=null,$delete=true)
{
    
$value=$this->getState(self::FLASH_KEY_PREFIX.$key,$defaultValue);
    if(
$delete)
        
$this->setFlash($key,null);
    return 
$value;
}

Returns a flash message. A flash message is available only in the current and the next requests.

getFlashes() 方法 (自版本 v1.1.3 可用)
public array getFlashes(boolean $delete=true)
$delete boolean whether to delete the flash messages after calling this method.
{return} array flash messages (key => message).
源码: framework/web/auth/CWebUser.php#639 (显示)
public function getFlashes($delete=true)
{
    
$flashes=array();
    
$prefix=$this->getStateKeyPrefix().self::FLASH_KEY_PREFIX;
    
$keys=array_keys($_SESSION);
    
$n=strlen($prefix);
    foreach(
$keys as $key)
    {
        if(!
strncmp($key,$prefix,$n))
        {
            
$flashes[substr($key,$n)]=$_SESSION[$key];
            if(
$delete)
                unset(
$_SESSION[$key]);
        }
    }
    if(
$delete)
        
$this->setState(self::FLASH_COUNTERS,array());
    return 
$flashes;
}

Returns all flash messages. This method is similar to getFlash except that it returns all currently available flash messages.

getId() 方法
public mixed getId()
{return} mixed the unique identifier for the user. If null, it means the user is a guest.
源码: framework/web/auth/CWebUser.php#297 (显示)
public function getId()
{
    return 
$this->getState('__id');
}

Returns a value that uniquely represents the user.

getIsGuest() 方法
public boolean getIsGuest()
{return} boolean whether the current application user is a guest.
源码: framework/web/auth/CWebUser.php#288 (显示)
public function getIsGuest()
{
    return 
$this->getState('__id')===null;
}

Returns a value indicating whether the user is a guest (not authenticated).

getName() 方法
public string getName()
{return} string the user name. If the user is not logged in, this will be guestName.
源码: framework/web/auth/CWebUser.php#315 (显示)
public function getName()
{
    if((
$name=$this->getState('__name'))!==null)
        return 
$name;
    else
        return 
$this->guestName;
}

Returns the unique identifier for the user (e.g. username). This is the unique identifier that is mainly used for display purpose.

getReturnUrl() 方法
public string getReturnUrl(string $defaultUrl=NULL)
$defaultUrl string the default return URL in case it was not set previously. If this is null, the application entry URL will be considered as the default return URL.
{return} string the URL that the user should be redirected to after login.
源码: framework/web/auth/CWebUser.php#342 (显示)
public function getReturnUrl($defaultUrl=null)
{
    if(
$defaultUrl===null)
    {
        
$defaultReturnUrl=Yii::app()->getUrlManager()->showScriptName Yii::app()->getRequest()->getScriptUrl() : Yii::app()->getRequest()->getBaseUrl().'/';
    }
    else
    {
        
$defaultReturnUrl=CHtml::normalizeUrl($defaultUrl);
    }
    return 
$this->getState('__returnUrl',$defaultReturnUrl);
}

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.

参见

getState() 方法
public mixed getState(string $key, mixed $defaultValue=NULL)
$key string variable name
$defaultValue mixed default value
{return} mixed the value of the variable. If it doesn't exist in the session, the provided default value will be returned
源码: framework/web/auth/CWebUser.php#574 (显示)
public function getState($key,$defaultValue=null)
{
    
$key=$this->getStateKeyPrefix().$key;
    return isset(
$_SESSION[$key]) ? $_SESSION[$key] : $defaultValue;
}

Returns the value of a variable that is stored in user session.

This function is designed to be used by CWebUser descendant classes who want to store additional user information in user session. A variable, if stored in user session using setState can be retrieved back using this function.

参见

getStateKeyPrefix() 方法
public string getStateKeyPrefix()
{return} string a prefix for the name of the session variables storing user session data.
源码: framework/web/auth/CWebUser.php#544 (显示)
public function getStateKeyPrefix()
{
    if(
$this->_keyPrefix!==null)
        return 
$this->_keyPrefix;
    else
        return 
$this->_keyPrefix=md5('Yii.'.get_class($this).'.'.Yii::app()->getId());
}

hasFlash() 方法
public boolean hasFlash(string $key)
$key string key identifying the flash message
{return} boolean whether the specified flash message exists
源码: framework/web/auth/CWebUser.php#699 (显示)
public function hasFlash($key)
{
    return 
$this->getFlash($keynullfalse)!==null;
}

hasState() 方法
public boolean hasState(string $key)
$key string state name
{return} boolean whether there is a state of the specified name.
源码: framework/web/auth/CWebUser.php#609 (显示)
public function hasState($key)
{
    
$key=$this->getStateKeyPrefix().$key;
    return isset(
$_SESSION[$key]);
}

Returns a value indicating whether there is a state of the specified name.

init() 方法
public void init()
源码: framework/web/auth/CWebUser.php#197 (显示)
public function init()
{
    
parent::init();
    
Yii::app()->getSession()->open();
    if(
$this->getIsGuest() && $this->allowAutoLogin)
        
$this->restoreFromCookie();
    elseif(
$this->autoRenewCookie && $this->allowAutoLogin)
        
$this->renewCookie();
    if(
$this->autoUpdateFlash)
        
$this->updateFlash();

    
$this->updateAuthStatus();
}

Initializes the application component. This method overrides the parent implementation by starting session, performing cookie-based authentication if enabled, and updating the flash variables.

loadIdentityStates() 方法
protected void loadIdentityStates(array $states)
$states array the identity states
源码: framework/web/auth/CWebUser.php#739 (显示)
protected function loadIdentityStates($states)
{
    
$names=array();
    if(
is_array($states))
    {
        foreach(
$states as $name=>$value)
        {
            
$this->setState($name,$value);
            
$names[$name]=true;
        }
    }
    
$this->setState(self::STATES_VAR,$names);
}

Loads identity states from an array and saves them to persistent storage.

login() 方法
public boolean login(IUserIdentity $identity, integer $duration=0)
$identity IUserIdentity the user identity (which should already be authenticated)
$duration integer number of seconds that the user can remain in logged-in status. Defaults to 0, meaning login till the user closes the browser. If greater than 0, cookie-based login will be used. In this case, allowAutoLogin must be set true, otherwise an exception will be thrown.
{return} boolean whether the user is logged in
源码: framework/web/auth/CWebUser.php#229 (显示)
public function login($identity,$duration=0)
{
    
$id=$identity->getId();
    
$states=$identity->getPersistentStates();
    if(
$this->beforeLogin($id,$states,false))
    {
        
$this->changeIdentity($id,$identity->getName(),$states);

        if(
$duration>0)
        {
            if(
$this->allowAutoLogin)
                
$this->saveToCookie($duration);
            else
                throw new 
CException(Yii::t('yii','{class}.allowAutoLogin must be set true in order to use cookie-based authentication.',
                    array(
'{class}'=>get_class($this))));
        }

        if (
$this->absoluteAuthTimeout)
            
$this->setState(self::AUTH_ABSOLUTE_TIMEOUT_VARtime()+$this->absoluteAuthTimeout);
        
$this->afterLogin(false);
    }
    return !
$this->getIsGuest();
}

Logs in a user.

The user identity information will be saved in storage that is persistent during the user session. By default, the storage is simply the session storage. If the duration parameter is greater than 0, a cookie will be sent to prepare for cookie-based login in future.

Note, you have to set allowAutoLogin to true if you want to allow user to be authenticated based on the cookie information.

loginRequired() 方法
public void loginRequired()
源码: framework/web/auth/CWebUser.php#372 (显示)
public function loginRequired()
{
    
$app=Yii::app();
    
$request=$app->getRequest();

    if(!
$request->getIsAjaxRequest())
    {
        
$this->setReturnUrl($request->getUrl());
        if((
$url=$this->loginUrl)!==null)
        {
            if(
is_array($url))
            {
                
$route=isset($url[0]) ? $url[0] : $app->defaultController;
                
$url=$app->createUrl($route,array_splice($url,1));
            }
            
$request->redirect($url);
        }
    }
    elseif(isset(
$this->loginRequiredAjaxResponse))
    {
        echo 
$this->loginRequiredAjaxResponse;
        
Yii::app()->end();
    }

    throw new 
CHttpException(403,Yii::t('yii','Login Required'));
}

Redirects the user browser to the login page. Before the redirection, the current URL (if it's not an AJAX url) will be kept in returnUrl so that the user browser may be redirected back to the current page after successful login. Make sure you set loginUrl 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.

logout() 方法
public void logout(boolean $destroySession=true)
$destroySession boolean whether to destroy the whole session. Defaults to true. If false, then clearStates will be called, which removes only the data stored via setState.
源码: framework/web/auth/CWebUser.php#260 (显示)
public function logout($destroySession=true)
{
    if(
$this->beforeLogout())
    {
        if(
$this->allowAutoLogin)
        {
            
Yii::app()->getRequest()->getCookies()->remove($this->getStateKeyPrefix());
            if(
$this->identityCookie!==null)
            {
                
$cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
                
$cookie->value=null;
                
$cookie->expire=0;
                
Yii::app()->getRequest()->getCookies()->add($cookie->name,$cookie);
            }
        }
        if(
$destroySession)
            
Yii::app()->getSession()->destroy();
        else
            
$this->clearStates();
        
$this->_access=array();
        
$this->afterLogout();
    }
}

Logs out the current user. This will remove authentication-related session data. If the parameter is true, the whole session will be destroyed as well.

renewCookie() 方法 (自版本 v1.1.3 可用)
protected void renewCookie()
源码: framework/web/auth/CWebUser.php#487 (显示)
protected function renewCookie()
{
    
$request=Yii::app()->getRequest();
    
$cookies=$request->getCookies();
    
$cookie=$cookies->itemAt($this->getStateKeyPrefix());
    if(
$cookie && !empty($cookie->value) && ($data=Yii::app()->getSecurityManager()->validateData($cookie->value))!==false)
    {
        
$data=@unserialize($data);
        if(
is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
        {
            
$this->saveToCookie($data[2]);
        }
    }
}

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.

restoreFromCookie() 方法
protected void restoreFromCookie()
源码: framework/web/auth/CWebUser.php#457 (显示)
protected function restoreFromCookie()
{
    
$app=Yii::app();
    
$request=$app->getRequest();
    
$cookie=$request->getCookies()->itemAt($this->getStateKeyPrefix());
    if(
$cookie && !empty($cookie->value) && is_string($cookie->value) && ($data=$app->getSecurityManager()->validateData($cookie->value))!==false)
    {
        
$data=@unserialize($data);
        if(
is_array($data) && isset($data[0],$data[1],$data[2],$data[3]))
        {
            list(
$id,$name,$duration,$states)=$data;
            if(
$this->beforeLogin($id,$states,true))
            {
                
$this->changeIdentity($id,$name,$states);
                if(
$this->autoRenewCookie)
                {
                    
$this->saveToCookie($duration);
                }
                
$this->afterLogin(true);
            }
        }
    }
}

Populates the current user object with the information obtained from cookie. This method is used when automatic login (allowAutoLogin) is enabled. The user identity information is recovered from cookie. Sufficient security measures are used to prevent cookie data from being tampered.

参见

saveIdentityStates() 方法
protected array saveIdentityStates()
{return} array the identity states
源码: framework/web/auth/CWebUser.php#727 (显示)
protected function saveIdentityStates()
{
    
$states=array();
    foreach(
$this->getState(self::STATES_VAR,array()) as $name=>$dummy)
        
$states[$name]=$this->getState($name);
    return 
$states;
}

Retrieves identity states from persistent storage and saves them as an array.

saveToCookie() 方法
protected void saveToCookie(integer $duration)
$duration integer number of seconds that the user can remain in logged-in status. Defaults to 0, meaning login till the user closes the browser.
源码: framework/web/auth/CWebUser.php#510 (显示)
protected function saveToCookie($duration)
{
    
$app=Yii::app();
    
$cookie=$this->createIdentityCookie($this->getStateKeyPrefix());
    
$cookie->expire=time()+$duration;
    
$data=array(
        
$this->getId(),
        
$this->getName(),
        
$duration,
        
$this->saveIdentityStates(),
    );
    
$cookie->value=$app->getSecurityManager()->hashData(serialize($data));
    
$app->getRequest()->getCookies()->add($cookie->name,$cookie);
}

Saves necessary user data into a cookie. This method is used when automatic login (allowAutoLogin) is enabled. This method saves user ID, username, other identity states and a validation key to cookie. These information are used to do authentication next time when user visits the application.

setFlash() 方法
public void setFlash(string $key, mixed $value, mixed $defaultValue=NULL)
$key string key identifying the flash message
$value mixed flash message
$defaultValue mixed if this value is the same as the flash message, the flash message will be removed. (Therefore, you can use setFlash('key',null) to remove a flash message.)
源码: framework/web/auth/CWebUser.php#684 (显示)
public function setFlash($key,$value,$defaultValue=null)
{
    
$this->setState(self::FLASH_KEY_PREFIX.$key,$value,$defaultValue);
    
$counters=$this->getState(self::FLASH_COUNTERS,array());
    if(
$value===$defaultValue)
        unset(
$counters[$key]);
    else
        
$counters[$key]=0;
    
$this->setState(self::FLASH_COUNTERS,$counters,array());
}

Stores a flash message. A flash message is available only in the current and the next requests.

setId() 方法
public void setId(mixed $value)
$value mixed the unique identifier for the user. If null, it means the user is a guest.
源码: framework/web/auth/CWebUser.php#305 (显示)
public function setId($value)
{
    
$this->setState('__id',$value);
}

setName() 方法
public void setName(string $value)
$value string the user name.
源码: framework/web/auth/CWebUser.php#328 (显示)
public function setName($value)
{
    
$this->setState('__name',$value);
}

Sets the unique identifier for the user (e.g. username).

参见

setReturnUrl() 方法
public void setReturnUrl(string $value)
$value string the URL that the user should be redirected to after login.
源码: framework/web/auth/CWebUser.php#358 (显示)
public function setReturnUrl($value)
{
    
$this->setState('__returnUrl',$value);
}

setState() 方法
public void setState(string $key, mixed $value, mixed $defaultValue=NULL)
$key string variable name
$value mixed variable value
$defaultValue mixed default value. If $value===$defaultValue, the variable will be removed from the session
源码: framework/web/auth/CWebUser.php#595 (显示)
public function setState($key,$value,$defaultValue=null)
{
    
$key=$this->getStateKeyPrefix().$key;
    if(
$value===$defaultValue)
        unset(
$_SESSION[$key]);
    else
        
$_SESSION[$key]=$value;
}

Stores a variable in user session.

This function is designed to be used by CWebUser descendant classes who want to store additional user information in user session. By storing a variable using this function, the variable may be retrieved back later using getState. The variable will be persistent across page requests during a user session.

参见

setStateKeyPrefix() 方法
public void setStateKeyPrefix(string $value)
$value string a prefix for the name of the session variables storing user session data.
源码: framework/web/auth/CWebUser.php#555 (显示)
public function setStateKeyPrefix($value)
{
    
$this->_keyPrefix=$value;
}

updateAuthStatus() 方法 (自版本 v1.1.7 可用)
protected void updateAuthStatus()
源码: framework/web/auth/CWebUser.php#782 (显示)
protected function updateAuthStatus()
{
    if((
$this->authTimeout!==null || $this->absoluteAuthTimeout!==null) && !$this->getIsGuest())
    {
        
$expires=$this->getState(self::AUTH_TIMEOUT_VAR);
        
$expiresAbsolute=$this->getState(self::AUTH_ABSOLUTE_TIMEOUT_VAR);

        if (
$expires!==null && $expires time() || $expiresAbsolute!==null && $expiresAbsolute time())
            
$this->logout(false);
        else
            
$this->setState(self::AUTH_TIMEOUT_VAR,time()+$this->authTimeout);
    }
}

Updates the authentication status according to authTimeout. If the user has been inactive for authTimeout seconds, or {link absoluteAuthTimeout} has passed, he will be automatically logged out.

updateFlash() 方法
protected void updateFlash()
源码: framework/web/auth/CWebUser.php#758 (显示)
protected function updateFlash()
{
    
$counters=$this->getState(self::FLASH_COUNTERS);
    if(!
is_array($counters))
        return;
    foreach(
$counters as $key=>$count)
    {
        if(
$count)
        {
            unset(
$counters[$key]);
            
$this->setState(self::FLASH_KEY_PREFIX.$key,null);
        }
        else
            
$counters[$key]++;
    }
    
$this->setState(self::FLASH_COUNTERS,$counters,array());
}

Updates the internal counters for flash messages. This method is internally used by CWebApplication to maintain the availability of flash messages.