HumHub Documentation (unofficial)

User extends Component
in package

User is the class for the `user` application component that manages the user authentication status.

You may use [[isGuest]] to determine whether the current user is a guest or not. If the user is a guest, the [[identity]] property would return null. Otherwise, it would be an instance of [[IdentityInterface]].

You may call various methods to change the user authentication status:

  • [[login()]]: sets the specified identity and remembers the authentication status in session and cookie;
  • [[logout()]]: marks the user as a guest and clears the relevant information from session and cookie;
  • [[setIdentity()]]: changes the user identity without touching session or cookie (this is best used in stateless RESTful API implementation).

Note that User only maintains the user authentication status. It does NOT handle how to authenticate a user. The logic of how to authenticate a user should be done in the class implementing [[IdentityInterface]]. You are also required to set [[identityClass]] with the name of this class.

User is configured as an application component in [[\yii\web\Application]] by default. You can access that instance via Yii::$app->user.

You can modify its configuration by adding an array to your application config under components as it is shown in the following example:

'user' => [
    'identityClass' => 'app\models\User', // User must implement the IdentityInterface
    'enableAutoLogin' => true,
    // 'loginUrl' => ['user/login'],
    // ...
]
Tags
author

Qiang Xue qiang.xue@gmail.com

since
2.0

Table of Contents

Constants

EVENT_AFTER_LOGIN  = 'afterLogin'
EVENT_AFTER_LOGOUT  = 'afterLogout'
EVENT_BEFORE_LOGIN  = 'beforeLogin'
EVENT_BEFORE_LOGOUT  = 'beforeLogout'

Properties

$absoluteAuthTimeout  : int|null
$absoluteAuthTimeoutParam  : string
$acceptableRedirectTypes  : array<string|int, mixed>
$accessChecker  : CheckAccessInterface|string|array<string|int, mixed>|null
$authKeyParam  : string
$authTimeout  : int|null
$authTimeoutParam  : string
$autoRenewCookie  : bool
$behaviors  : array<string|int, Behavior>
$enableAutoLogin  : bool
$enableSession  : bool
$id  : string|int|null
$identity  : IdentityInterface|null
$identityClass  : string
$identityCookie  : array<string|int, mixed>
$idParam  : string
$isGuest  : bool
$loginUrl  : string|array<string|int, mixed>|null
$returnUrl  : string
$returnUrlParam  : string
$_access  : mixed
$_behaviors  : array<string|int, Behavior>|null
$_events  : array<string|int, mixed>
$_eventWildcards  : array<string|int, mixed>
$_identity  : mixed

Methods

