Skip to content

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.

View source

Public Properties ​

PropertyDescription
absoluteAuthTimeoutinteger, null – The number of seconds in which the user will be logged out automatically regardless of activity.
absoluteAuthTimeoutParamstring – The session variable name used to store the value of absolute expiration timestamp of the authenticated state.
acceptableRedirectTypesarray – MIME types for which this component should redirect to the loginUrl.
accessCheckeryii\rbac\CheckAccessInterface, string, array, null – The access checker object to use for checking access or the application component ID of the access checker.
authDurationParamstring – The session variable name used to store the duration of the authenticated state.
authKeyParamstring – The session variable name used to store authentication key.
authTimeoutinteger, null – The number of seconds in which the user will be logged out automatically if the user remains inactive.
authTimeoutParamstring – The session variable name used to store the value of expiration timestamp of the authenticated state.
autoRenewCookieboolean – Whether to automatically renew the identity cookie each time a page is requested.
behaviorsyii\base\Behavior – List of behaviors attached to this component.
elevatedSessionTimeoutinteger, false – The number of seconds left in the current elevated user session or false if it has been disabled.
elevatedSessionTimeoutParamstring – The session variable name used to store the value of the expiration timestamp of the elevated session state.
enableAutoLoginboolean – Whether to enable cookie-based login.
enableSessionboolean – Whether to use session to persist authentication status across multiple requests.
hasElevatedSessionboolean – Whether the user currently has an elevated session
idstring, integer, null – The unique identifier for the user.
idParamstring – The session variable name used to store the value of id.
identitycraft\elements\User, null – The logged-in user.
identityClassstring – The class name of the identity object.
identityCookiearray – The configuration of the identity cookie.
isAdminboolean – Whether the current user is an admin.
isGuestboolean – Whether the current user is a guest.
loginUrlstring, array, null – The URL for login when loginRequired() is called.
remainingSessionTimeinteger – The seconds left in the session, or -1 if their session will expire when their HTTP session ends.
rememberedUsernamestring, null
returnUrlstring – The URL that the user should be redirected to after login.
returnUrlParamstring – The session variable name used to store the value of returnUrl.
tokenstring, null
tokenParamstring – The session variable name used to store the user session token.
usernameCookiearray – 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.

View source

elevatedSessionTimeout ​

Type
integer, false
Default value
null
Access
Read-only

The number of seconds left in the current elevated user session or false if it has been disabled.

View source

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.

View source

hasElevatedSession ​

Type
boolean
Default value
null

Whether the user currently has an elevated session

View source

identity ​

Type
craft\elements\User, null
Default value
null

The logged-in user.

View source

isAdmin ​

Type
boolean
Default value
null
Access
Read-only

Whether the current user is an admin.

View source

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.

View source

rememberedUsername ​

Type
string, null
Default value
null
Access
Read-only

View source

token ​

Type
string, null
Default value
null
Access
Read-only
Since
3.6.11

View source

tokenParam ​

Type
string
Default value
'__token'

The session variable name used to store the user session token.

View source

usernameCookie ​

Type
array
Default value
null

The configuration of the username cookie.

See also yii\web\Cookie

View source

Public Methods ​

MethodDescription
__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.
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.
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().
switchIdentity()Switches to a new identity for the current user.
trigger()Triggers an event.

checkPermission() ​

Returns whether the current user has a given permission.

View source

Arguments ​

  • $permissionName (string) – The name of the permission.

Returns ​

boolean – Whether the current user has the permission.

generateToken() ​

Since
3.1.1

Generates a new user session token.

View source

Arguments ​

getElevatedSessionTimeout() ​

Returns how many seconds are left in the current elevated user session.

View source

Returns ​

integer, false – 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.

View source

Returns ​

boolean – Whether the user currently has an elevated session

getIdentity() ​

Returns the logged-in user.

View source

Arguments ​

  • $autoRenew

Returns ​

craft\elements\User, null –

getIsAdmin() ​

Returns whether the current user is an admin.

View source

Returns ​

boolean – Whether the current user is an admin.

getIsGuest() ​

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

View source

Returns ​

boolean – Whether the current user is a guest.


Example ​

php
$isGuest = Craft::$app->user->isGuest;
twig
{% 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.

View source

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.

View source

Returns ​

string, null


Example ​

php
$username = Craft::$app->user->rememberedUsername;
twig
<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="Sign in">
</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.

View source

Arguments ​

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.

View source

Returns ​

string, null

guestRequired() ​

Since
3.4.0

Redirects the user browser away from a guest page.

View source

Returns ​

craft\web\Response – The redirection response

Throws ​

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 set true.

If enableSession is false:

  • the $duration parameter will be ignored

View source

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 to 0

Returns ​

boolean – Whether the user is logged in

loginByUserId() ​

Logs in a user by their ID.

View source

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

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 ​

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.

View source

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 ​

MethodDescription
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.

View source

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.

View source

Arguments ​

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.

View source

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.

View source

Arguments ​

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.

View source

Constants ​

ConstantDescription
EVENT_AFTER_LOGIN
EVENT_AFTER_LOGOUT
EVENT_BEFORE_LOGIN
EVENT_BEFORE_LOGOUT