UserSessionService

Type
Class
Namespace
Craft
Inherits
Craft\UserSessionService » CWebUser » CApplicationComponent » CComponent
Implements
IApplicationComponent, IWebUser
Since
1.0

UserSessionService provides APIs for managing user sessions.

An instance of UserSessionService is globally accessible in Craft via {@link WebApp::userSession craft()->userSession}.

See also http://craftcms.com

View source

Public Properties

PropertyDescription
$absoluteAuthTimeoutinteger – Timeout in seconds after which user is logged out regardless of activity.
$allowAutoLoginboolean – Whether to enable cookie-based login.
$authTimeoutinteger – Timeout in seconds after which user is logged out if inactive.
$autoRenewCookieboolean – Whether to automatically renew the identity cookie each time a page is requested.
$autoUpdateFlashboolean – Whether to automatically update the validity of flash messages.
$behaviorsarray – The behaviors that should be attached to this component.
$guestNamestring – The name for a guest user.
$identityCookiearray – The property values (in name-value pairs) used to initialize the identity cookie.
$loginRequiredAjaxResponsestring – Value that will be echoed in case that user session has expired during an ajax call.
$loginUrlstring, array – The URL for login.

Public Methods

MethodDescription
__call()Calls the named method which is not a class method.
__get()PHP magic method.
__isset()PHP magic method.
__set()PHP magic method.
__unset()PHP magic method.
addJsFlash()Stores JS in the user’s flash data.
addJsResourceFlash()Stores a JS file from resources/ in the user’s flash data.
asa()Returns the named behavior object.
attachBehavior()Attaches a behavior to this component.
attachBehaviors()Attaches a list of behaviors to the component.
attachEventHandler()Attaches an event handler to an event.
authorize()Authorizes the user to perform an action for the duration of the session.
canGetProperty()Determines whether a property can be read.
canSetProperty()Determines whether a property can be set.
checkAccess()Performs access check for this user.
checkAuthorization()Returns whether the user is authorized to perform an action.
checkPermission()Returns whether the current user has a given permission.
clearStates()Overriding Yii's implementation to make sure that session has been started before calling.
deauthorize()Deauthorizes the user from performing an action.
deleteStateCookie()Deletes a cookie on the browser that was stored for the current application state.
detachBehavior()Detaches a behavior from the component.
detachBehaviors()Detaches all behaviors from the component.
detachEventHandler()Detaches an existing event handler.
disableBehavior()Disables an attached behavior.
disableBehaviors()Disables all behaviors attached to this component.
enableBehavior()Enables an attached behavior.
enableBehaviors()Enables all behaviors attached to this component.
evaluateExpression()Evaluates a PHP expression or callback under the context of this component.
getAuthTimeout()Returns how many seconds are left in the current user session.
getElevatedSessionTimeout()Returns how many seconds are left in the current elevated user session.
getEventHandlers()Returns the list of attached event handlers for an event.
getFlash()Returns a flash message.
getFlashes()Overriding Yii's implementation to make sure that session has been started before calling.
getId()Returns a value that uniquely represents the user.
getIdentityCookie()Returns the current user identity cookie, if there is one.
getIdentityCookieValue()Returns the current user identity cookie’s value, if there is one.
getIsGuest()Alias of {@link isGuest()}.
getIsInitialized()Checks if this application component has been initialized.
getJsFlashes()Returns the stored JS flashes.
getJsResourceFlashes()Returns the stored JS resource flashes.
getLoginErrorCode()Returns the login error code from the user identity.
getLoginErrorMessage()Returns a login error message by a given error code.
getName()Returns the unique identifier for the user (e.g. username).
getRememberedUsername()Returns the username of the account that the browser was last logged in as.
getReturnUrl()Returns the URL the user was trying to access before getting redirected to the login page via {@link requireLogin()}.
getState()Overriding Yii's implementation to make sure that session has been started before calling.
getStateCookie()Returns a cookie that was stored for the current application state.
getStateCookieValue()Returns the value of a cookie by its name, ensuring that the data hasn’t been tampered with.
getStateKeyPrefix()
getUser()Returns the currently logged-in user.
hasElevatedSession()Returns whether the user current has an elevated session.
hasEvent()Determines whether an event is defined.
hasEventHandler()Checks whether the named event has attached handlers.
hasFlash()
hasProperty()Determines whether a property is defined.
hasState()Overriding Yii's implementation to make sure that session has been started before calling.
impersonate()This method has been deprecated. Use {@link UserSessionService::loginByUserId()} instead.
init()Initializes the application component.
isAdmin()Returns whether the current user is an admin.
isGuest()Alias of {@link getIsGuest()}.
isLoggedIn()Returns whether the current user is logged in.
login()Logs a user in.
loginByUserId()Logs a user in by their user ID.
loginRequired()Alias of {@link requireLogin()}.
logout()Logs out the current user.
onBeforeAuthenticate()Fires an 'onBeforeAuthenticate' event.
onBeforeLogin()Fires an 'onBeforeLogin' event.
onBeforeLogout()Fires an 'onBeforeLogout' event.
onLogin()Fires an 'onLogin' event.
onLogout()Fires an 'onLogout' event.
processUsernameCookie()If the 'rememberUsernameDuration' config setting is set, will save a cookie with the given username for that duration. Otherwise, will delete any existing username cookie.
raiseEvent()Raises an event.
requireAdmin()Checks whether the current user is an admin, and ends the request with a 403 error if they aren’t.
requireAuthorization()Checks whether the current user can perform a given action, and ends the request with a 403 error if they don’t.
requireLogin()Checks whether the current user is logged in, and redirects them to the Login page if they aren’t.
requirePermission()Checks whether the current user has a given permission, and ends the request with a 403 error if they don’t.
saveCookie()Sets a cookie on the browser.
setError()Stores an error message in the user’s flash data.
setFlash()Stores a flash message.
setId()
setName()Sets the unique identifier for the user (e.g. username).
setNotice()Stores a notice in the user’s flash data.
setReturnUrl()
setState()Overriding Yii's implementation to make sure that session has been started before calling.
setStateKeyPrefix()
shouldExtendSession()Returns whether the request should extend the current session timeout or not.
startElevatedSession()Starts an elevated user session for the current user.
storeSessionToken()Saves a new session record for a given user.
wasSessionRestoredFromCookie()Returns whether the current user session was just restored from a cookie.