__call()  : mixed
Calls the named method which is not a class method.
__clone()  : mixed
This method is called after the object is created by cloning an existing one.
__construct()  : mixed
Constructor.
__get()  : mixed
Returns the value of a component property.
__isset()  : bool
Checks if a property is set, i.e. defined and not null.
__set()  : mixed
Sets the value of a component property.
__unset()  : mixed
Sets a component property to be null.
attachBehavior()  : Behavior
Attaches a behavior to this component.
attachBehaviors()  : mixed
Attaches a list of behaviors to the component.
behaviors()  : array<string|int, mixed>
Returns a list of behaviors that this component should behave as.
can()  : bool
Checks if the user can perform the operation as specified by the given permission.
canGetProperty()  : bool
Returns a value indicating whether a property can be read.
canSetProperty()  : bool
Returns a value indicating whether a property can be set.
checkRedirectAcceptable()  : bool
Checks if the `Accept` header contains a content type that allows redirection to the login page.
className()  : string
Returns the fully qualified name of this class.
detachBehavior()  : Behavior|null
Detaches a behavior from the component.
detachBehaviors()  : mixed
Detaches all behaviors from the component.
ensureBehaviors()  : mixed
Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.
getBehavior()  : Behavior|null
Returns the named behavior object.
getBehaviors()  : array<string|int, Behavior>
Returns all behaviors attached to this component.
getId()  : string|int|null
Returns a value that uniquely represents the user.
getIdentity()  : IdentityInterface|null
Returns the identity object associated with the currently logged-in user.
getIsGuest()  : bool
Returns a value indicating whether the user is a guest (not authenticated).
getReturnUrl()  : string
Returns the URL that the browser should be redirected to after successful login.
hasEventHandlers()  : bool
Returns a value indicating whether there is any handler attached to the named event.
hasMethod()  : bool
Returns a value indicating whether a method is defined.
hasProperty()  : bool
Returns a value indicating whether a property is defined for this component.
init()  : mixed
Initializes the application component.
login()  : bool
Logs in a user.
loginByAccessToken()  : IdentityInterface|null
Logs in a user by the given access token.
loginRequired()  : Response
Redirects the user browser to the login page.
logout()  : bool
Logs out the current user.
off()  : bool
Detaches an existing event handler from this component.
on()  : mixed
Attaches an event handler to an event.
setIdentity()  : mixed
Sets the user identity object.
setReturnUrl()  : mixed
Remembers the URL in the session so that it can be retrieved back later by [[getReturnUrl()]].
switchIdentity()  : mixed
Switches to a new identity for the current user.
trigger()  : mixed
Triggers an event.
afterLogin()  : mixed
This method is called after the user is successfully logged in.
afterLogout()  : mixed
This method is invoked right after a user is logged out via [[logout()]].
beforeLogin()  : bool
This method is called before logging in a user.
beforeLogout()  : bool
This method is invoked when calling [[logout()]] to log out a user.
getAccessChecker()  : CheckAccessInterface
Returns the access checker used for checking access.
getAuthManager()  : ManagerInterface
Returns auth manager associated with the user component.
getIdentityAndDurationFromCookie()  : array<string|int, mixed>|null
Determines if an identity cookie has a valid format and contains a valid auth key.
loginByCookie()  : mixed
Logs in a user by cookie.
regenerateCsrfToken()  : mixed
Regenerates CSRF token
removeIdentityCookie()  : mixed
Removes the identity cookie.
renewAuthStatus()  : mixed
Updates the authentication status using the information from session and cookie.
renewIdentityCookie()  : mixed
Renews the identity cookie.
sendIdentityCookie()  : mixed
Sends an identity cookie.
attachBehaviorInternal()  : Behavior
Attaches a behavior to this component.

Constants

EVENT_AFTER_LOGIN

public mixed EVENT_AFTER_LOGIN = 'afterLogin'

EVENT_AFTER_LOGOUT

public mixed EVENT_AFTER_LOGOUT = 'afterLogout'

EVENT_BEFORE_LOGIN

public mixed EVENT_BEFORE_LOGIN = 'beforeLogin'

EVENT_BEFORE_LOGOUT

public mixed EVENT_BEFORE_LOGOUT = 'beforeLogout'

Properties

$absoluteAuthTimeout

public int|null $absoluteAuthTimeout

the number of seconds in which the user will be logged out automatically regardless of activity. Note that this will not work if [[enableAutoLogin]] is true.

$absoluteAuthTimeoutParam

public string $absoluteAuthTimeoutParam = '__absoluteExpire'

the session variable name used to store the value of absolute expiration timestamp of the authenticated state. This is used when [[absoluteAuthTimeout]] is set.

$acceptableRedirectTypes

public array<string|int, mixed> $acceptableRedirectTypes = ['text/html', 'application/xhtml+xml']

MIME types for which this component should redirect to the [[loginUrl]].

Tags
since
2.0.8

$accessChecker

public CheckAccessInterface|string|array<string|int, mixed>|null $accessChecker

The access checker object to use for checking access or the application component ID of the access checker. If not set the application auth manager will be used.

Tags
since
2.0.9

$authKeyParam

public string $authKeyParam = '__authKey'

