UserSessionService
- Type
- Class
- Namespace
- Craft
- Inherits
- Craft\UserSessionService » CWebUser (opens new window) » CApplicationComponent (opens new window) » CComponent (opens new window)
- 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 (opens new window)
# Public Properties
Property | Description |
---|---|
$absoluteAuthTimeout (opens new window) | integer (opens new window) – Timeout in seconds after which user is logged out regardless of activity. |
$allowAutoLogin (opens new window) | boolean (opens new window) – Whether to enable cookie-based login. |
$authTimeout (opens new window) | integer (opens new window) – Timeout in seconds after which user is logged out if inactive. |
$autoRenewCookie (opens new window) | boolean (opens new window) – Whether to automatically renew the identity cookie each time a page is requested. |
$autoUpdateFlash (opens new window) | boolean (opens new window) – Whether to automatically update the validity of flash messages. |
$behaviors (opens new window) | array (opens new window) – The behaviors that should be attached to this component. |
$guestName (opens new window) | string (opens new window) – The name for a guest user. |
$identityCookie (opens new window) | array (opens new window) – The property values (in name-value pairs) used to initialize the identity cookie. |
$loginRequiredAjaxResponse (opens new window) | string (opens new window) – Value that will be echoed in case that user session has expired during an ajax call. |
$loginUrl (opens new window) | string (opens new window), array (opens new window) – The URL for login. |
# Public Methods
Method | Description |
---|---|
__call() (opens new window) | Calls the named method which is not a class method. |
__get() (opens new window) | PHP magic method. |
__isset() (opens new window) | PHP magic method. |
__set() (opens new window) | PHP magic method. |
__unset() (opens new window) | 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() (opens new window) | Returns the named behavior object. |
attachBehavior() (opens new window) | Attaches a behavior to this component. |
attachBehaviors() (opens new window) | Attaches a list of behaviors to the component. |
attachEventHandler() (opens new window) | Attaches an event handler to an event. |
authorize() | Authorizes the user to perform an action for the duration of the session. |
canGetProperty() (opens new window) | Determines whether a property can be read. |
canSetProperty() (opens new window) | Determines whether a property can be set. |
checkAccess() (opens new window) | 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() (opens new window) | Detaches a behavior from the component. |
detachBehaviors() (opens new window) | Detaches all behaviors from the component. |
detachEventHandler() (opens new window) | Detaches an existing event handler. |
disableBehavior() (opens new window) | Disables an attached behavior. |
disableBehaviors() (opens new window) | Disables all behaviors attached to this component. |
enableBehavior() (opens new window) | Enables an attached behavior. |
enableBehaviors() (opens new window) | Enables all behaviors attached to this component. |
evaluateExpression() (opens new window) | 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() (opens new window) | Returns the list of attached event handlers for an event. |
getFlash() (opens new window) | Returns a flash message. |
getFlashes() | Overriding Yii's implementation to make sure that session has been started before calling. |
getId() (opens new window) | 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() (opens new window) | 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() (opens new window) | 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() (opens new window) | |
getUser() | Returns the currently logged-in user. |
hasElevatedSession() | Returns whether the user current has an elevated session. |
hasEvent() (opens new window) | Determines whether an event is defined. |
hasEventHandler() (opens new window) | Checks whether the named event has attached handlers. |
hasFlash() (opens new window) | |
hasProperty() (opens new window) | 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() (opens new window) | 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() (opens new window) | 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() (opens new window) | Stores a flash message. |
setId() (opens new window) | |
setName() (opens new window) | Sets the unique identifier for the user (e.g. username). |
setNotice() | Stores a notice in the user’s flash data. |
setReturnUrl() (opens new window) | |
setState() | Overriding Yii's implementation to make sure that session has been started before calling. |
setStateKeyPrefix() (opens new window) | |
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 (opens new window)
Arguments
$js
(string (opens new window)) – The Javascript code.
Returns
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 (opens new window)
Arguments
$resource
(string (opens new window)) – The resource path to the JS file.
Returns
Signature
public null addJsResourceFlash ( $resource )
# authorize()
Authorizes the user to perform an action for the duration of the session.
View source (opens new window)
Arguments
$action
(string (opens new window))
Returns
Signature
public null authorize ( $action )
# checkAuthorization()
Returns whether the user is authorized to perform an action.
View source (opens new window)
Arguments
$action
(string (opens new window))
Returns
Signature
public boolean checkAuthorization ( $action )
# checkPermission()
Returns whether the current user has a given permission.
View source (opens new window)
Arguments
$permissionName
(string (opens new window)) – The name of the permission.
Returns
boolean (opens new window) – 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 (opens new window)
Returns
Signature
public null clearStates ( )
# deauthorize()
Deauthorizes the user from performing an action.
View source (opens new window)
Arguments
$action
(string (opens new window))
Returns
Signature
public null deauthorize ( $action )
# deleteStateCookie()
Deletes a cookie on the browser that was stored for the current application state.
View source (opens new window)
Arguments
$name
(string (opens new window)) – The name of the cookie.
Returns
Signature
public null deleteStateCookie ( $name )
# getAuthTimeout()
Returns how many seconds are left in the current user session.
View source (opens new window)
Returns
integer (opens new window) – 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 (opens new window)
Returns
integer (opens new window), boolean (opens new window) – 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 (opens new window)
Arguments
$delete
(boolean (opens new window))
Returns
array (opens new window), void
Signature
public array, void getFlashes ( $delete = true )
# getIdentityCookie()
Returns the current user identity cookie, if there is one.
View source (opens new window)
Returns
Craft\HttpCookie, null (opens new window) – 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 (opens new window)
Arguments
$cookie
Returns
array (opens new window), null (opens new window) – The user identity cookie’s data, or null
if it didn’t exist.
Signature
public array, null getIdentityCookieValue ( Craft\HttpCookie $cookie = null )
# getIsGuest()
Signature
public boolean getIsGuest ( )
# getJsFlashes()
Returns the stored JS flashes.
View source (opens new window)
Arguments
$delete
(boolean (opens new window)) – Whether to delete the stored flashes. Defaults totrue
.
Returns
array (opens new window) – The stored JS flashes.
Signature
public array getJsFlashes ( $delete = true )
# getJsResourceFlashes()
Returns the stored JS resource flashes.
View source (opens new window)
Arguments
$delete
(boolean (opens new window)) – Whether to delete the stored flashes. Defaults totrue
.
Returns
array (opens new window) – The stored JS resource flashes.
Signature
public array getJsResourceFlashes ( $delete = true )
# getLoginErrorCode()
Returns the login error code from the user identity.
View source (opens new window)
Returns
integer (opens new window), null (opens new window) – 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 (opens new window)
Arguments
$errorCode
– The login error code.$loginName
– The user’s username or email.
Returns
string (opens new window) – 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 (opens new window)
Returns
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 (opens new window)
Arguments
$defaultUrl
(string (opens new window), null (opens new window)) – The default URL that should be returned if no return URL was stored.$delete
(boolean (opens new window)) – Whether the stored return URL should be deleted after it was fetched.
Returns
string (opens new window), null (opens new window) – 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 (opens new window)
Arguments
$key
(string (opens new window))$defaultValue
(null (opens new window))
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 (opens new window)
Arguments
$name
(string (opens new window)) – The cookie name.
Returns
Craft\HttpCookie, null (opens new window) – 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 (opens new window)
Arguments
$cookie
(Craft\HttpCookie, string (opens new window)) – The cookie, or the name of the cookie.
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 (opens new window)
Returns
Craft\UserModel, null (opens new window) – 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 (opens new window)
Returns
boolean (opens new window) – 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 (opens new window)
Arguments
$key
(string (opens new window))
Returns
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 (opens new window)
Arguments
$userId
(integer (opens new window)) – The user’s ID.
Returns
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 (opens new window)
Returns
Signature
public null init ( )
# isAdmin()
Returns whether the current user is an admin.
View source (opens new window)
Returns
boolean (opens new window) – Whether the current user is an admin.
Signature
public boolean isAdmin ( )
# isGuest()
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 (opens new window)
Returns
boolean (opens new window) – 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 (opens new window)
config setting. Otherwise it will last for the duration specified by the
userSessionDuration (opens new window)
config setting.
View source (opens new window)
Arguments
$username
(string (opens new window)) – The user’s username.$password
(string (opens new window)) – The user’s submitted password.$rememberMe
(boolean (opens new window)) – Whether the user should be remembered.
Returns
boolean (opens new window) – 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 (opens new window)
Arguments
$userId
(integer (opens new window)) – The user ID of the person to log in.$rememberMe
(boolean (opens new window)) – Whether the user should be remembered.$setUsernameCookie
(boolean (opens new window)) – Whether to set the username cookie or not.
Returns
Throws
Signature
public boolean loginByUserId ( $userId, $rememberMe = false, $setUsernameCookie = false )
# loginRequired()
Signature
public null loginRequired ( )
# onBeforeAuthenticate()
Fires an 'onBeforeAuthenticate' event.
View source (opens new window)
Arguments
$event
(Craft\Event)
Returns
Signature
public null onBeforeAuthenticate ( Craft\Event $event )
# onBeforeLogin()
Fires an 'onBeforeLogin' event.
View source (opens new window)
Arguments
$event
(Craft\Event)
Returns
Signature
public null onBeforeLogin ( Craft\Event $event )
# onBeforeLogout()
Signature
public void onBeforeLogout ( Craft\Event $event )
# onLogin()
Signature
public null onLogin ( Craft\Event $event )
# onLogout()
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 (opens new window)
Arguments
$username
(string (opens new window)) – The username to save in the cookie.
Returns
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 (opens new window)
Returns
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 (opens new window)
Arguments
$action
(string (opens new window)) – The name of the action to check.
Returns
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 (opens new window)
Returns
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 (opens new window)
Arguments
$permissionName
(string (opens new window)) – The name of the permission.
Returns
Throws
Signature
public null requirePermission ( $permissionName )
# saveCookie()
Sets a cookie on the browser.
View source (opens new window)
Arguments
$name
(string (opens new window)) – The name of the cookie.$data
(mixed
) – The data that should be stored on the cookie.$duration
(integer (opens new window)) – 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 (opens new window)
Arguments
$message
(string (opens new window)) – The message.
Returns
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 (opens new window)
Arguments
$message
(string (opens new window)) – The message.
Returns
Signature
public null setNotice ( $message )
# setState()
Overriding Yii's implementation to make sure that session has been started before calling.
View source (opens new window)
Arguments
$key
(string (opens new window))$value
(mixed
)$defaultValue
(null (opens new window))
Returns
Signature
public null setState ( $key, $value, $defaultValue = null )
# shouldExtendSession()
Returns whether the request should extend the current session timeout or not.
View source (opens new window)
Returns
Signature
public boolean shouldExtendSession ( )
# startElevatedSession()
Starts an elevated user session for the current user.
View source (opens new window)
Arguments
$password
(string (opens new window)) – The current user’s password
Returns
boolean (opens new window) – 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 (opens new window)
Arguments
$user
(Craft\UserModel)$sessionToken
(string (opens new window))
Returns
string (opens new window) – 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 (opens new window)
Returns
boolean (opens new window) – Whether the current user session was just restored from a cookie.
Signature
public boolean wasSessionRestoredFromCookie ( )
# Protected Methods
Method | Description |
---|---|
afterLogin() | Called after a user is logged in. |
afterLogout() | Fires an 'onLogout' event after a user has been logged out. |
beforeLogin() (opens new window) | This method is called before logging in a user. |
beforeLogout() | Called before a user is logged out. |
changeIdentity() (opens new window) | Changes the current user with the specified identity information. |
createIdentityCookie() (opens new window) | Creates a cookie to store identity information. |
loadIdentityStates() (opens new window) | 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() (opens new window) | Retrieves identity states from persistent storage and saves them as an array. |
saveToCookie() (opens new window) | Saves necessary user data into a cookie. |
updateAuthStatus() | Updates the authentication status according to {@link authTimeout}. |
updateFlash() (opens new window) | Updates the internal counters for flash messages. |
# afterLogin()
Signature
protected null afterLogin ( )
# afterLogout()
Signature
protected null afterLogout ( )
# beforeLogout()
Called before a user is logged out.
View source (opens new window)
Returns
boolean (opens new window) – 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 (opens new window) or rememberedUserSessionDuration (opens new window) config setting, depending on whether Remember Me was checked when they logged in.
View source (opens new window)
Returns
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 (opens new window)
Returns
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 (opens new window) config setting, and it won't update the timeout state if the 'dontExtendSession' param is set.
View source (opens new window)
Returns
Signature
protected null updateAuthStatus ( )
# Constants
Constant | Description |
---|---|
AUTH_ABSOLUTE_TIMEOUT_VAR | |
AUTH_ACCESS_VAR | |
AUTH_TIMEOUT_VAR | |
ELEVATED_SESSION_TIMEOUT_VAR | |
FLASH_COUNTERS | |
FLASH_KEY_PREFIX | |
STATES_VAR | |
USER_IMPERSONATE_KEY |