PHP Class yii\web\User

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. You may call various methods to change the user authentication status: - User::login: sets the specified identity and remembers the authentication status in session and cookie. - User::logout: marks the user as a guest and clears the relevant information from session and cookie. - User::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. User is configured as an application component in Application by default. 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'], ... ] ~~~
Since: 2.0
Author: Qiang Xue ([email protected])
Inheritance: extends yii\base\Component
Afficher le fichier Open project: yiisoft/yii2 Class Usage Examples

Méthodes publiques

Свойство Type Description
$absoluteAuthTimeout the number of seconds in which the user will be logged out automatically regardless of activity. Note that this will not work if [[enableAutoLogin]] is true.
$absoluteAuthTimeoutParam the session variable name used to store the value of absolute expiration timestamp of the authenticated state. This is used when [[absoluteAuthTimeout]] is set.
$acceptableRedirectTypes MIME types for which this component should redirect to the [[loginUrl]].
$accessChecker The access checker to use for checking access. If not set the application auth manager will be used.
$authTimeout 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]]). Note that this will not work if [[enableAutoLogin]] is true.
$authTimeoutParam the session variable name used to store the value of expiration timestamp of the authenticated state. This is used when [[authTimeout]] is set.
$autoRenewCookie whether to automatically renew the identity cookie each time a page is requested. This property is effective only when [[enableAutoLogin]] 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.
$enableAutoLogin whether to enable cookie-based login. Defaults to false. Note that this property will be ignored if [[enableSession]] is false.
$enableSession whether to use session to persist authentication status across multiple requests. You set this property to be false if your application is stateless, which is often the case for RESTful APIs.
$idParam the session variable name used to store the value of [[id]].
$identityClass the class name of the [[identity]] object.
$identityCookie the configuration of the identity cookie. This property is used only when [[enableAutoLogin]] is true.
$loginUrl the URL for login when User::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, php ['site/login', 'ref' => 1] If this property is null, a 403 HTTP exception will be raised when User::loginRequired is called.
$returnUrlParam the session variable name used to store the value of [[returnUrl]].

Méthodes publiques

Méthode Description
can ( string $permissionName, array $params = [], boolean $allowCaching = true ) : boolean Checks if the user can perform the operation as specified by the given permission.
getId ( ) : string | integer Returns a value that uniquely represents the user.
getIdentity ( boolean $autoRenew = true ) : yii\web\IdentityInterface | null Returns the identity object associated with the currently logged-in user.
getIsGuest ( ) : boolean Returns a value indicating whether the user is a guest (not authenticated).
getReturnUrl ( string | array $defaultUrl = null ) : string Returns the URL that the browser should be redirected to after successful login.
init ( ) Initializes the application component.
login ( yii\web\IdentityInterface $identity, integer $duration ) : boolean Logs in a user.
loginByAccessToken ( string $token, mixed $type = null ) : yii\web\IdentityInterface | null Logs in a user by the given access token.
loginRequired ( boolean $checkAjax = true, boolean $checkAcceptHeader = true ) : Response Redirects the user browser to the login page.
logout ( boolean $destroySession = true ) : boolean Logs out the current user.
setIdentity ( yii\web\IdentityInterface | null $identity ) Sets the user identity object.
setReturnUrl ( string | array $url ) Remembers the URL in the session so that it can be retrieved back later by User::getReturnUrl.
switchIdentity ( yii\web\IdentityInterface | null $identity, integer $duration ) Switches to a new identity for the current user.

Méthodes protégées