the session variable name used to store authentication key.

Tags
since
2.0.41

$authTimeout

public int|null $authTimeout

the number of seconds in which the user will be logged out automatically if the user remains inactive. If this property is not set, the user will be logged out after the current session expires (c.f. [[Session::timeout]]). Note that this will not work if [[enableAutoLogin]] is true.

$authTimeoutParam

public string $authTimeoutParam = '__expire'

the session variable name used to store the value of expiration timestamp of the authenticated state. This is used when [[authTimeout]] is set.

$autoRenewCookie

public bool $autoRenewCookie = true

whether to automatically renew the identity cookie each time a page is requested. This property is effective only when [[enableAutoLogin]] is true. When this is false, the identity cookie will expire after the specified duration since the user is initially logged in. When this is true, the identity cookie will expire after the specified duration since the user visits the site the last time.

Tags
see
enableAutoLogin

$behaviors read-only

public array<string|int, Behavior> $behaviors

List of behaviors attached to this component.

$enableAutoLogin

public bool $enableAutoLogin = false

whether to enable cookie-based login. Defaults to false. Note that this property will be ignored if [[enableSession]] is false.

$enableSession

public bool $enableSession = true

whether to use session to persist authentication status across multiple requests. You set this property to be false if your application is stateless, which is often the case for RESTful APIs.

$id read-only

public string|int|null $id

The unique identifier for the user. If null, it means the user is a guest.

$identity

public IdentityInterface|null $identity

The identity object associated with the currently logged-in user. null is returned if the user is not logged in (not authenticated).

$identityClass

public string $identityClass

the class name of the [[identity]] object.

$identityCookie

public array<string|int, mixed> $identityCookie = ['name' => '_identity', 'httpOnly' => true]

the configuration of the identity cookie. This property is used only when [[enableAutoLogin]] is true.

Tags
see
Cookie

$idParam

public string $idParam = '__id'

the session variable name used to store the value of [[id]].

$isGuest read-only

public bool $isGuest

Whether the current user is a guest.

$loginUrl

public string|array<string|int, mixed>|null $loginUrl = ['site/login']

the URL for login when [[loginRequired()]] is called. If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL. The first element of the array should be the route to the login action, and the rest of the name-value pairs are GET parameters used to construct the login URL. For example,

['site/login', 'ref' => 1]

If this property is null, a 403 HTTP exception will be raised when [[loginRequired()]] is called.

$returnUrl

public string $returnUrl

The URL that the user should be redirected to after login. Note that the type of this property differs in getter and setter. See [[getReturnUrl()]] and [[setReturnUrl()]] for details.

$returnUrlParam

public string $returnUrlParam = '__returnUrl'

the session variable name used to store the value of [[returnUrl]].

$_access

private mixed $_access = []

$_behaviors

private array<string|int, Behavior>|null $_behaviors

the attached behaviors (behavior name => behavior). This is null when not initialized.

$_events

private array<string|int, mixed> $_events = []

the attached event handlers (event name => handlers)

$_eventWildcards

private array<string|int, mixed> $_eventWildcards = []

the event handlers attached for wildcard patterns (event name wildcard => handlers)

Tags
since
2.0.14

$_identity

private mixed $_identity = false

Methods

__call()

Calls the named method which is not a class method.

public __call(string $name, array<string|int, mixed> $params) : mixed

This method will check if any attached behavior has the named method and will execute it if available.

Do not call this method directly as it is a PHP magic method that will be implicitly called when an unknown method is being invoked.

Parameters
$name : string

the method name

$params : array<string|int, mixed>

method parameters

Tags
throws
UnknownMethodException

when calling unknown method

Return values
mixed

the method return value

__clone()

This method is called after the object is created by cloning an existing one.

public __clone() : mixed

It removes all behaviors because they are attached to the old object.

__construct()

Constructor.

public __construct([array<string|int, mixed> $config = [] ]) : mixed

