PHP Класс 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'], ... ] ~~~
С версии: 2.0
Автор: Qiang Xue ([email protected])
Наследование: extends yii\base\Component
Показать файл Открыть проект Примеры использования класса

Открытые свойства

Свойство Тип Описание
$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]].

Открытые методы

Метод Описание
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.

Защищенные методы

Метод Описание
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.

Описание методов

afterLogin() защищенный Метод

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() защищенный Метод

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() защищенный Метод

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.
Результат boolean whether the user should continue to be logged in

beforeLogout() защищенный Метод

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
Результат boolean whether the user should continue to be logged out

can() публичный Метод

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 = []`.
Результат boolean whether the user can perform the operation as specified by the given permission.

checkRedirectAcceptable() защищенный Метод

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.
См. также: acceptableRedirectTypes
С версии: 2.0.8
protected checkRedirectAcceptable ( ) : boolean
Результат boolean whether this request may be redirected to the login page.

getAccessChecker() защищенный Метод

Returns the access checker used for checking access.
С версии: 2.0.9
protected getAccessChecker ( ) : yii\rbac\CheckAccessInterface
Результат yii\rbac\CheckAccessInterface

getAuthManager() защищенный Метод

By default this is the authManager application component. You may override this method to return a different auth manager instance if needed.
Устаревший: since version 2.0.9, to be removed in 2.1. Use [[getAccessChecker()]] instead.
С версии: 2.0.6
protected getAuthManager ( ) : yii\rbac\ManagerInterface
Результат yii\rbac\ManagerInterface

getId() публичный Метод

Returns a value that uniquely represents the user.
См. также: getIdentity()
public getId ( ) : string | integer
Результат string | integer the unique identifier for the user. If `null`, it means the user is a guest.

getIdentity() публичный Метод

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.
См. также: login()
См. также: 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.
Результат 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() защищенный Метод

This method is used when [[enableAutoLogin]] is true. This method attempts to authenticate a user using the information in the identity cookie.
См. также: loginByCookie()
С версии: 2.0.9
protected getIdentityAndDurationFromCookie ( ) : array | null
Результат array | null Returns an array of 'identity' and 'duration' if valid, otherwise null.

getIsGuest() публичный Метод

Returns a value indicating whether the user is a guest (not authenticated).
См. также: getIdentity()
public getIsGuest ( ) : boolean
Результат boolean whether the current user is a guest.

getReturnUrl() публичный Метод

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.
См. также: 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.
Результат string the URL that the user should be redirected to after login.

init() публичный Метод

Initializes the application component.
public init ( )

login() публичный Метод

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`
Результат boolean whether the user is logged in

loginByAccessToken() публичный Метод

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`.
Результат 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() защищенный Метод

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

loginRequired() публичный Метод

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.
Результат Response the redirection response if [[loginUrl]] is set

logout() публичный Метод

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.
Результат boolean whether the user is logged out

removeIdentityCookie() защищенный Метод

This method is used when [[enableAutoLogin]] is true.
С версии: 2.0.9
protected removeIdentityCookie ( )

renewAuthStatus() защищенный Метод

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() защищенный Метод

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() защищенный Метод

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.
См. также: 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() публичный Метод

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() публичный Метод

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() публичный Метод

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.

Описание свойств

$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.
public $absoluteAuthTimeout

$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.
public $absoluteAuthTimeoutParam

$acceptableRedirectTypes публичное свойство

MIME types for which this component should redirect to the [[loginUrl]].
С версии: 2.0.8
public $acceptableRedirectTypes

$accessChecker публичное свойство

The access checker to use for checking access. If not set the application auth manager will be used.
С версии: 2.0.9
public $accessChecker

$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.
public $authTimeout

$authTimeoutParam публичное свойство

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 публичное свойство

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
public $autoRenewCookie

$enableAutoLogin публичное свойство

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

$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.
public $enableSession

$idParam публичное свойство

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

$identityClass публичное свойство

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

$identityCookie публичное свойство

the configuration of the identity cookie. This property is used only when [[enableAutoLogin]] is true.
См. также: Cookie
public $identityCookie

$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.
public $loginUrl

$returnUrlParam публичное свойство

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