Méthode Description
afterLogin ( yii\web\IdentityInterface $identity, boolean $cookieBased, integer $duration ) This method is called after the user is successfully logged in.
afterLogout ( yii\web\IdentityInterface $identity ) This method is invoked right after a user is logged out via User::logout.
beforeLogin ( yii\web\IdentityInterface $identity, boolean $cookieBased, integer $duration ) : boolean This method is called before logging in a user.
beforeLogout ( yii\web\IdentityInterface $identity ) : boolean This method is invoked when calling User::logout to log out a user.
checkRedirectAcceptable ( ) : boolean Checks if the Accept header contains a content type that allows redirection to the login page.
getAccessChecker ( ) : yii\rbac\CheckAccessInterface Returns the access checker used for checking access.
getAuthManager ( ) : yii\rbac\ManagerInterface Returns auth manager associated with the user component.
getIdentityAndDurationFromCookie ( ) : array | null Determines if an identity cookie has a valid format and contains a valid auth key.
loginByCookie ( ) Logs in a user by cookie.
removeIdentityCookie ( ) Removes the identity cookie.
renewAuthStatus ( ) Updates the authentication status using the information from session and cookie.
renewIdentityCookie ( ) Renews the identity cookie.
sendIdentityCookie ( yii\web\IdentityInterface $identity, integer $duration ) Sends an identity cookie.

Method Details

afterLogin() protected méthode

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.
protected afterLogin ( yii\web\IdentityInterface $identity, boolean $cookieBased, integer $duration )
$identity yii\web\IdentityInterface the user identity information
$cookieBased boolean whether the login is cookie-based
$duration integer 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.

afterLogout() protected méthode

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.
protected afterLogout ( yii\web\IdentityInterface $identity )
$identity yii\web\IdentityInterface the user identity information

beforeLogin() protected méthode

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.
protected beforeLogin ( yii\web\IdentityInterface $identity, boolean $cookieBased, integer $duration ) : boolean
$identity yii\web\IdentityInterface the user identity information
$cookieBased boolean whether the login is cookie-based
$duration integer 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.
Résultat boolean whether the user should continue to be logged in

beforeLogout() protected méthode

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.
protected beforeLogout ( yii\web\IdentityInterface $identity ) : boolean
$identity yii\web\IdentityInterface the user identity information
Résultat boolean whether the user should continue to be logged out

can() public méthode