The default implementation does two things:

  • Initializes the object with the given configuration $config.
  • Call [[init()]].

If this method is overridden in a child class, it is recommended that

  • the last parameter of the constructor is a configuration array, like $config here.
  • call the parent implementation at the end of the constructor.
Parameters
$config : array<string|int, mixed> = []

name-value pairs that will be used to initialize the object properties

__get()

Returns the value of a component property.

public __get(string $name) : mixed

This method will check in the following order and act accordingly:

  • a property defined by a getter: return the getter result
  • a property of a behavior: return the behavior property value

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $value = $component->property;.

Parameters
$name : string

the property name

Tags
throws
UnknownPropertyException

if the property is not defined

throws
InvalidCallException

if the property is write-only.

see
__set()
Return values
mixed

the property value or the value of a behavior's property

__isset()

Checks if a property is set, i.e. defined and not null.

public __isset(string $name) : bool

This method will check in the following order and act accordingly:

  • a property defined by a setter: return whether the property is set
  • a property of a behavior: return whether the property is set
  • return false for non existing properties

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing isset($component->property).

Parameters
$name : string

the property name or the event name

Tags
see
https://www.php.net/manual/en/function.isset.php
Return values
bool

whether the named property is set

__set()

Sets the value of a component property.

public __set(string $name, mixed $value) : mixed

This method will check in the following order and act accordingly:

  • a property defined by a setter: set the property value
  • an event in the format of "on xyz": attach the handler to the event "xyz"
  • a behavior in the format of "as xyz": attach the behavior named as "xyz"
  • a property of a behavior: set the behavior property value

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing $component->property = $value;.

Parameters
$name : string

the property name or the event name

$value : mixed

the property value

Tags
throws
UnknownPropertyException

if the property is not defined

throws
InvalidCallException

if the property is read-only.

see
__get()

__unset()

Sets a component property to be null.

public __unset(string $name) : mixed

This method will check in the following order and act accordingly:

  • a property defined by a setter: set the property value to be null
  • a property of a behavior: set the property value to be null

Do not call this method directly as it is a PHP magic method that will be implicitly called when executing unset($component->property).

Parameters
$name : string

the property name

Tags
throws
InvalidCallException

if the property is read only.

see
https://www.php.net/manual/en/function.unset.php

attachBehavior()

Attaches a behavior to this component.

public attachBehavior(string $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior

This method will create the behavior object based on the given configuration. After that, the behavior object will be attached to this component by calling the [[Behavior::attach()]] method.

Parameters
$name : string

the name of the behavior.

$behavior : string|array<string|int, mixed>|Behavior

the behavior configuration. This can be one of the following:

  • a [[Behavior]] object
  • a string specifying the behavior class
  • an object configuration array that will be passed to [[Yii::createObject()]] to create the behavior object.
Tags
see
detachBehavior()
Return values
Behavior

the behavior object

attachBehaviors()

Attaches a list of behaviors to the component.

public attachBehaviors(array<string|int, mixed> $behaviors) : mixed

Each behavior is indexed by its name and should be a [[Behavior]] object, a string specifying the behavior class, or an configuration array for creating the behavior.

Parameters
$behaviors : array<string|int, mixed>

list of behaviors to be attached to the component

Tags
see
attachBehavior()

behaviors()

Returns a list of behaviors that this component should behave as.

public behaviors() : array<string|int, mixed>

Child classes may override this method to specify the behaviors they want to behave as.

The return value of this method should be an array of behavior objects or configurations indexed by behavior names. A behavior configuration can be either a string specifying the behavior class or an array of the following structure:

'behaviorName' => [
    'class' => 'BehaviorClass',
    'property1' => 'value1',
    'property2' => 'value2',
]

Note that a behavior class must extend from [[Behavior]]. Behaviors can be attached using a name or anonymously. When a name is used as the array key, using this name, the behavior can later be retrieved using [[getBehavior()]] or be detached using [[detachBehavior()]]. Anonymous behaviors can not be retrieved or detached.

Behaviors declared in this method will be attached to the component automatically (on demand).

Return values
array<string|int, mixed>

the behavior configurations.

can()

Checks if the user can perform the operation as specified by the given permission.

public can(string $permissionName[, array<string|int, mixed> $params = [] ][, bool $allowCaching = true ]) : bool

Note that you must configure "authManager" application component in order to use this method. Otherwise it will always return false.

Parameters
$permissionName : string

the name of the permission (e.g. "edit post") that needs access check.

$params : array<string|int, mixed> = []

name-value pairs that would be passed to the rules associated with the roles and permissions assigned to the user.

$allowCaching : bool = true

whether to allow caching the result of access check. When this parameter is true (default), if the access check of an operation was performed before, its result will be directly returned when calling this method to check the same operation. If this parameter is false, this method will always call [[\yii\rbac\CheckAccessInterface::checkAccess()]] to obtain the up-to-date access result. Note that this caching is effective only within the same request and only works when $params = [].

Return values
bool

whether the user can perform the operation as specified by the given permission.

canGetProperty()

Returns a value indicating whether a property can be read.

public canGetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool

A property can be read if:

  • the class has a getter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);
  • an attached behavior has a readable property of the given name (when $checkBehaviors is true).
