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 IUserIdentity identity which
implements the actual authentication algorithm.
A typical authentication process using CWebUser is as follows:
- The user provides information needed for authentication.
- An IUserIdentity identity instance is created with the user-provided
information.
- Call
IUserIdentity::authenticate()
to check if the identity is
valid.
- If valid, call
CWebUser::login()
to login the user, and Redirect the
user browser to returnUrl.
- 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 IUserIdentity 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 CWebUser::getState()
. Note, when allowAutoLogin 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.
Methods summary
public
mixed
|
#
__get( string $name )
PHP magic method. This method is overriden so that persistent states can be
accessed like properties.
PHP magic method. This method is overriden so that persistent states can be
accessed like properties.
Parameters
- $name
string $name property name
Returns
mixed property value
Throws
Overrides
|
public
mixed
|
#
__set( string $name, mixed $value )
PHP magic method. This method is overriden so that persistent states can be
set like properties.
PHP magic method. This method is overriden so that persistent states can be
set like properties.
Parameters
- $name
string $name property name
- $value
mixed $value property value
Returns
mixed
Throws
CException
if the property/event is not defined or the property is read only.
Overrides
|
public
boolean
|
#
__isset( string $name )
PHP magic method. This method is overriden so that persistent states can also
be checked for null value.
PHP magic method. This method is overriden so that persistent states can also
be checked for null value.
Parameters
- $name
string $name property name
Returns
boolean
Overrides
|
public
mixed
|
#
__unset( string $name )
PHP magic method. This method is overriden so that persistent states can also
be unset.
PHP magic method. This method is overriden so that persistent states can also
be unset.
Parameters
- $name
string $name property name
Returns
mixed
Throws
Overrides
|
public
|
#
init( )
Initializes the application component. This method overrides the parent
implementation by starting session, performing cookie-based authentication if
enabled, and updating the flash variables.
Initializes the application component. This method overrides the parent
implementation by starting session, performing cookie-based authentication if
enabled, and updating the flash variables.
Overrides
|
public
boolean
|
#
login( IUserIdentity $identity, integer $duration = 0 )
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 CWebUser::$allowAutoLogin to true if you want to allow
user to be authenticated based on the cookie information.
Parameters
- $identity
IUserIdentity
$identity the user identity (which should already be authenticated)
- $duration
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. If greater than
0, cookie-based login will be used. In this case, CWebUser::$allowAutoLogin must be
set true, otherwise an exception will be thrown.
Returns
boolean whether the user is logged in
|
public
|
#
logout( boolean $destroySession = true )
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.
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.
Parameters
|
public
boolean
|
#
getIsGuest( )
Returns a value indicating whether the user is a guest (not
authenticated).
Returns a value indicating whether the user is a guest (not
authenticated).
Returns
boolean whether the current application user is a guest.
Implementation of
|
public
mixed
|
#
getId( )
Returns a value that uniquely represents the user.
Returns a value that uniquely represents the user.
Returns
mixed the unique identifier for the user. If null, it means the user is a guest.
Implementation of
|
public
|
#
setId( mixed $value )
Parameters
- $value
mixed $value the unique identifier for the user. If null, it means the user is a
guest.
|
public
string
|
#
getName( )
Returns the unique identifier for the user (e.g. username). This is the
unique identifier that is mainly used for display purpose.
Returns the unique identifier for the user (e.g. username). This is the
unique identifier that is mainly used for display purpose.
Returns
Implementation of
|
public
|
#
setName( string $value )
Sets the unique identifier for the user (e.g. username).
Sets the unique identifier for the user (e.g. username).
Parameters
- $value
string $value the user name.
See
|
public
string
|
#
getReturnUrl( string $defaultUrl = null )
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.
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.
Parameters
- $defaultUrl
string $defaultUrl 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.
Returns
string the URL that the user should be redirected to after login.
See
|
public
|
#
setReturnUrl( string $value )
Parameters
- $value
string $value the URL that the user should be redirected to after login.
|
public
|
#
loginRequired( )
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 CWebUser::$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.
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 CWebUser::$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.
Implementation of
|
protected
boolean
|
#
beforeLogin( mixed $id, array $states, boolean $fromCookie )
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.
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.
Parameters
- $id
mixed $id the user ID. This is the same as returned by CWebUser::getId() .
- $states
array $states a set of name-value pairs that are provided by the user identity.
- $fromCookie
boolean $fromCookie whether the login is based on cookie
Returns
boolean whether the user should be logged in
Since
1.1.3
|
protected
|
#
afterLogin( boolean $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).
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).
Parameters
- $fromCookie
boolean $fromCookie whether the login is based on cookie.
Since
1.1.3
|
protected
boolean
|
#
beforeLogout( )
This method is invoked when calling CWebUser::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.
This method is invoked when calling CWebUser::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.
Returns
boolean whether to log out the user
Since
1.1.3
|
protected
|
#
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.
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.
Since
1.1.3
|
protected
|
#
restoreFromCookie( )
Populates the current user object with the information obtained from cookie.
This method is used when automatic login (CWebUser::$allowAutoLogin ) is enabled.
The user identity information is recovered from cookie. Sufficient security
measures are used to prevent cookie data from being tampered.
Populates the current user object with the information obtained from cookie.
This method is used when automatic login (CWebUser::$allowAutoLogin ) is enabled.
The user identity information is recovered from cookie. Sufficient security
measures are used to prevent cookie data from being tampered.
See
|
protected
|
#
renewCookie( )
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.
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.
Since
1.1.3
|
protected
|
#
saveToCookie( integer $duration )
Saves necessary user data into a cookie. This method is used when automatic
login (CWebUser::$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.
Saves necessary user data into a cookie. This method is used when automatic
login (CWebUser::$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.
Parameters
- $duration
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.
See
|
protected
CHttpCookie
|
#
createIdentityCookie( string $name )
Creates a cookie to store identity information.
Creates a cookie to store identity information.
Parameters
- $name
string $name the cookie name
Returns
CHttpCookie
the cookie used to store identity information
|
public
string
|
#
getStateKeyPrefix( )
Returns
string a prefix for the name of the session variables storing user session data.
|
public
|
#
setStateKeyPrefix( string $value )
Parameters
- $value
string $value a prefix for the name of the session variables storing user session data.
|
public
mixed
|
#
getState( string $key, mixed $defaultValue = null )
Returns the value of a variable that is stored in user session.
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 CWebUser::setState() can be retrieved back using this
function.
Parameters
- $key
string $key variable name
- $defaultValue
mixed $defaultValue default value
Returns
mixed the value of the variable. If it doesn't exist in the session, the provided
default value will be returned
See
|
public
|
#
setState( string $key, mixed $value, mixed $defaultValue = null )
Stores a variable in user session.
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 CWebUser::getState() . The variable will be persistent across page requests during a user
session.
Parameters
- $key
string $key variable name
- $value
mixed $value variable value
- $defaultValue
mixed $defaultValue default value. If $value===$defaultValue, the variable will be
removed from the session
See
|
public
boolean
|
#
hasState( string $key )
Returns a value indicating whether there is a state of the specified
name.
Returns a value indicating whether there is a state of the specified
name.
Parameters
- $key
string $key state name
Returns
boolean whether there is a state of the specified name.
|
public
|
|
public
array
|
#
getFlashes( boolean $delete = true )
Returns all flash messages. This method is similar to CWebUser::getFlash() except
that it returns all currently available flash messages.
Returns all flash messages. This method is similar to CWebUser::getFlash() except
that it returns all currently available flash messages.
Parameters
- $delete
boolean $delete whether to delete the flash messages after calling this method.
Returns
array flash messages (key => message).
Since
1.1.3
|
public
mixed
|
#
getFlash( string $key, mixed $defaultValue = null, boolean $delete = true )
Returns a flash message. A flash message is available only in the current and
the next requests.
Returns a flash message. A flash message is available only in the current and
the next requests.
Parameters
- $key
string $key key identifying the flash message
- $defaultValue
mixed $defaultValue value to be returned if the flash message is not available.
- $delete
boolean $delete whether to delete this flash message after accessing it. Defaults to
true.
Returns
mixed the message message
|
public
|
#
setFlash( string $key, mixed $value, mixed $defaultValue = null )
Stores a flash message. A flash message is available only in the current and
the next requests.
Stores a flash message. A flash message is available only in the current and
the next requests.
Parameters
- $key
string $key key identifying the flash message
- $value
mixed $value flash message
- $defaultValue
mixed $defaultValue 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.)
|
public
boolean
|
#
hasFlash( string $key )
Parameters
- $key
string $key key identifying the flash message
Returns
boolean whether the specified flash message exists
|
protected
|
#
changeIdentity( mixed $id, string $name, array $states )
Changes the current user with the specified identity information. This method
is called by CWebUser::login() and CWebUser::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.
Changes the current user with the specified identity information. This method
is called by CWebUser::login() and CWebUser::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.
Parameters
- $id
mixed $id a unique identifier for the user
- $name
string $name the display name for the user
- $states
array $states identity states
|
protected
array
|
#
saveIdentityStates( )
Retrieves identity states from persistent storage and saves them as an
array.
Retrieves identity states from persistent storage and saves them as an
array.
Returns
array the identity states
|
protected
|
#
loadIdentityStates( array $states )
Loads identity states from an array and saves them to persistent storage.
Loads identity states from an array and saves them to persistent storage.
Parameters
- $states
array $states the identity states
|
protected
|
#
updateFlash( )
Updates the internal counters for flash messages. This method is internally
used by CWebApplication to maintain the availability of flash
messages.
Updates the internal counters for flash messages. This method is internally
used by CWebApplication to maintain the availability of flash
messages.
|
protected
|
|
public
boolean
|
#
checkAccess( string $operation, array $params = array(), boolean $allowCaching = true )
Performs access check for this user.
Performs access check for this user.
Parameters
- $operation
string $operation the name of the operation that need access check.
- $params
array $params 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 CWebUser::getId() when
CDbAuthManager or CPhpAuthManager is used.
- $allowCaching
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
IAuthManager::checkAccess() to obtain the up-to-date access result. Note
that this caching is effective only within the same request and only works when
<span class="php-var">$params</span>=<span
class="php-keyword1">array</span>() .
Returns
boolean whether the operations can be performed by this user.
Implementation of
|
Properties summary
public
boolean
|
$allowAutoLogin
|
false |
#
whether to enable cookie-based login. Defaults to false.
whether to enable cookie-based login. Defaults to false.
|
public
string
|
$guestName
|
'Guest' |
#
the name for a guest user. Defaults to 'Guest'. This is used by CWebUser::getName() when the current user is a guest (not authenticated).
the name for a guest user. Defaults to 'Guest'. This is used by CWebUser::getName() when the current user is a guest (not authenticated).
|
public
string|array
|
$loginUrl
|
array('/site/login') |
#
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.
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.
See
|
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 CWebUser::$allowAutoLogin is true.
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 CWebUser::$allowAutoLogin is true.
|
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).
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).
Since
1.1.7
|
public
integer
|
$absoluteAuthTimeout
|
|
#
timeout in seconds after which user is logged out regardless of activity.
timeout in seconds after which user is logged out regardless of activity.
Since
1.1.14
|
public
boolean
|
$autoRenewCookie
|
false |
#
whether to automatically renew the identity cookie each time a page is
requested. Defaults to false. This property is effective only when CWebUser::$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.
whether to automatically renew the identity cookie each time a page is
requested. Defaults to false. This property is effective only when CWebUser::$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.
Since
1.1.0
See
|
public
boolean
|
$autoUpdateFlash
|
true |
#
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 CWebUser::getFlash() with the 3rd parameter being true).
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 CWebUser::getFlash() with the 3rd parameter being true).
Since
1.1.7
|
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, CWebUser::loginRequired() redirects to CWebUser::$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.
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, CWebUser::loginRequired() redirects to CWebUser::$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.
Since
1.1.9
See
|