Note that you must configure "authManager" application component in order to use this method. Otherwise it will always return false.
public can ( string $permissionName, array $params = [], boolean $allowCaching = true ) : boolean
$permissionName string the name of the permission (e.g. "edit post") that needs access check.
$params array name-value pairs that would be passed to the rules associated with the roles and permissions assigned to the user.
$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 [[\yii\rbac\CheckAccessInterface::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 = []`.
Résultat boolean whether the user can perform the operation as specified by the given permission.

checkRedirectAcceptable() protected méthode

The login page is assumed to serve text/html or application/xhtml+xml by default. You can change acceptable content types by modifying [[acceptableRedirectTypes]] property.
See also: acceptableRedirectTypes
Since: 2.0.8
protected checkRedirectAcceptable ( ) : boolean
Résultat boolean whether this request may be redirected to the login page.

getAccessChecker() protected méthode

Returns the access checker used for checking access.
Since: 2.0.9
protected getAccessChecker ( ) : yii\rbac\CheckAccessInterface
Résultat yii\rbac\CheckAccessInterface

getAuthManager() protected méthode

By default this is the authManager application component. You may override this method to return a different auth manager instance if needed.
Deprecation: since version 2.0.9, to be removed in 2.1. Use [[getAccessChecker()]] instead.
Since: 2.0.6
protected getAuthManager ( ) : yii\rbac\ManagerInterface
Résultat yii\rbac\ManagerInterface

getId() public méthode

Returns a value that uniquely represents the user.
See also: getIdentity()
public getId ( ) : string | integer
Résultat string | integer the unique identifier for the user. If `null`, it means the user is a guest.

getIdentity() public méthode

When [[enableSession]] is true, this method may attempt to read the user's authentication data stored in session and reconstruct the corresponding identity object, if it has not done so before.
See also: login()
See also: logout()
public getIdentity ( boolean $autoRenew = true ) : yii\web\IdentityInterface | null
$autoRenew boolean whether to automatically renew authentication status if it has not been done so before. This is only useful when [[enableSession]] is true.
Résultat yii\web\IdentityInterface | null the identity object associated with the currently logged-in user. `null` is returned if the user is not logged in (not authenticated).

getIdentityAndDurationFromCookie() protected méthode

This method is used when [[enableAutoLogin]] is true. This method attempts to authenticate a user using the information in the identity cookie.
See also: loginByCookie()
Since: 2.0.9
protected getIdentityAndDurationFromCookie ( ) : array | null
Résultat array | null Returns an array of 'identity' and 'duration' if valid, otherwise null.

getIsGuest() public méthode

Returns a value indicating whether the user is a guest (not authenticated).
See also: getIdentity()
public getIsGuest ( ) : boolean
Résultat boolean whether the current user is a guest.

getReturnUrl() public méthode

This method reads the return URL from the session. It is usually used by the login action which may call this method to redirect the browser to where it goes after successful authentication.
See also: loginRequired()
public getReturnUrl ( string | array $defaultUrl = null ) : string
$defaultUrl string | array the default return URL in case it was not set previously. 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.
Résultat string the URL that the user should be redirected to after login.

init() public méthode

Initializes the application component.
public init ( )

login() public méthode

After logging in a user: - the user's identity information is obtainable from the [[identity]] property If [[enableSession]] is true: - the identity information will be stored in session and be available in the next requests - in case of $duration == 0: as long as the session remains active or till the user closes the browser - in case of $duration > 0: as long as the session remains active or as long as the cookie remains valid by it's $duration in seconds when [[enableAutoLogin]] is set true. If [[enableSession]] is false: - the $duration parameter will be ignored
public login ( yii\web\IdentityInterface $identity, integer $duration ) : boolean
$identity yii\web\IdentityInterface 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`
Résultat boolean whether the user is logged in

loginByAccessToken() public méthode

This method will first authenticate the user by calling [[IdentityInterface::findIdentityByAccessToken()]] with the provided access token. If successful, it will call User::login to log in the authenticated user. If authentication fails or User::login is unsuccessful, it will return null.
public loginByAccessToken ( string $token, mixed $type = null ) : yii\web\IdentityInterface | null
$token string the access token
$type mixed the type of the token. The value of this parameter depends on the implementation. For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be `yii\filters\auth\HttpBearerAuth`.
Résultat yii\web\IdentityInterface | null the identity associated with the given access token. Null is returned if the access token is invalid or [[login()]] is unsuccessful.

loginByCookie() protected méthode

This method attempts to log in a user using the ID and authKey information provided by the [[identityCookie|identity cookie]].
protected loginByCookie ( )

loginRequired() public méthode

Before the redirection, the current URL (if it's not an AJAX url) will be kept as [[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. Note that when [[loginUrl]] is set, calling this method will NOT terminate the application execution.
public loginRequired ( boolean $checkAjax = true, boolean $checkAcceptHeader = true ) : Response
$checkAjax boolean whether to check if the request is an AJAX request. When this is true and the request is an AJAX request, the current URL (for AJAX request) will NOT be set as the return URL.
$checkAcceptHeader boolean whether to check if the request accepts HTML responses. Defaults to `true`. When this is true and the request does not accept HTML responses the current URL will not be SET as the return URL. Also instead of redirecting the user an ForbiddenHttpException is thrown. This parameter is available since version 2.0.8.
Résultat Response the redirection response if [[loginUrl]] is set

logout() public méthode

This will remove authentication-related session data. If $destroySession is true, all session data will be removed.
public logout ( boolean $destroySession = true ) : boolean
$destroySession boolean whether to destroy the whole session. Defaults to true. This parameter is ignored if [[enableSession]] is false.
Résultat boolean whether the user is logged out

removeIdentityCookie() protected méthode

This method is used when [[enableAutoLogin]] is true.
Since: 2.0.9
protected removeIdentityCookie ( )

renewAuthStatus() protected méthode

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.
protected renewAuthStatus ( )

renewIdentityCookie() protected méthode

This method will set the expiration time of the identity cookie to be the current time plus the originally specified cookie duration.
protected renewIdentityCookie ( )

sendIdentityCookie() protected méthode

This method is used when [[enableAutoLogin]] is true. It saves [[id]], [[IdentityInterface::getAuthKey()|auth key]], and the duration of cookie-based login information in the cookie.
See also: loginByCookie()
protected sendIdentityCookie ( yii\web\IdentityInterface $identity, integer $duration )
$identity yii\web\IdentityInterface
$duration integer number of seconds that the user can remain in logged-in status.

setIdentity() public méthode

Note that this method does not deal with session or cookie. You should usually use User::switchIdentity to change the identity of the current user.
public setIdentity ( yii\web\IdentityInterface | null $identity )
$identity yii\web\IdentityInterface | null the identity object associated with the currently logged user. If null, it means the current user will be a guest without any associated identity.

setReturnUrl() public méthode

Remembers the URL in the session so that it can be retrieved back later by User::getReturnUrl.
public setReturnUrl ( string | array $url )
$url string | array the URL that the user should be redirected to after login. 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, ```php ['admin/index', 'ref' => 1] ```

switchIdentity() public méthode

When [[enableSession]] is true, this method may use session and/or cookie to store the user identity information, according to the value of $duration. Please refer to User::login for more details. This method is mainly called by User::login, User::logout and User::loginByCookie when the current user needs to be associated with the corresponding identity information.
public switchIdentity ( yii\web\IdentityInterface | null $identity, integer $duration )
$identity yii\web\IdentityInterface | null the identity information to be associated with the current user. If null, it means switching the current user to be a guest.
$duration integer number of seconds that the user can remain in logged-in status. This parameter is used only when `$identity` is not null.

Property Details

$absoluteAuthTimeout public_oe property

the number of seconds in which the user will be logged out automatically regardless of activity. Note that this will not work if [[enableAutoLogin]] is true.
public $absoluteAuthTimeout

$absoluteAuthTimeoutParam public_oe property

the session variable name used to store the value of absolute expiration timestamp of the authenticated state. This is used when [[absoluteAuthTimeout]] is set.
public $absoluteAuthTimeoutParam

$acceptableRedirectTypes public_oe property

MIME types for which this component should redirect to the [[loginUrl]].
Since: 2.0.8
public $acceptableRedirectTypes

$accessChecker public_oe property

The access checker to use for checking access. If not set the application auth manager will be used.
Since: 2.0.9
public $accessChecker

$authTimeout public_oe property

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]]). Note that this will not work if [[enableAutoLogin]] is true.
public $authTimeout