addJsFlash()

Stores JS in the user’s flash data. The Javascript code will be stored on the user session, and can be retrieved by calling {@link getJsFlashes()} or {@link TemplatesService::getFootHtml()}.

View source

Arguments

  • $js (string) – The Javascript code.

Returns

null

Signature

public null addJsFlash ( $js )

addJsResourceFlash()

Stores a JS file from resources/ in the user’s flash data. The file will be stored on the user session, and can be retrieved by calling {@link getJsResourceFlashes()} or {@link TemplatesService::getFootHtml()}.

View source

Arguments

  • $resource (string) – The resource path to the JS file.

Returns

null

Signature

public null addJsResourceFlash ( $resource )

authorize()

Authorizes the user to perform an action for the duration of the session.

View source

Arguments

Returns

null

Signature

public null authorize ( $action )

checkAuthorization()

Returns whether the user is authorized to perform an action.

View source

Arguments

Returns

boolean

Signature

public boolean checkAuthorization ( $action )

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 ( $permissionName )

clearStates()

Overriding Yii's implementation to make sure that session has been started before calling.

View source

Returns

null

Signature

public null clearStates ( )

deauthorize()

Deauthorizes the user from performing an action.

View source

Arguments

Returns

null

Signature

public null deauthorize ( $action )

deleteStateCookie()

Deletes a cookie on the browser that was stored for the current application state.

View source

Arguments

  • $name (string) – The name of the cookie.

Returns

null

Signature

public null deleteStateCookie ( $name )

getAuthTimeout()

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 getAuthTimeout ( )

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 ( )

getFlashes()

