UsersController ​
- Type
- Class
- Namespace
- craft\controllers
- Inherits
- craft\controllers\UsersController » craft\web\Controller » yii\web\Controller » yii\base\Controller » yii\base\Component » yii\base\BaseObject
- Implements
- yii\base\Configurable, yii\base\ViewContextInterface
- Uses traits
- craft\controllers\EditUserTrait
- 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(), \craft\controllers\actionGetRemainingSessionTime
, actionSendPasswordResetEmail(), actionSetPassword(), actionVerifyEmail() and actionSaveUser() require an authenticated Craft session via allowAnonymous.
Public Properties ​
Property | Description |
---|---|
action | yii\base\Action, null – The action that is currently being executed. |
actionParams | array – The parameters bound to the current action. |
behaviors | yii\base\Behavior – List of behaviors attached to this component. |
defaultAction | string – The ID of the action that is used when the action ID is not specified in the request. |
enableCsrfValidation | boolean – Whether to enable CSRF validation for the actions in this controller. |
id | string – The ID of this controller. |
layout | string, null, false – The name of the layout to be applied to this controller's views. |
module | yii\base\Module – The module that this controller belongs to. |
modules | yii\base\Module – All ancestor modules that this controller is located within. |
request | craft\web\Request |
response | craft\web\Response |
route | string – The route (module ID, controller ID and action ID) of the current request. |
uniqueId | string – The controller ID that is prefixed with the module ID (if any). |
view | craft\web\View – The view object that can be used to render views or view files |
viewPath | string – The directory containing the view files for this controller. |
Protected Properties ​
Property | Description |
---|---|
allowAnonymous | integer, boolean, integer[], string[] – Whether this controller’s actions can be accessed anonymously. |
allowAnonymous
​
- Type
- integer, boolean, integer[], string[]
- 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-modal' => self::ALLOW_ANONYMOUS_LIVE | self::ALLOW_ANONYMOUS_OFFLINE, 'get-user-for-login' => self::ALLOW_ANONYMOUS_LIVE | self::ALLOW_ANONYMOUS_OFFLINE, 'login' => self::ALLOW_ANONYMOUS_LIVE | self::ALLOW_ANONYMOUS_OFFLINE, 'auth-form' => self::ALLOW_ANONYMOUS_LIVE | self::ALLOW_ANONYMOUS_OFFLINE, 'login-with-passkey' => self::ALLOW_ANONYMOUS_LIVE | self::ALLOW_ANONYMOUS_OFFLINE, 'logout' => self::ALLOW_ANONYMOUS_LIVE | self::ALLOW_ANONYMOUS_OFFLINE, 'impersonate-with-token' => 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
orself::ALLOW_ANONYMOUS_NEVER
(default) – indicates that all controller actions should never be accessed anonymouslytrue
orself::ALLOW_ANONYMOUS_LIVE
– indicates that all controller actions can be accessed anonymously when the system is liveself::ALLOW_ANONYMOUS_OFFLINE
– indicates that all controller actions can be accessed anonymously when the system is offlineself::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.
Public Methods ​
Method | Description |
---|---|
__call() | Calls the named method which is not a class method. |
__clone() | This method is called after the object is created by cloning an existing one. |
__construct() | |
__get() | Returns the value of a component property. |
__isset() | Checks if a property is set, i.e. defined and not null. |
__set() | Sets the value of a component property. |
__unset() | Sets a component property to be null. |
actionActivateUser() | Manually activates a user account. Only admins have access. |
actionAddresses() | User addresses screen. |
actionAuthForm() | |
actionCreate() | Creates a new unpublished draft of a user and redirects to its edit page. |
actionDeactivateUser() | Deactivates a user. |
actionDeleteAddress() | Deletes a user’s address. |
actionDeleteUser() | Deletes a user. |
actionDeleteUserPhoto() | Delete all the photos for current user. |
actionEnableUser() | Enables a user that is currently disabled or archived. |
actionGetElevatedSessionTimeout() | Returns how many seconds are left in the current elevated user session. |
actionGetImpersonationUrl() | Generates and returns a new impersonation URL |
actionGetPasswordResetUrl() | Generates a new verification code for a given user, and returns its URL. |
actionImpersonate() | Logs a user in for impersonation. |
actionImpersonateWithToken() | Logs a user in for impersonation via an impersonation token. |
actionIndex() | User index |
actionLogin() | Displays the login template, and handles login post requests for logging in with a password. |
actionLoginModal() | Renders the login modal for logged-out control panel uses. |
actionLoginWithPasskey() | Logs a user in with a passkey. |
actionLogout() | |
actionMarkAnnouncementsAsRead() | Marks the user’s feature announcements as read. |
actionPasskeys() | User passkey screen |
actionPassword() | User password screen. |
actionPermissions() | User permissions screen. |
actionPreferences() | User preferences screen. |
actionProfile() | User profile screen |
actionRemovePasswordResetRequirement() | Removes the requirement for a user to reset their password on next login. |
actionRenderPhotoInput() | Renders a user photo input. |
actionRequirePasswordReset() | Requires a user to reset their password on next login. |
actionSaveAddress() | Saves a user’s address. |
actionSaveFieldLayout() | Saves the user field layout. |
actionSavePassword() | Saves a user’s new password. |
actionSavePermissions() | Saves a user’s permissions. |
actionSavePreferences() | Saves a user’s preferences. |
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. |
actionSetup2fa() | Returns a 2FA setup screen, for users who require a 2FA method. |
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() | Declares external actions for the controller. |
afterAction() | This method is invoked right after an action is executed. |
asCpModal() | Sends a control panel modal response. |
asCpScreen() | Sends a control panel screen response. |
asErrorJson() | Responds to the request with a JSON error message. |
asFailure() | Sends a failure response. |
asJson() | Send data formatted as JSON. |
asJsonP() | Sets the response format of the given data as JSONP. |
asModelFailure() | |
asModelSuccess() | |
asRaw() | Sets the response format of the given data as RAW. |
asSuccess() | Sends a success response. |
asXml() | Send data formatted as XML. |
attachBehavior() | Attaches a behavior to this component. |
attachBehaviors() | Attaches a list of behaviors to the component. |
beforeAction() | This method is invoked right before an action is executed. |
behaviors() | Returns a list of behaviors that this component should behave as. |
bindActionParams() | Binds the parameters to the action. |
canGetProperty() | Returns a value indicating whether a property can be read. |
canSetProperty() | Returns a value indicating whether a property can be set. |
className() | Returns the fully qualified name of this class. |
createAction() | Creates an action based on the given action ID. |
currentUser() | Returns the currently logged-in user. |
detachBehavior() | Detaches a behavior from the component. |
detachBehaviors() | Detaches all behaviors from the component. |
ensureBehaviors() | Makes sure that the behaviors declared in behaviors() are attached to this component. |
findLayoutFile() | Finds the applicable layout file. |
getBehavior() | Returns the named behavior object. |
getBehaviors() | Returns all behaviors attached to this component. |
getModules() | Returns all ancestor modules of this controller. |
getRoute() | Returns the route of the current request. |
getUniqueId() | Returns the unique ID of the controller. |
getView() | Returns the view object that can be used to render views or view files |
getViewPath() | Returns the directory containing view files for this controller. |
goBack() | Redirects the browser to the last visited page. |
goHome() | Redirects the browser to the home page. |
hasEventHandlers() | Returns a value indicating whether there is any handler attached to the named event. |
hasMethod() | Returns a value indicating whether a method is defined. |
hasProperty() | Returns a value indicating whether a property is defined for this component. |
init() | Initializes the object. |
off() | Detaches an existing event handler from this component. |
on() | 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() | Refreshes the current page. |
render() | Renders a view and applies layout if available. |
renderAjax() | Renders a view in response to an AJAX request. |
renderContent() | Renders a static string by applying a layout. |
renderFile() | Renders a view file. |
renderPartial() | Renders a view without applying layout. |
renderTemplate() | Sends a rendered template response. |
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() | 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() | Sets the view object to be used by this controller. |
setViewPath() | Sets the directory that contains the view files. |
trigger() | Triggers an event. |
actionActivateUser()
​
Manually activates a user account. Only admins have access.
Returns ​
actionAddresses()
​
- Since
- 5.0.0
User addresses screen.
Arguments ​
Returns ​
actionAuthForm()
​
actionCreate()
​
- Since
- 5.0.0
Creates a new unpublished draft of a user and redirects to its edit page.
Returns ​
actionDeactivateUser()
​
- Since
- 4.0.0
Deactivates a user.
Returns ​
actionDeleteAddress()
​
- Since
- 4.0.0
Deletes a user’s address.
Returns ​
actionDeleteUser()
​
Deletes a user.
Returns ​
actionDeleteUserPhoto()
​
Delete all the photos for current user.
Returns ​
Throws ​
actionEnableUser()
​
- Since
- 4.3.2
Enables a user that is currently disabled or archived.
Returns ​
actionGetElevatedSessionTimeout()
​
Returns how many seconds are left in the current elevated user session.
Returns ​
actionGetImpersonationUrl()
​
- Since
- 3.6.0
Generates and returns a new impersonation URL
Returns ​
Throws ​
actionGetPasswordResetUrl()
​
Generates a new verification code for a given user, and returns its URL.
Returns ​
Throws ​
- yii\web\BadRequestHttpException
if the existing password submitted with the request is invalid
actionImpersonate()
​
Logs a user in for impersonation.
Returns ​
Throws ​
actionImpersonateWithToken()
​
- Since
- 3.6.0
Logs a user in for impersonation via an impersonation token.
Arguments ​
Returns ​
Throws ​
actionIndex()
​
- Since
- 5.3.0
User index
Arguments ​
Returns ​
actionLogin()
​
Displays the login template, and handles login post requests for logging in with a password.
Returns ​
Throws ​
actionLoginModal()
​
- Since
- 5.0.0
Renders the login modal for logged-out control panel uses.
Returns ​
actionLoginWithPasskey()
​
- Since
- 5.0.0
Logs a user in with a passkey.
Returns ​
actionLogout()
​
Returns ​
actionMarkAnnouncementsAsRead()
​
Marks the user’s feature announcements as read.
Returns ​
actionPasskeys()
​
- Since
- 5.0.0
User passkey screen
Returns ​
actionPassword()
​
- Since
- 5.0.0
User password screen.
Arguments ​
$user
(craft\elements\User, null) – The user being edited, if there were any validation errors.
Returns ​
actionPermissions()
​
- Since
- 5.0.0
User permissions screen.
Arguments ​
Returns ​
actionPreferences()
​
- Since
- 5.0.0
User preferences screen.
Returns ​
actionProfile()
​
- Since
- 5.0.0
User profile screen
Arguments ​
$userId
(integer, null) – The user’s ID.$element
(craft\elements\User, null) – The user being edited, if there were any validation errors.
Returns ​
actionRemovePasswordResetRequirement()
​
- Since
- 5.0.0
Removes the requirement for a user to reset their password on next login.
Returns ​
actionRenderPhotoInput()
​
- Since
- 5.0.0
Renders a user photo input.
Returns ​
actionRequirePasswordReset()
​
- Since
- 5.0.0
Requires a user to reset their password on next login.
Returns ​
actionSaveAddress()
​
- Since
- 4.0.0
Saves a user’s address.
Returns ​
Throws ​
actionSaveFieldLayout()
​
Saves the user field layout.
Returns ​
actionSavePassword()
​
- Since
- 5.0.0
Saves a user’s new password.
Returns ​
actionSavePermissions()
​
- Since
- 5.0.0
Saves a user’s permissions.
Returns ​
actionSavePreferences()
​
- Since
- 5.0.0
Saves a user’s preferences.
Returns ​
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.
Returns ​
Throws ​
- yii\web\NotFoundHttpException
if the requested user cannot be found - yii\web\BadRequestHttpException
if attempting to create a client account, and one already exists - yii\web\ForbiddenHttpException
if attempting public registration but public registration is not allowed
actionSendActivationEmail()
​
Sends a new activation email to a user.
Returns ​
Throws ​
- yii\web\BadRequestHttpException
if the user is not pending
actionSendPasswordResetEmail()
​
Sends a password reset email.
Returns ​
Throws ​
- yii\web\NotFoundHttpException
if the requested user cannot be found
actionSessionInfo()
​
- Since
- 3.4.0
Returns information about the current user session, if any.
Returns ​
actionSetPassword()
​
Sets a user’s password once they’ve verified they have access to their email.
Returns ​
actionSetup2fa()
​
- Since
- 5.0.0
Returns a 2FA setup screen, for users who require a 2FA method.
Returns ​
actionSuspendUser()
​
Suspends a user.
Returns ​
Throws ​
- yii\web\ForbiddenHttpException
if a non-admin is attempting to suspend an admin
actionUnlockUser()
​
Unlocks a user, bypassing the cooldown phase.
Returns ​
Throws ​
- yii\web\ForbiddenHttpException
if a non-admin is attempting to unlock an admin
actionUnsuspendUser()
​
Unsuspends a user.
Returns ​
Throws ​
- yii\web\ForbiddenHttpException
if a non-admin is attempting to unsuspend an admin
actionUploadUserPhoto()
​
Upload a user photo.
Returns ​
Throws ​
- yii\web\BadRequestHttpException
if the uploaded file is not an image
actionUserContentSummary()
​
- Since
- 3.0.13
Returns a summary of the content that is owned by a given user ID(s).
Returns ​
actionVerifyEmail()
​
Verifies that a user has access to an email address.
Returns ​
actionVerifyPassword()
​
Verifies a password for a user.
Returns ​
asModelFailure()
​
Arguments ​
$model
$message
$modelName
$data
$routeParams
asModelSuccess()
​
Arguments ​
$model
$message
$modelName
$data
$redirect
beforeAction()
​
This method is invoked right before an action is executed.
The method will trigger the EVENT_BEFORE_ACTION 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): bool
{
// 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
}
Arguments ​
$action
(yii\base\Action) – The action to be executed.
Returns ​
boolean – Whether the action should continue to run.
Throws ​
- yii\web\BadRequestHttpException
if the request is missing a valid CSRF token - yii\web\ForbiddenHttpException
if the user is not logged in or lacks the necessary permissions - craft\web\ServiceUnavailableHttpException
if the system is offline and the user isn't allowed to access it - yii\web\UnauthorizedHttpException
Protected Methods ​
Method | Description |
---|---|
asEditUserScreen() | Prepares the response for a user management screen. |
bindInjectedParams() | Fills parameters based on types and names in action method signature. |
defineBehaviors() | Returns the behaviors to attach to this class. |
editedUser() | Returns the user being edited. |
getPostedRedirectUrl() | Gets the redirect param specified in the POST data. |
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_AFTER_FIND_LOGIN_USER ​
- Type
- craft\events\FindLoginUserEvent
- Since
- 4.2.0
The event that is triggered after attempting to find a user to sign in
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_BEFORE_FIND_LOGIN_USER ​
- Type
- craft\events\FindLoginUserEvent
- Since
- 4.2.0
The event that is triggered before attempting to find a user to sign in
use Craft;
use craft\controllers\UsersController;
use craft\elements\User;
use craft\events\FindLoginUserEvent;
use yii\base\Event;
Event::on(
UsersController::class,
UsersController::EVENT_BEFORE_FIND_LOGIN_USER,
function(FindLoginUserEvent $event) {
// force username-based login
$event->user = User::find()
->username($event->loginName)
->addSelect(['users.password', 'users.passwordResetRequired'])
->one();
}
);
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_DEFINE_EDIT_SCREENS ​
- Type
craft\controllers\DefineEditUserScreensEvent
- Since
- 5.1.0
The event that is triggered when defining the screens that should be shown for the user being edited.
EVENT_INVALID_USER_TOKEN ​
- Type
- craft\events\InvalidUserTokenEvent
- Since
- 3.6.5
The event that is triggered when an invalid user token is sent.
EVENT_LOGIN_FAILURE ​
The event that is triggered when a failed login attempt was made