Parameters
$name : string

the property name

$checkVars : bool = true

whether to treat member variables as properties

$checkBehaviors : bool = true

whether to treat behaviors' properties as properties of this component

Tags
see
canSetProperty()
Return values
bool

whether the property can be read

canSetProperty()

Returns a value indicating whether a property can be set.

public canSetProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool

A property can be written if:

  • the class has a setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);
  • an attached behavior has a writable property of the given name (when $checkBehaviors is true).
Parameters
$name : string

the property name

$checkVars : bool = true

whether to treat member variables as properties

$checkBehaviors : bool = true

whether to treat behaviors' properties as properties of this component

Tags
see
canGetProperty()
Return values
bool

whether the property can be written

checkRedirectAcceptable()

Checks if the `Accept` header contains a content type that allows redirection to the login page.

public checkRedirectAcceptable() : bool

The login page is assumed to serve text/html or application/xhtml+xml by default. You can change acceptable content types by modifying [[acceptableRedirectTypes]] property.

Tags
see
acceptableRedirectTypes
since
2.0.8
Return values
bool

whether this request may be redirected to the login page.

className()

Returns the fully qualified name of this class.

public static className() : string
Tags
deprecated

since 2.0.14. On PHP >=5.5, use ::class instead.

Return values
string

the fully qualified name of this class.

detachBehavior()

Detaches a behavior from the component.

public detachBehavior(string $name) : Behavior|null

The behavior's [[Behavior::detach()]] method will be invoked.

Parameters
$name : string

the behavior's name.

Return values
Behavior|null

the detached behavior. Null if the behavior does not exist.

detachBehaviors()

Detaches all behaviors from the component.

public detachBehaviors() : mixed

ensureBehaviors()

Makes sure that the behaviors declared in [[behaviors()]] are attached to this component.

public ensureBehaviors() : mixed

getBehavior()

Returns the named behavior object.

public getBehavior(string $name) : Behavior|null
Parameters
$name : string

the behavior name

Return values
Behavior|null

the behavior object, or null if the behavior does not exist

getBehaviors()

Returns all behaviors attached to this component.

public getBehaviors() : array<string|int, Behavior>
Return values
array<string|int, Behavior>

list of behaviors attached to this component

getId()

Returns a value that uniquely represents the user.

public getId() : string|int|null
Tags
see
getIdentity()
Return values
string|int|null

the unique identifier for the user. If null, it means the user is a guest.

getIdentity()

Returns the identity object associated with the currently logged-in user.

public getIdentity([bool $autoRenew = true ]) : IdentityInterface|null