Overriding Yii's implementation to make sure that session has been started before calling.

View source

Arguments

Returns

array, void

Signature

public array, void getFlashes ( $delete = true )

getIdentityCookie()

Returns the current user identity cookie, if there is one.

View source

Returns

Craft\HttpCookie, null – The user identity cookie.

Signature

public Craft\HttpCookie, null getIdentityCookie ( )

getIdentityCookieValue()

Returns the current user identity cookie’s value, if there is one.

View source

Arguments

  • $cookie

Returns

array, null – The user identity cookie’s data, or null if it didn’t exist.

Signature

public array, null getIdentityCookieValue ( Craft\HttpCookie $cookie = null )

getIsGuest()

Alias of {@link isGuest()}.

View source

Returns

boolean

Signature

public boolean getIsGuest ( )

getJsFlashes()

Returns the stored JS flashes.

View source

Arguments

  • $delete (boolean) – Whether to delete the stored flashes. Defaults to true.

Returns

array – The stored JS flashes.

Signature

public array getJsFlashes ( $delete = true )

getJsResourceFlashes()

Returns the stored JS resource flashes.

View source

Arguments

  • $delete (boolean) – Whether to delete the stored flashes. Defaults to true.

Returns

array – The stored JS resource flashes.

Signature

public array getJsResourceFlashes ( $delete = true )

getLoginErrorCode()

Returns the login error code from the user identity.

View source

Returns

integer, null – The login error code, or null if there isn’t one.

Signature

public integer, null getLoginErrorCode ( )

getLoginErrorMessage()

Returns a login error message by a given error code.

View source

Arguments

  • $errorCode – The login error code.
  • $loginName – The user’s username or email.

Returns

string – The login error message.

Signature

public string getLoginErrorMessage ( $errorCode, $loginName )

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 ( )

getReturnUrl()

Returns the URL the user was trying to access before getting redirected to the login page via {@link requireLogin()}.

View source

Arguments

  • $defaultUrl (string, null) – The default URL that should be returned if no return URL was stored.
  • $delete (boolean) – Whether the stored return URL should be deleted after it was fetched.

Returns

string, null – The return URL, or $defaultUrl.

Signature

public string, null getReturnUrl ( $defaultUrl = null, $delete = false )

getState()

Overriding Yii's implementation to make sure that session has been started before calling.

View source

Arguments

Returns

mixed, void

Signature

public mixed, void getState ( $key, $defaultValue = null )

getStateCookie()

Returns a cookie that was stored for the current application state.

View source

Arguments

  • $name (string) – The cookie name.

Returns

Craft\HttpCookie, null – The cookie, or null if it didn’t exist.

Signature

public Craft\HttpCookie, null getStateCookie ( $name )

getStateCookieValue()

Returns the value of a cookie by its name, ensuring that the data hasn’t been tampered with.

View source

Arguments

Returns

mixed – The value of the cookie if it exists and hasn’t been tampered with, or null.

Signature

public mixed getStateCookieValue ( $cookie )

getUser()

Returns the currently logged-in user.

View source

Returns

Craft\UserModel, null – The currently logged-in user, or null.

Signature

public Craft\UserModel, null getUser ( )

hasElevatedSession()

Returns whether the user current has an elevated session.

View source

Returns

boolean – Whether the user has an elevated session

Signature

public boolean hasElevatedSession ( )

hasState()

Overriding Yii's implementation to make sure that session has been started before calling.

View source

Arguments

Returns

boolean, void

Signature

public boolean, void hasState ( $key )

impersonate()

DEPRECATED

Deprecated Deprecated in 2.3. Use {@link UserSessionService::loginByUserId()} instead.

This method has been deprecated. Use {@link UserSessionService::loginByUserId()} instead.

View source

Arguments

  • $userId (integer) – The user’s ID.

Returns

null

Signature

public null impersonate ( $userId )

init()

Initializes the application component. This method will determine how long user sessions are configured to last, and whether the current request has requested to not extend the current user session, before calling {@link \CWebUser::init()}.