$authTimeoutParam public_oe property

the session variable name used to store the value of expiration timestamp of the authenticated state. This is used when [[authTimeout]] is set.
public $authTimeoutParam

$autoRenewCookie public_oe property

whether to automatically renew the identity cookie each time a page is requested. This property is effective only when [[enableAutoLogin]] 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.
See also: enableAutoLogin
public $autoRenewCookie

$enableAutoLogin public_oe property

whether to enable cookie-based login. Defaults to false. Note that this property will be ignored if [[enableSession]] is false.
public $enableAutoLogin

$enableSession public_oe property

whether to use session to persist authentication status across multiple requests. You set this property to be false if your application is stateless, which is often the case for RESTful APIs.
public $enableSession

$idParam public_oe property

the session variable name used to store the value of [[id]].
public $idParam

$identityClass public_oe property

the class name of the [[identity]] object.
public $identityClass

$identityCookie public_oe property

the configuration of the identity cookie. This property is used only when [[enableAutoLogin]] is true.
See also: Cookie
public $identityCookie

$loginUrl public_oe property

the URL for login when User::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, php ['site/login', 'ref' => 1] If this property is null, a 403 HTTP exception will be raised when User::loginRequired is called.
public $loginUrl

$returnUrlParam public_oe property

the session variable name used to store the value of [[returnUrl]].
public $returnUrlParam