When [[enableSession]] is true, this method may attempt to read the user's authentication data stored in session and reconstruct the corresponding identity object, if it has not done so before.

Parameters
$autoRenew : bool = true

whether to automatically renew authentication status if it has not been done so before. This is only useful when [[enableSession]] is true.

Tags
see
login()
see
logout()
Return values
IdentityInterface|null

the identity object associated with the currently logged-in user. null is returned if the user is not logged in (not authenticated).

getIsGuest()

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

public getIsGuest() : bool
Tags
see
getIdentity()
Return values
bool

whether the current user is a guest.

getReturnUrl()

Returns the URL that the browser should be redirected to after successful login.

public getReturnUrl([string|array<string|int, mixed>|null $defaultUrl = null ]) : string

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.

Parameters
$defaultUrl : string|array<string|int, mixed>|null = null

the default return URL in case it was not set previously. If this is null and the return URL was not set previously, [[Application::homeUrl]] will be redirected to. Please refer to [[setReturnUrl()]] on accepted format of the URL.

Tags
see
loginRequired()
Return values
string

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

hasEventHandlers()

Returns a value indicating whether there is any handler attached to the named event.

public hasEventHandlers(string $name) : bool
Parameters
$name : string

the event name

Return values
bool

whether there is any handler attached to the event.

hasMethod()

Returns a value indicating whether a method is defined.

public hasMethod(string $name[, bool $checkBehaviors = true ]) : bool

A method is defined if:

  • the class has a method with the specified name
  • an attached behavior has a method with the given name (when $checkBehaviors is true).
Parameters
$name : string

the property name

$checkBehaviors : bool = true

whether to treat behaviors' methods as methods of this component

Return values
bool

whether the method is defined

hasProperty()

Returns a value indicating whether a property is defined for this component.

public hasProperty(string $name[, bool $checkVars = true ][, bool $checkBehaviors = true ]) : bool

A property is defined if:

  • the class has a getter or setter method associated with the specified name (in this case, property name is case-insensitive);
  • the class has a member variable with the specified name (when $checkVars is true);
  • an attached behavior has a property of the given name (when $checkBehaviors is true).
Parameters
$name : string

the property name

$checkVars : bool = true

whether to treat member variables as properties

$checkBehaviors : bool = true

whether to treat behaviors' properties as properties of this component

Tags
see
canGetProperty()
see
canSetProperty()
Return values
bool

whether the property is defined

init()

Initializes the application component.

public init() : mixed

login()

Logs in a user.

public login(IdentityInterface $identity[, int $duration = 0 ]) : bool

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
Parameters
$identity : IdentityInterface

the user identity (which should already be authenticated)

$duration : int = 0

number of seconds that the user can remain in logged-in status, defaults to 0

Return values
bool

whether the user is logged in

loginByAccessToken()

Logs in a user by the given access token.

public loginByAccessToken(string $token[, mixed $type = null ]) : IdentityInterface|null

This method will first authenticate the user by calling [[IdentityInterface::findIdentityByAccessToken()]] with the provided access token. If successful, it will call [[login()]] to log in the authenticated user. If authentication fails or [[login()]] is unsuccessful, it will return null.

Parameters
$token : string

the access token

$type : mixed = null

the type of the token. The value of this parameter depends on the implementation. For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be yii\filters\auth\HttpBearerAuth.

Return values
IdentityInterface|null

the identity associated with the given access token. Null is returned if the access token is invalid or [[login()]] is unsuccessful.

loginRequired()

Redirects the user browser to the login page.

public loginRequired([bool $checkAjax = true ][, bool $checkAcceptHeader = true ]) : Response