View source

Returns

null

Signature

public null init ( )

isAdmin()

Returns whether the current user is an admin.

View source

Returns

boolean – Whether the current user is an admin.

Signature

public boolean isAdmin ( )

isGuest()

Alias of {@link getIsGuest()}.

View source

Returns

boolean

Signature

public boolean isGuest ( )

isLoggedIn()

Returns whether the current user is logged in. The result will always just be the opposite of whatever {@link getIsGuest()} returns.

View source

Returns

boolean – Whether the current user is logged in.

Signature

public boolean isLoggedIn ( )

login()

Logs a user in. If $rememberMe is set to true, the user will be logged in for the duration specified by the rememberedUserSessionDuration config setting. Otherwise it will last for the duration specified by the userSessionDuration config setting.

View source

Arguments

  • $username (string) – The user’s username.
  • $password (string) – The user’s submitted password.
  • $rememberMe (boolean) – Whether the user should be remembered.

Returns

boolean – Whether the user was logged in successfully.

Throws

Signature

public boolean login ( $username, $password, $rememberMe = false )

loginByUserId()

Logs a user in by their user ID. This method doesn’t have any sort of credential verification, so use it at your own peril.

View source

Arguments

  • $userId (integer) – The user ID of the person to log in.
  • $rememberMe (boolean) – Whether the user should be remembered.
  • $setUsernameCookie (boolean) – Whether to set the username cookie or not.

Returns

boolean

Throws

Signature

public boolean loginByUserId ( $userId, $rememberMe = false, $setUsernameCookie = false )

loginRequired()

Alias of {@link requireLogin()}.

View source

Returns

null

Signature

public null loginRequired ( )

onBeforeAuthenticate()

Fires an 'onBeforeAuthenticate' event.

View source

Arguments

Returns

null

Signature

public null onBeforeAuthenticate ( Craft\Event $event )

onBeforeLogin()

Fires an 'onBeforeLogin' event.

View source

Arguments

Returns

null

Signature

public null onBeforeLogin ( Craft\Event $event )

onBeforeLogout()

Fires an 'onBeforeLogout' event.

View source

Arguments

Signature

public void onBeforeLogout ( Craft\Event $event )

onLogin()

Fires an 'onLogin' event.

View source

Arguments

Returns

null

Signature

public null onLogin ( Craft\Event $event )

onLogout()

Fires an 'onLogout' event.

View source

Arguments

Signature

public void onLogout ( Craft\Event $event )

processUsernameCookie()

If the 'rememberUsernameDuration' config setting is set, will save a cookie with the given username for that duration. Otherwise, will delete any existing username cookie.

View source

Arguments

  • $username (string) – The username to save in the cookie.

Returns

null

Signature

public null processUsernameCookie ( $username )

requireAdmin()

Checks whether the current user is an admin, and ends the request with a 403 error if they aren’t.

View source

Returns

null

Throws

Signature

public null requireAdmin ( )

requireAuthorization()

Checks whether the current user can perform a given action, and ends the request with a 403 error if they don’t.

View source

Arguments

  • $action (string) – The name of the action to check.

Returns

null

Throws

Signature

public null requireAuthorization ( $action )

requireLogin()

Checks whether the current user is logged in, and redirects them to the Login page if they aren’t. The current request’s URL will be stored on the user’s session before they get redirected, and Craft will automatically redirect them back to the original URL after they’ve logged in.

View source

Returns

null

Throws

Signature

public null requireLogin ( )

requirePermission()

Checks whether the current user has a given permission, and ends the request with a 403 error if they don’t.

View source

Arguments

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

Returns

null

Throws

Signature

public null requirePermission ( $permissionName )

saveCookie()

Sets a cookie on the browser.

View source

Arguments

  • $name (string) – The name of the cookie.
  • $data (mixed) – The data that should be stored on the cookie.
  • $duration (integer) – The duration that the cookie should be stored for, in seconds.

Returns

Craft\HttpCookie – The cookie.

Signature

