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

The User component provides APIs for managing the user authentication status.

An instance of the User component is globally accessible in Craft via craft\base\ApplicationTrait::getUser().

View source

Public Properties

PropertyDescription
$absoluteAuthTimeoutinteger – 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 – The access checker to use for checking access.
$authTimeoutinteger – The number of seconds in which the user will be logged out automatically if he 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, boolean – 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 – The unique identifier for the user.
$idParamstring – The session variable name used to store the value of $id.
$identityyii\web\IdentityInterface, null – The identity object associated with the currently 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 – 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.
$usernameCookiearray – The configuration of the username cookie.

$elevatedSessionTimeout

Type
integer, boolean
Access
Read-only

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

View source

Signature

public integer, boolean getElevatedSessionTimeout ( )

$elevatedSessionTimeoutParam

Type
string

The session variable name used to store the value of the expiration timestamp of the elevated session state.

View source

Signature

public string $elevatedSessionTimeoutParam = '__elevated_timeout'

$hasElevatedSession

Type
boolean
Access
Read-only

Whether the user currently has an elevated session

View source

Signature

public boolean getHasElevatedSession ( )

$isAdmin

Type
boolean
Access
Read-only

Whether the current user is an admin.

View source

Signature

public boolean getIsAdmin ( )

$isGuest

Type
boolean
Access
Read-only

Whether the current user is a guest.

View source

Signature

public boolean getIsGuest ( )

$remainingSessionTime

Type
integer
Access
Read-only

The seconds left in the session, or -1 if their session will expire when their HTTP session ends.

View source

Signature

public integer getRemainingSessionTime ( )

$rememberedUsername

Type
string, null
Access
Read-only

View source

Signature

public string, null getRememberedUsername ( )

$returnUrl

Type
string

The URL that the user should be redirected to after login.

View source

Signature

public string getReturnUrl ( $defaultUrl = null )
public void setReturnUrl ( $url )

$usernameCookie

Type
array

The configuration of the username cookie.

See also yii\web\Cookie

View source

Signature

public array $usernameCookie = null

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 an object property.
__isset()Checks if a property is set, i.e. defined and not null.
__set()Sets value of an object property.
__unset()Sets an object property to 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.
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.
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 identity object associated with the currently 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.
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.
init()Initializes the object.
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.

View source

Arguments

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

Returns

boolean – Whether the current user has the permission.

Signature

public boolean checkPermission ( \craft\web\string $permissionName )

destroyDebugPreferencesInSession()

Removes the debug preferences from the session.

View source

Signature

public void destroyDebugPreferencesInSession ( )

getElevatedSessionTimeout()

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

View source

Returns

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

Signature

public integer, boolean getElevatedSessionTimeout ( )

getHasElevatedSession()

Returns whether the user currently has an elevated session.

View source

Returns

boolean – Whether the user currently has an elevated session

Signature

public boolean getHasElevatedSession ( )

getIsAdmin()

Returns whether the current user is an admin.

View source

Returns

boolean – Whether the current user is an admin.

Signature

public boolean getIsAdmin ( )

getIsGuest()

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

View source

Returns

boolean – Whether the current user is a guest.

Signature

public boolean getIsGuest ( )

Example

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.

Signature

public integer getRemainingSessionTime ( )

getRememberedUsername()

Returns the username of the account that the browser was last logged in as.

View source

Returns

string, null

Signature

public string, null getRememberedUsername ( )

Example

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.

Signature

public string getReturnUrl ( $defaultUrl = null )

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

Signature

public boolean loginByUserId ( \craft\web\int $userId, \craft\web\int $duration = 0 )

removeReturnUrl()

Removes the stored return URL, if there is one.

See also getReturnUrl()View source

Signature

public void removeReturnUrl ( )

saveDebugPreferencesToSession()

Saves the logged-in user’s Debug toolbar preferences to the session.

View source

Signature

public void saveDebugPreferencesToSession ( )

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

Signature

public void sendUsernameCookie ( craft\elements\User $user )

startElevatedSession()

Starts an elevated user session for the current user.

View source

Arguments

  • $password (string) – The current user’s password

Returns

boolean – Whether the password was valid, and the user session has been elevated

Signature

public boolean startElevatedSession ( \craft\web\string $password )

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.
checkRedirectAcceptable()Checks if the Accept header contains a content type that allows redirection to the login page.
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.

Signature

protected void afterLogin ( $identity, $cookieBased, $duration )

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

Signature

protected void afterLogout ( $identity )

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

Signature

protected boolean beforeLogin ( $identity, $cookieBased, $duration )

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

Signature

protected void renewAuthStatus ( )

renewIdentityCookie()

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.

View source

Signature

protected void renewIdentityCookie ( )

Constants

ConstantDescription
EVENT_AFTER_LOGIN
EVENT_AFTER_LOGOUT
EVENT_BEFORE_LOGIN
EVENT_BEFORE_LOGOUT