Before the redirection, the current URL (if it's not an AJAX url) will be kept as [[returnUrl]] so that the user browser may be redirected back to the current page after successful login.

Make sure you set [[loginUrl]] so that the user browser can be redirected to the specified login URL after calling this method.

Note that when [[loginUrl]] is set, calling this method will NOT terminate the application execution.

Parameters
$checkAjax : bool = true

whether to check if the request is an AJAX request. When this is true and the request is an AJAX request, the current URL (for AJAX request) will NOT be set as the return URL.

$checkAcceptHeader : bool = true

whether to check if the request accepts HTML responses. Defaults to true. When this is true and the request does not accept HTML responses the current URL will not be SET as the return URL. Also instead of redirecting the user an ForbiddenHttpException is thrown. This parameter is available since version 2.0.8.

Tags
throws
ForbiddenHttpException

the "Access Denied" HTTP exception if [[loginUrl]] is not set or a redirect is not applicable.

Return values
Response

the redirection response if [[loginUrl]] is set

logout()

Logs out the current user.

public logout([bool $destroySession = true ]) : bool

This will remove authentication-related session data. If $destroySession is true, all session data will be removed.

Parameters
$destroySession : bool = true

whether to destroy the whole session. Defaults to true. This parameter is ignored if [[enableSession]] is false.

Return values
bool

whether the user is logged out

off()

Detaches an existing event handler from this component.

public off(string $name[, callable|null $handler = null ]) : bool

This method is the opposite of [[on()]].

Note: in case wildcard pattern is passed for event name, only the handlers registered with this wildcard will be removed, while handlers registered with plain names matching this wildcard will remain.

Parameters
$name : string

event name

$handler : callable|null = null

the event handler to be removed. If it is null, all handlers attached to the named event will be removed.

Tags
see
on()
Return values
bool

if a handler is found and detached

on()

Attaches an event handler to an event.

public on(string $name, callable $handler[, mixed $data = null ][, bool $append = true ]) : mixed

The event handler must be a valid PHP callback. The following are some examples:

function ($event) { ... }         // anonymous function
[$object, 'handleClick']          // $object->handleClick()
['Page', 'handleClick']           // Page::handleClick()
'handleClick'                     // global function handleClick()

The event handler must be defined with the following signature,

function ($event)

where $event is an [[Event]] object which includes parameters associated with the event.

Since 2.0.14 you can specify event name as a wildcard pattern:

$component->on('event.group.*', function ($event) {
    Yii::trace($event->name . ' is triggered.');
});
Parameters
$name : string

the event name

$handler : callable

the event handler

$data : mixed = null

the data to be passed to the event handler when the event is triggered. When the event handler is invoked, this data can be accessed via [[Event::data]].

$append : bool = true

whether to append new event handler to the end of the existing handler list. If false, the new handler will be inserted at the beginning of the existing handler list.

Tags
see
off()

setIdentity()

Sets the user identity object.

public setIdentity(IdentityInterface|null $identity) : mixed

Note that this method does not deal with session or cookie. You should usually use [[switchIdentity()]] to change the identity of the current user.

Parameters
$identity : IdentityInterface|null

the identity object associated with the currently logged user. If null, it means the current user will be a guest without any associated identity.

Tags
throws
InvalidValueException

if $identity object does not implement [[IdentityInterface]].

setReturnUrl()

Remembers the URL in the session so that it can be retrieved back later by [[getReturnUrl()]].

public setReturnUrl(string|array<string|int, mixed> $url) : mixed
Parameters
$url : string|array<string|int, mixed>

the URL that the user should be redirected to after login. If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL. The first element of the array should be the route, and the rest of the name-value pairs are GET parameters used to construct the URL. For example,

['admin/index', 'ref' => 1]

switchIdentity()

Switches to a new identity for the current user.

public switchIdentity(IdentityInterface|null $identity[, int $duration = 0 ]) : mixed

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.

Parameters
$identity : 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 : int = 0

number of seconds that the user can remain in logged-in status. This parameter is used only when $identity is not null.

trigger()

Triggers an event.

public trigger(string $name[, Event|null $event = null ]) : mixed

This method represents the happening of an event. It invokes all attached handlers for the event including class-level handlers.

Parameters
$name : string

the event name

$event : Event|null = null

the event instance. If not set, a default [[Event]] object will be created.

afterLogin()

This method is called after the user is successfully logged in.

protected afterLogin(IdentityInterface $identity, bool $cookieBased, int $duration) : mixed

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.

Parameters
$identity : IdentityInterface

the user identity information

$cookieBased : bool

whether the login is cookie-based

$duration : int

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

protected afterLogout(IdentityInterface $identity) : mixed

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.

Parameters
$identity : IdentityInterface

the user identity information

beforeLogin()

This method is called before logging in a user.

protected beforeLogin(IdentityInterface $identity, bool $cookieBased, int $duration) : bool

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.

Parameters
$identity : IdentityInterface

the user identity information

$cookieBased : bool

whether the login is cookie-based

$duration : int

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.

Return values
bool

whether the user should continue to be logged in

beforeLogout()

This method is invoked when calling [[logout()]] to log out a user.

protected beforeLogout(IdentityInterface $identity) : bool

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.

Parameters
$identity : IdentityInterface

the user identity information

Return values
bool

whether the user should continue to be logged out

getAuthManager()

Returns auth manager associated with the user component.

protected getAuthManager() : ManagerInterface

By default this is the authManager application component. You may override this method to return a different auth manager instance if needed.

Tags
since
2.0.6
deprecated

since version 2.0.9, to be removed in 2.1. Use [[getAccessChecker()]] instead.

Return values
ManagerInterface

getIdentityAndDurationFromCookie()

Determines if an identity cookie has a valid format and contains a valid auth key.

protected getIdentityAndDurationFromCookie() : array<string|int, mixed>|null

This method is used when [[enableAutoLogin]] is true. This method attempts to authenticate a user using the information in the identity cookie.

Tags
see
loginByCookie()
since
2.0.9
Return values
array<string|int, mixed>|null

Returns an array of 'identity' and 'duration' if valid, otherwise null.

loginByCookie()

Logs in a user by cookie.

protected loginByCookie() : mixed

This method attempts to log in a user using the ID and authKey information provided by the [[identityCookie|identity cookie]].

regenerateCsrfToken()

Regenerates CSRF token

protected regenerateCsrfToken() : mixed
Tags
since
2.0.14.2

removeIdentityCookie()

Removes the identity cookie.

protected removeIdentityCookie() : mixed

This method is used when [[enableAutoLogin]] is true.

Tags
since
2.0.9

renewAuthStatus()

Updates the authentication status using the information from session and cookie.

protected renewAuthStatus() : mixed

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 [[loginByCookie()|login by cookie]] if [[enableAutoLogin]] is true.

renewIdentityCookie()

Renews the identity cookie.

protected renewIdentityCookie() : mixed

This method will set the expiration time of the identity cookie to be the current time plus the originally specified cookie duration.

sendIdentityCookie()

Sends an identity cookie.

protected sendIdentityCookie(IdentityInterface $identity, int $duration) : mixed

This method is used when [[enableAutoLogin]] is true. It saves [[id]], [[IdentityInterface::getAuthKey()|auth key]], and the duration of cookie-based login information in the cookie.

Parameters
$identity : IdentityInterface
$duration : int

number of seconds that the user can remain in logged-in status.

Tags
see
loginByCookie()

attachBehaviorInternal()

Attaches a behavior to this component.

private attachBehaviorInternal(string|int $name, string|array<string|int, mixed>|Behavior $behavior) : Behavior
Parameters
$name : string|int

the name of the behavior. If this is an integer, it means the behavior is an anonymous one. Otherwise, the behavior is a named one and any existing behavior with the same name will be detached first.

$behavior : string|array<string|int, mixed>|Behavior

the behavior to be attached

Return values
Behavior

the attached behavior.


        
On this page

Search results