public Craft\HttpCookie saveCookie ( $name, $data, $duration = 0 )

setError()

Stores an error message in the user’s flash data. The message will be stored on the user session, and can be retrieved by calling {@link getFlash() getFlash('error')} or {@link getFlashes()}.

Only one flash error message can be stored at a time.

View source

Arguments

  • $message (string) – The message.

Returns

null

Signature

public null setError ( $message )

setNotice()

Stores a notice in the user’s flash data. The message will be stored on the user session, and can be retrieved by calling {@link getFlash() getFlash('notice')} or {@link getFlashes()}.

Only one flash notice can be stored at a time.

View source

Arguments

  • $message (string) – The message.

Returns

null

Signature

public null setNotice ( $message )

setState()

Overriding Yii's implementation to make sure that session has been started before calling.

View source

Arguments

Returns

null

Signature

public null setState ( $key, $value, $defaultValue = null )

shouldExtendSession()

Returns whether the request should extend the current session timeout or not.

View source

Returns

boolean

Signature

public boolean shouldExtendSession ( )

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 ( $password )

storeSessionToken()

Saves a new session record for a given user.

View source

Arguments

Returns

string – The session's UID.

Signature

public string storeSessionToken ( Craft\UserModel $user, $sessionToken )

wasSessionRestoredFromCookie()

Returns whether the current user session was just restored from a cookie. This happens when a user with an active session closes their browser, and then re-opens it before their session is supposed to expire.

View source

Returns

boolean – Whether the current user session was just restored from a cookie.

Signature

public boolean wasSessionRestoredFromCookie ( )

Protected Methods

MethodDescription
afterLogin()Called after a user is logged in.
afterLogout()Fires an 'onLogout' event after a user has been logged out.
beforeLogin()This method is called before logging in a user.
beforeLogout()Called before a user is logged out.
changeIdentity()Changes the current user with the specified identity information.
createIdentityCookie()Creates a cookie to store identity information.
loadIdentityStates()Loads identity states from an array and saves them to persistent storage.
renewCookie()Renews the user’s identity cookie.
restoreFromCookie()Restores a user session from the identity cookie.
saveIdentityStates()Retrieves identity states from persistent storage and saves them as an array.
saveToCookie()Saves necessary user data into a cookie.
updateAuthStatus()Updates the authentication status according to {@link authTimeout}.
updateFlash()Updates the internal counters for flash messages.

afterLogin()

Called after a user is logged in.

View source

Returns

null

Signature

protected null afterLogin ( )

afterLogout()

Fires an 'onLogout' event after a user has been logged out.

View source

Returns

null

Signature

protected null afterLogout ( )

beforeLogout()

Called before a user is logged out.

View source

Returns

boolean – So true.

Signature

protected boolean beforeLogout ( )

renewCookie()

Renews the user’s identity cookie. This function extends the identity cookie's expiration time based on either the userSessionDuration or rememberedUserSessionDuration config setting, depending on whether Remember Me was checked when they logged in.

View source

Returns

null

Signature

protected null renewCookie ( )

restoreFromCookie()

Restores a user session from the identity cookie. This method is used when automatic login ({@link allowAutoLogin}) is enabled. The user identity information is recovered from cookie.

View source

Returns

null

Signature

protected null restoreFromCookie ( )

updateAuthStatus()

Updates the authentication status according to {@link authTimeout}. Based on the parts of {@link \CWebUser::updateAuthStatus()} that are relevant to Craft, but this version also enforces the requireUserAgentAndIpForSession config setting, and it won't update the timeout state if the 'dontExtendSession' param is set.

View source

Returns

null

Signature

protected null updateAuthStatus ( )

Constants

ConstantDescription
AUTH_ABSOLUTE_TIMEOUT_VAR
AUTH_ACCESS_VAR
AUTH_TIMEOUT_VAR
ELEVATED_SESSION_TIMEOUT_VAR
FLASH_COUNTERS
FLASH_KEY_PREFIX
STATES_VAR
USER_IMPERSONATE_KEY