UsersController

Type
Class
Namespace
craft\controllers
Inherits
craft\controllers\UsersController » craft\web\Controller » yii\web\Controller (opens new window) » yii\base\Controller (opens new window) » yii\base\Component (opens new window) » yii\base\BaseObject (opens new window)
Implements
yii\base\Configurable (opens new window), yii\base\ViewContextInterface (opens new window)
Since
3.0.0

The UsersController class is a controller that handles various user account related tasks such as logging-in, impersonating a user, logging out, forgetting passwords, setting passwords, validating accounts, activating accounts, creating users, saving users, processing user avatars, deleting, suspending and unsuspending users.

Note that all actions in the controller, except actionLogin(), actionLogout(), actionGetRemainingSessionTime(), actionSendPasswordResetEmail(), actionSetPassword(), actionVerifyEmail() and actionSaveUser() require an authenticated Craft session via allowAnonymous.

View source (opens new window)

# Public Properties

Property Description
action (opens new window) yii\base\Action (opens new window) – The action that is currently being executed.
actionParams (opens new window) array (opens new window) – The parameters bound to the current action.
behaviors (opens new window) yii\base\Behavior (opens new window) – List of behaviors attached to this component
defaultAction (opens new window) string (opens new window) – The ID of the action that is used when the action ID is not specified in the request.
enableCsrfValidation (opens new window) boolean (opens new window) – Whether to enable CSRF validation for the actions in this controller.
id (opens new window) string (opens new window) – The ID of this controller.
layout (opens new window) null (opens new window), string (opens new window), false (opens new window) – The name of the layout to be applied to this controller's views.
module (opens new window) yii\base\Module (opens new window) – The module that this controller belongs to.
modules (opens new window) yii\base\Module (opens new window) – All ancestor modules that this controller is located within.
request (opens new window) yii\base\Request (opens new window), array (opens new window), string (opens new window) – The request.
response (opens new window) yii\base\Response (opens new window), array (opens new window), string (opens new window) – The response.
route (opens new window) string (opens new window) – The route (module ID, controller ID and action ID) of the current request.
uniqueId (opens new window) string (opens new window) – The controller ID that is prefixed with the module ID (if any).
view (opens new window) yii\base\View (opens new window), yii\web\View (opens new window) – The view object that can be used to render views or view files.
viewPath (opens new window) string (opens new window) – The view path that may be prefixed to a relative view name.

# Protected Properties

Property Description
allowAnonymous integer (opens new window), boolean (opens new window), integer (opens new window)[], string (opens new window)[] – Whether this controller’s actions can be accessed anonymously.

# allowAnonymous

Type
integer (opens new window), boolean (opens new window), integer (opens new window)[], string (opens new window)[]
Default value
['get-remaining-session-time' => self::ALLOW_ANONYMOUS_LIVE | self::ALLOW_ANONYMOUS_OFFLINE, 'session-info' => self::ALLOW_ANONYMOUS_LIVE | self::ALLOW_ANONYMOUS_OFFLINE, 'login' => self::ALLOW_ANONYMOUS_LIVE | self::ALLOW_ANONYMOUS_OFFLINE, 'logout' => self::ALLOW_ANONYMOUS_LIVE | self::ALLOW_ANONYMOUS_OFFLINE, 'save-user' => self::ALLOW_ANONYMOUS_LIVE, 'send-activation-email' => self::ALLOW_ANONYMOUS_LIVE | self::ALLOW_ANONYMOUS_OFFLINE, 'send-password-reset-email' => self::ALLOW_ANONYMOUS_LIVE | self::ALLOW_ANONYMOUS_OFFLINE, 'set-password' => self::ALLOW_ANONYMOUS_LIVE | self::ALLOW_ANONYMOUS_OFFLINE, 'verify-email' => self::ALLOW_ANONYMOUS_LIVE | self::ALLOW_ANONYMOUS_OFFLINE]

Whether this controller’s actions can be accessed anonymously.

