User ​
- Type
- Class
- Namespace
- craft\web
- Inherits
- craft\web\User » yii\web\User » yii\base\Component » yii\base\BaseObject
- Implements
- yii\base\Configurable
- Since
- 3.0.0
The User component provides APIs for managing the user authentication status.
An instance of the User component is globally accessible in Craft via Craft::$app->user
.
Public Properties ​
Property | Description |
---|---|
absoluteAuthTimeout | integer, null – The number of seconds in which the user will be logged out automatically regardless of activity. |
absoluteAuthTimeoutParam | string – The session variable name used to store the value of absolute expiration timestamp of the authenticated state. |
acceptableRedirectTypes | array – MIME types for which this component should redirect to the loginUrl. |
accessChecker | yii\rbac\CheckAccessInterface, string, array, null – The access checker object to use for checking access or the application component ID of the access checker. |
authDurationParam | string – The session variable name used to store the duration of the authenticated state. |
authKeyParam | string – The session variable name used to store authentication key. |
authTimeout | integer, null – The number of seconds in which the user will be logged out automatically if the user remains inactive. |
authTimeoutParam | string – The session variable name used to store the value of expiration timestamp of the authenticated state. |
autoRenewCookie | boolean – Whether to automatically renew the identity cookie each time a page is requested. |
behaviors | yii\base\Behavior – List of behaviors attached to this component. |
elevatedSessionTimeout | integer, boolean – The number of seconds left in the current elevated user session or false if it has been disabled. |
elevatedSessionTimeoutParam | string – The session variable name used to store the value of the expiration timestamp of the elevated session state. |
enableAutoLogin | boolean – Whether to enable cookie-based login. |
enableSession | boolean – Whether to use session to persist authentication status across multiple requests. |
hasElevatedSession | boolean – Whether the user currently has an elevated session |
id | string, integer, null – The unique identifier for the user. |
idParam | string – The session variable name used to store the value of id. |
identity | craft\elements\User, null – The logged-in user. |
identityClass | string – The class name of the identity object. |
identityCookie | array – The configuration of the identity cookie. |
isAdmin | boolean – Whether the current user is an admin. |
isGuest | boolean – Whether the current user is a guest. |
loginUrl | string, array, null – The URL for login when loginRequired() is called. |
remainingSessionTime | integer – The seconds left in the session, or -1 if their session will expire when their HTTP session ends. |
rememberedUsername | string, null |
returnUrl | string – The URL that the user should be redirected to after login. |
returnUrlParam | string – The session variable name used to store the value of returnUrl. |
token | string |
tokenParam | string – The session variable name used to store the user session token. |
usernameCookie | array – The configuration of the username cookie. |
authDurationParam
​
- Type
- string
- Default value
'__duration'
- Since
- 3.6.8
The session variable name used to store the duration of the authenticated state.
elevatedSessionTimeout
​
The number of seconds left in the current elevated user session or false if it has been disabled.
elevatedSessionTimeoutParam
​
- Type
- string
- Default value
'__elevated_timeout'
The session variable name used to store the value of the expiration timestamp of the elevated session state.
hasElevatedSession
​
- Type
- boolean
- Default value
null
Whether the user currently has an elevated session
identity
​
- Type
- craft\elements\User, null
- Default value
null
The logged-in user.
isAdmin
​
- Type
- boolean
- Default value
null
- Access
- Read-only
Whether the current user is an admin.
remainingSessionTime
​
- Type
- integer
- Default value
null
- Access
- Read-only
The seconds left in the session, or -1 if their session will expire when their HTTP session ends.
rememberedUsername
​
token
​
- Type
- string
- Default value
null
- Access
- Read-only
- Since
- 3.6.11
tokenParam
​
- Type
- string
- Default value
'__token'
The session variable name used to store the user session token.
usernameCookie
​
- Type
- array
- Default value
null
The configuration of the username cookie.
See also yii\web\Cookie
Public Methods ​
Method | Description |
---|---|
__call() | Calls the named method which is not a class method. |
__clone() | This method is called after the object is created by cloning an existing one. |
__construct() | Constructor. |
__get() | Returns the value of a component property. |
__isset() | Checks if a property is set, i.e. defined and not null. |
__set() | Sets the value of a component property. |
__unset() | Sets a component property to be null. |
attachBehavior() | Attaches a behavior to this component. |
attachBehaviors() | Attaches a list of behaviors to the component. |
behaviors() | Returns a list of behaviors that this component should behave as. |
can() | Checks if the user can perform the operation as specified by the given permission. |
canGetProperty() | Returns a value indicating whether a property can be read. |
canSetProperty() | Returns a value indicating whether a property can be set. |
checkPermission() | Returns whether the current user has a given permission. |
checkRedirectAcceptable() | Checks if the Accept header contains a content type that allows redirection to the login page. |
className() | Returns the fully qualified name of this class. |
destroyDebugPreferencesInSession() | Removes the debug preferences from the session. |
detachBehavior() | Detaches a behavior from the component. |
detachBehaviors() | Detaches all behaviors from the component. |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. |
generateToken() | Generates a new user session token. |
getBehavior() | Returns the named behavior object. |
getBehaviors() | Returns all behaviors attached to this component. |
getElevatedSessionTimeout() | Returns how many seconds are left in the current elevated user session. |
getHasElevatedSession() | Returns whether the user currently has an elevated session. |
getId() | Returns a value that uniquely represents the user. |
getIdentity() | Returns the logged-in user. |
getIsAdmin() | Returns whether the current user is an admin. |
getIsGuest() | Returns a value indicating whether the user is a guest (not authenticated). |
getRemainingSessionTime() | Returns how many seconds are left in the current user session. |
getRememberedUsername() | Returns the username of the account that the browser was last logged in as. |
getReturnUrl() | Returns the URL that the browser should be redirected to after successful login. |
getToken() | Returns the user token from the session. |
guestRequired() | Redirects the user browser away from a guest page. |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. |
hasMethod() | Returns a value indicating whether a method is defined. |
hasProperty() | Returns a value indicating whether a property is defined for this component. |
init() | Initializes the application component. |
login() | Logs in a user. |
loginByAccessToken() | Logs in a user by the given access token. |
loginByUserId() | Logs in a user by their ID. |
loginRequired() | Redirects the user browser to the login page. |
logout() | Logs out the current user. |
off() | Detaches an existing event handler from this component. |
on() | Attaches an event handler to an event. |
removeReturnUrl() | Removes the stored return URL, if there is one. |
saveDebugPreferencesToSession() | Saves the logged-in user’s Debug toolbar preferences to the session. |
sendUsernameCookie() | Sends a username cookie. |
setIdentity() | Sets the user identity object. |
setReturnUrl() | Remembers the URL in the session so that it can be retrieved back later by getReturnUrl(). |
startElevatedSession() | Starts an elevated user session for the current user. |
switchIdentity() | Switches to a new identity for the current user. |
trigger() | Triggers an event. |
checkPermission()
​
Returns whether the current user has a given permission.
Arguments ​
$permissionName
(string) – The name of the permission.
Returns ​
boolean – Whether the current user has the permission.
destroyDebugPreferencesInSession()
​
DEPRECATED
Deprecated in 3.5.0
Removes the debug preferences from the session.
generateToken()
​
- Since
- 3.1.1
Generates a new user session token.
Arguments ​
$userId
(integer)
getElevatedSessionTimeout()
​
Returns how many seconds are left in the current elevated user session.
Returns ​
integer, boolean – The number of seconds left in the current elevated user session or false if it has been disabled.
getHasElevatedSession()
​
Returns whether the user currently has an elevated session.
Returns ​
boolean – Whether the user currently has an elevated session
getIdentity()
​
Returns the logged-in user.
Arguments ​
$autoRenew
Returns ​
craft\elements\User, null –
getIsAdmin()
​
Returns whether the current user is an admin.
Returns ​
boolean – Whether the current user is an admin.
getIsGuest()
​
Returns a value indicating whether the user is a guest (not authenticated).
Returns ​
boolean – Whether the current user is a guest.
Example ​
$isGuest = Craft::$app->user->isGuest;
{% if craft.app.user.isGuest %}
<a href="{{ url(craft.app.config.general.getLoginPath()) }}">
Login
</a>
{% else %}
<a href="{{ url(craft.app.config.general.getLogoutPath()) }}">
Logout
</a>
{% endif %}
getRemainingSessionTime()
​
Returns how many seconds are left in the current user session.
Returns ​
integer – The seconds left in the session, or -1 if their session will expire when their HTTP session ends.
getRememberedUsername()
​
Returns the username of the account that the browser was last logged in as.
Returns ​
Example ​
$username = Craft::$app->user->rememberedUsername;
<form method="post" action="" accept-charset="UTF-8">
{{ csrfInput() }}
{{ actionInput('users/login') }}
{% set username = craft.app.user.rememberedUsername %}
<input type="text" name="loginName" value="{{ username }}">
<input type="password" name="password">
<input type="submit" value="Login">
</form>
getReturnUrl()
​
Returns the URL that the browser should be redirected to after successful login.
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.
Arguments ​
$defaultUrl
(string, array, null) – The default return URL in case it was not set previously. If this is null and the return URL was not set previously, craft\web\Application::$homeUrl will be redirected to. Please refer to setReturnUrl() on accepted format of the URL.
Returns ​
string – The URL that the user should be redirected to after login.
getToken()
​
- Since
- 3.6.11
Returns the user token from the session.
Returns ​
guestRequired()
​
- Since
- 3.4.0
Redirects the user browser away from a guest page.
Returns ​
craft\web\Response – The redirection response
Throws ​
- yii\web\ForbiddenHttpException
if the request doesn’t accept a redirect response
login()
​
Logs in a user.
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 settrue
.
If enableSession is false
:
- the
$duration
parameter will be ignored
Arguments ​
$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 to0
Returns ​
boolean – Whether the user is logged in
loginByUserId()
​
Logs in a user by their ID.
Arguments ​
$userId
(integer) – The user’s ID$duration
(integer) – The number of seconds that the user can remain in logged-in status. Defaults to 0, meaning login till the user closes the browser or the session is manually destroyed. If greater than 0 and enableAutoLogin is true, cookie-based login will be supported. Note that if enableSession is false, this parameter will be ignored.
Returns ​
boolean – Whether the user is logged in
removeReturnUrl()
​
Removes the stored return URL, if there is one.
See also getReturnUrl()View source
saveDebugPreferencesToSession()
​
DEPRECATED
Deprecated in 3.5.0
Saves the logged-in user’s Debug toolbar preferences to the session.
sendUsernameCookie()
​
Sends a username cookie.
This method is used after a user is logged in. It saves the logged-in user's username in a cookie, so that login forms can remember the initial Username value on login forms.
See also afterLogin()View source
Arguments ​
$user
(craft\elements\User)
startElevatedSession()
​
Starts an elevated user session for the current user.
Arguments ​
$password
(string) – The current user’s password
Returns ​
boolean – Whether the password was valid, and the user session has been elevated
Throws ​
- craft\errors\UserLockedException
if the user is locked.
switchIdentity()
​
Switches to a new identity for the current user.
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 login() for more details.
This method is mainly called by login(), logout() and loginByCookie() when the current user needs to be associated with the corresponding identity information.
Arguments ​
$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.
Protected Methods ​
Method | Description |
---|---|
afterLogin() | This method is called after the user is successfully logged in. |
afterLogout() | This method is invoked right after a user is logged out via logout(). |
beforeLogin() | This method is called before logging in a user. |
beforeLogout() | This method is invoked when calling logout() to log out a user. |
getAccessChecker() | Returns the access checker used for checking access. |
getAuthManager() | Returns auth manager associated with the user component. |
getIdentityAndDurationFromCookie() | Determines if an identity cookie has a valid format and contains a valid auth key. |
loginByCookie() | Logs in a user by cookie. |
regenerateCsrfToken() | Regenerates CSRF token |
removeIdentityCookie() | Removes the identity cookie. |
renewAuthStatus() | Updates the authentication status using the information from session and cookie. |
renewIdentityCookie() | Renews the identity cookie. |
sendIdentityCookie() | Sends an identity cookie. |
afterLogin()
​
This method is called after the user is successfully logged in.
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.
Arguments ​
$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()
​
This method is invoked right after a user is logged out via logout().
The default implementation will trigger the EVENT_AFTER_LOGOUT event. If you override this method, make sure you call the parent implementation so that the event is triggered.
Arguments ​
$identity
(yii\web\IdentityInterface) – The user identity information
beforeLogin()
​
This method is called before logging in a user.
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.
Arguments ​
$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.
Returns ​
boolean – Whether the user should continue to be logged in
beforeLogout()
​
This method is invoked when calling logout() to log out a user.
The default implementation will trigger the EVENT_BEFORE_LOGOUT event. If you override this method, make sure you call the parent implementation so that the event is triggered.
Arguments ​
$identity
(yii\web\IdentityInterface) – The user identity information
Returns ​
boolean – Whether the user should continue to be logged out
renewAuthStatus()
​
Updates the authentication status using the information from session and cookie.
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 login by cookie if enableAutoLogin is true.
Constants ​
Constant | Description |
---|---|
EVENT_AFTER_LOGIN | |
EVENT_AFTER_LOGOUT | |
EVENT_BEFORE_LOGIN | |
EVENT_BEFORE_LOGOUT |