This can be set to any of the following:

  • false or self::ALLOW_ANONYMOUS_NEVER (default) – indicates that all controller actions should never be accessed anonymously
  • true or self::ALLOW_ANONYMOUS_LIVE – indicates that all controller actions can be accessed anonymously when the system is live
  • self::ALLOW_ANONYMOUS_OFFLINE – indicates that all controller actions can be accessed anonymously when the system is offline
  • self::ALLOW_ANONYMOUS_LIVE | self::ALLOW_ANONYMOUS_OFFLINE – indicates that all controller actions can be accessed anonymously when the system is live or offline
  • An array of action IDs (e.g. ['save-guest-entry', 'edit-guest-entry']) – indicates that the listed action IDs can be accessed anonymously when the system is live
  • An array of action ID/bitwise pairs (e.g. ['save-guest-entry' => self::ALLOW_ANONYMOUS_OFFLINE] – indicates that the listed action IDs can be accessed anonymously per the bitwise int assigned to it.

View source (opens new window)

# Public Methods

Method Description
__call() (opens new window) Calls the named method which is not a class method.
__clone() (opens new window) This method is called after the object is created by cloning an existing one.
__construct() (opens new window) Constructor.
__get() (opens new window) Returns the value of an object property.
__isset() (opens new window) Checks if a property is set, i.e. defined and not null.
__set() (opens new window) Sets value of an object property.
__unset() (opens new window) Sets an object property to null.
actionActivateUser() Manually activates a user account. Only admins have access.
actionDeleteUser() Deletes a user.
actionDeleteUserPhoto() Delete all the photos for current user.
actionEditUser() Edit a user account.
actionGetElevatedSessionTimeout() Returns how many seconds are left in the current elevated user session.
actionGetPasswordResetUrl() Generates a new verification code for a given user, and returns its URL.
actionGetRemainingSessionTime() Returns how many seconds are left in the current user session.
actionImpersonate() Logs a user in for impersonation. Requires you to be an administrator.
actionLogin() Displays the login template, and handles login post requests.
actionLogout()
actionSaveFieldLayout() Saves the user field layout.
actionSaveUser() Provides an endpoint for saving a user account.
actionSendActivationEmail() Sends a new activation email to a user.
actionSendPasswordResetEmail() Sends a password reset email.
actionSessionInfo() Returns information about the current user session, if any.
actionSetPassword() Sets a user's password once they've verified they have access to their email.
actionStartElevatedSession() Starts an elevated user session.
actionSuspendUser() Suspends a user.
actionUnlockUser() Unlocks a user, bypassing the cooldown phase.
actionUnsuspendUser() Unsuspends a user.
actionUploadUserPhoto() Upload a user photo.
actionUserContentSummary() Returns a summary of the content that is owned by a given user ID(s).
actionVerifyEmail() Verifies that a user has access to an email address.
actionVerifyPassword() Verifies a password for a user.
actions() (opens new window) Declares external actions for the controller.
afterAction() (opens new window) This method is invoked right after an action is executed.
asErrorJson() Responds to the request with a JSON error message.
asJson() (opens new window) Send data formatted as JSON.
asJsonP() Sets the response format of the given data as JSONP.
asRaw() Sets the response format of the given data as RAW.
asXml() (opens new window) Send data formatted as XML.
attachBehavior() (opens new window) Attaches a behavior to this component.
attachBehaviors() (opens new window) Attaches a list of behaviors to the component.
beforeAction() This method is invoked right before an action is executed.
behaviors() (opens new window) Returns a list of behaviors that this component should behave as.
bindActionParams() (opens new window) Binds the parameters to the action.
canGetProperty() (opens new window) Returns a value indicating whether a property can be read.
canSetProperty() (opens new window) Returns a value indicating whether a property can be set.
className() (opens new window) Returns the fully qualified name of this class.
createAction() (opens new window) Creates an action based on the given action ID.
detachBehavior() (opens new window) Detaches a behavior from the component.
detachBehaviors() (opens new window) Detaches all behaviors from the component.
ensureBehaviors() (opens new window) Makes sure that the behaviors declared in behaviors() (opens new window) are attached to this component.
findLayoutFile() (opens new window) Finds the applicable layout file.
getBehavior() (opens new window) Returns the named behavior object.
getBehaviors() (opens new window) Returns all behaviors attached to this component.
getModules() (opens new window) Returns all ancestor modules of this controller.
getRoute() (opens new window) Returns the route of the current request.
getUniqueId() (opens new window) Returns the unique ID of the controller.
getView() (opens new window) Returns the view object that can be used to render views or view files.
getViewPath() (opens new window)
goBack() (opens new window) Redirects the browser to the last visited page.
goHome() (opens new window) Redirects the browser to the home page.
hasEventHandlers() (opens new window) Returns a value indicating whether there is any handler attached to the named event.
hasMethod() (opens new window) Returns a value indicating whether a method is defined.
hasProperty() (opens new window) Returns a value indicating whether a property is defined.
init() Initializes the object.
off() (opens new window) Detaches an existing event handler from this component.
on() (opens new window) Attaches an event handler to an event.
redirect() Redirects the browser to the specified URL.
redirectToPostedUrl() Redirects to the URI specified in the POST.
refresh() (opens new window) Refreshes the current page.
render() (opens new window) Renders a view and applies layout if available.
renderAjax() (opens new window) Renders a view in response to an AJAX request.
renderContent() (opens new window) Renders a static string by applying a layout.
renderFile() (opens new window) Renders a view file.
renderPartial() (opens new window) Renders a view without applying layout.
renderTemplate() Renders a template.
requireAcceptsJson() Throws a 400 error if the request doesn't accept JSON.
requireAdmin() Throws a 403 error if the current user is not an admin.
requireAuthorization() Checks whether the current user can perform a given action, and ends the request with a 403 error if they don’t.
requireCpRequest() Throws a 400 error if the current request isn’t a control panel request.
requireElevatedSession() Requires that the user has an elevated session.
requireGuest() Redirects the user to the account template if they are logged in.
requireLogin() Redirects the user to the login template if they're not logged in.
requirePermission() Checks whether the current user has a given permission, and ends the request with a 403 error if they don’t.
requirePostRequest() Throws a 400 error if this isn’t a POST request
requireSiteRequest() Throws a 400 error if the current request isn’t a site request.
requireToken() Throws a 400 error if the current request doesn’t have a valid Craft token.
run() (opens new window) Runs a request specified in terms of a route.
runAction() Runs an action within this controller with the specified action ID and parameters.
setFailFlash() Sets an error flash message on the user session.
setSuccessFlash() Sets a success flash message on the user session.
setView() (opens new window) Sets the view object to be used by this controller.
setViewPath() (opens new window) Sets the directory that contains the view files.
trigger() (opens new window) Triggers an event.

# actionActivateUser()

Manually activates a user account. Only admins have access.

View source (opens new window)

Returns

yii\web\Response (opens new window)

# actionDeleteUser()

Deletes a user.

View source (opens new window)

Returns

yii\web\Response (opens new window), null (opens new window)

# actionDeleteUserPhoto()

Delete all the photos for current user.

View source (opens new window)

Returns

yii\web\Response (opens new window)

Throws

# actionEditUser()

Edit a user account.

View source (opens new window)

Arguments

Returns

yii\web\Response (opens new window)

Throws

# actionGetElevatedSessionTimeout()

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

View source (opens new window)

Returns

yii\web\Response (opens new window)

# actionGetPasswordResetUrl()

Generates a new verification code for a given user, and returns its URL.

View source (opens new window)

Returns

yii\web\Response (opens new window)

Throws

# actionGetRemainingSessionTime()

DEPRECATED

Deprecated in 3.4.0. Use actionSessionInfo() instead.

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

View source (opens new window)

Returns

yii\web\Response (opens new window)

# actionImpersonate()

Logs a user in for impersonation. Requires you to be an administrator.

View source (opens new window)

Returns

yii\web\Response (opens new window), null (opens new window)

Throws

# actionLogin()

Displays the login template, and handles login post requests.

View source (opens new window)

Returns

yii\web\Response (opens new window), null (opens new window)

Throws

# actionLogout()

View source (opens new window)

Returns

yii\web\Response (opens new window)

# actionSaveFieldLayout()

Saves the user field layout.

View source (opens new window)

Returns

yii\web\Response (opens new window), null (opens new window)

# actionSaveUser()

Provides an endpoint for saving a user account.

This action accounts for the following scenarios:

  • An admin registering a new user account.
  • An admin editing an existing user account.
  • A normal user with user-administration permissions registering a new user account.
  • A normal user with user-administration permissions editing an existing user account.
  • A guest registering a new user account ("public registration"). This action behaves the same regardless of whether it was requested from the control panel or the front-end site.

View source (opens new window)

Returns

yii\web\Response (opens new window), null (opens new window)

Throws

# actionSendActivationEmail()

Sends a new activation email to a user.

View source (opens new window)

Returns

yii\web\Response (opens new window)

Throws

# actionSendPasswordResetEmail()

Sends a password reset email.

View source (opens new window)

Returns

yii\web\Response (opens new window), null (opens new window)

Throws

# actionSessionInfo()

Since
3.4.0

Returns information about the current user session, if any.

View source (opens new window)

Returns

yii\web\Response (opens new window)

# actionSetPassword()

Sets a user's password once they've verified they have access to their email.

View source (opens new window)

Returns

yii\web\Response (opens new window)

# actionStartElevatedSession()

Starts an elevated user session.

return Response

View source (opens new window)

# actionSuspendUser()

Suspends a user.

View source (opens new window)

Returns

yii\web\Response (opens new window), null (opens new window)

Throws

# actionUnlockUser()

Unlocks a user, bypassing the cooldown phase.

View source (opens new window)

Returns

yii\web\Response (opens new window)

Throws

# actionUnsuspendUser()

Unsuspends a user.

View source (opens new window)

Returns

yii\web\Response (opens new window), null (opens new window)

Throws

# actionUploadUserPhoto()

Upload a user photo.

View source (opens new window)

Returns

yii\web\Response (opens new window), null (opens new window)

Throws

# actionUserContentSummary()

Since
3.0.13

Returns a summary of the content that is owned by a given user ID(s).

View source (opens new window)

Returns

yii\web\Response (opens new window), null (opens new window)

# actionVerifyEmail()

Verifies that a user has access to an email address.

View source (opens new window)

Returns

yii\web\Response (opens new window)

# actionVerifyPassword()

Verifies a password for a user.

View source (opens new window)

Returns

yii\web\Response (opens new window)

# beforeAction()

This method is invoked right before an action is executed.

The method will trigger the EVENT_BEFORE_ACTION (opens new window) event. The return value of the method will determine whether the action should continue to run.

In case the action should not run, the request should be handled inside of the beforeAction code by either providing the necessary output or redirecting the request. Otherwise the response will be empty.

If you override this method, your code should look like the following:

public function beforeAction($action)
{
    // your custom code here, if you want the code to run before action filters,
    // which are triggered on the [EVENT_BEFORE_ACTION](https://www.yiiframework.com/doc/api/2.0/yii-base-controller#EVENT_BEFORE_ACTION-detail) event, e.g. PageCache or AccessControl

    if (!parent::beforeAction($action)) {
        return false;
    }

    // other custom code here

    return true; // or false to not run the action
}

View source (opens new window)

Arguments

Returns

boolean (opens new window) – Whether the action should continue to run.

Throws

# Protected Methods

Method Description
bindInjectedParams() (opens new window) Fills parameters based on types and names in action method signature.

# Constants

Constant Description
ALLOW_ANONYMOUS_LIVE
ALLOW_ANONYMOUS_NEVER
ALLOW_ANONYMOUS_OFFLINE

# Events

# EVENT_AFTER_ASSIGN_GROUPS_AND_PERMISSIONS

Type
craft\events\UserEvent
Since
3.5.13

The event that is triggered after user groups and permissions have been assigned to the user getting saved

# EVENT_BEFORE_ASSIGN_GROUPS_AND_PERMISSIONS

Type
craft\events\UserEvent
Since
3.5.13

The event that is triggered BEFORE user groups and permissions ARE assigned to the user getting saved

# EVENT_DEFINE_CONTENT_SUMMARY

Type
craft\events\DefineUserContentSummaryEvent
Since
3.0.13

The event that is triggered when defining a summary of content owned by a user(s), before they are deleted

Example

use craft\controllers\UsersController;
use craft\events\DefineUserContentSummaryEvent;
use yii\base\Event;

Event::on(UsersController::class, UsersController::EVENT_DEFINE_CONTENT_SUMMARY, function(DefineUserContentSummaryEvent $e) {
    $e->contentSummary[] = 'A pair of sneakers';
});

# EVENT_LOGIN_FAILURE

Type
craft\events\LoginFailureEvent

The event that is triggered when a failed login attempt was made

# EVENT_REGISTER_USER_ACTIONS

Type
craft\events\RegisterUserActionsEvent

The event that is triggered when a user’s available actions are being registered