class UserLoginForm

Same name in other branches
  1. 8.9.x core/modules/user/src/Form/UserLoginForm.php \Drupal\user\Form\UserLoginForm
  2. 10 core/modules/user/src/Form/UserLoginForm.php \Drupal\user\Form\UserLoginForm
  3. 11.x core/modules/user/src/Form/UserLoginForm.php \Drupal\user\Form\UserLoginForm

Provides a user login form.

@internal

Hierarchy

Expanded class hierarchy of UserLoginForm

1 file declares its use of UserLoginForm
UserLoginFormTest.php in core/modules/user/tests/src/Kernel/Form/UserLoginFormTest.php
1 string reference to 'UserLoginForm'
user.routing.yml in core/modules/user/user.routing.yml
core/modules/user/user.routing.yml

File

core/modules/user/src/Form/UserLoginForm.php, line 21

Namespace

Drupal\user\Form
View source
class UserLoginForm extends FormBase {
    
    /**
     * The user flood control service.
     *
     * @var \Drupal\user\UserFloodControl
     */
    protected $userFloodControl;
    
    /**
     * The user storage.
     *
     * @var \Drupal\user\UserStorageInterface
     */
    protected $userStorage;
    
    /**
     * The user authentication object.
     *
     * @var \Drupal\user\UserAuthInterface
     */
    protected $userAuth;
    
    /**
     * The renderer.
     *
     * @var \Drupal\Core\Render\RendererInterface
     */
    protected $renderer;
    
    /**
     * The bare HTML renderer.
     *
     * @var \Drupal\Core\Render\BareHtmlPageRendererInterface
     */
    protected $bareHtmlPageRenderer;
    
    /**
     * Constructs a new UserLoginForm.
     *
     * @param \Drupal\user\UserFloodControlInterface $user_flood_control
     *   The user flood control service.
     * @param \Drupal\user\UserStorageInterface $user_storage
     *   The user storage.
     * @param \Drupal\user\UserAuthInterface $user_auth
     *   The user authentication object.
     * @param \Drupal\Core\Render\RendererInterface $renderer
     *   The renderer.
     * @param \Drupal\Core\Render\BareHtmlPageRendererInterface $bare_html_renderer
     *   The renderer.
     */
    public function __construct($user_flood_control, UserStorageInterface $user_storage, UserAuthInterface $user_auth, RendererInterface $renderer, BareHtmlPageRendererInterface $bare_html_renderer = NULL) {
        if (!$user_flood_control instanceof UserFloodControlInterface) {
            @trigger_error('Passing the flood service to ' . __METHOD__ . ' is deprecated in drupal:9.1.0 and is replaced by user.flood_control in drupal:10.0.0. See https://www.drupal.org/node/3067148', E_USER_DEPRECATED);
            $user_flood_control = \Drupal::service('user.flood_control');
        }
        if (!$bare_html_renderer instanceof BareHtmlPageRendererInterface) {
            @trigger_error('Calling UserLoginForm::__construct() without the $bare_html_renderer argument is deprecated in drupal:9.4.0 and will be required before drupal:10.0.0. See https://www.drupal.org/node/3251987.', E_USER_DEPRECATED);
            $bare_html_renderer = \Drupal::service('bare_html_page_renderer');
        }
        $this->userFloodControl = $user_flood_control;
        $this->userStorage = $user_storage;
        $this->userAuth = $user_auth;
        $this->renderer = $renderer;
        $this->bareHtmlPageRenderer = $bare_html_renderer;
    }
    
    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container) {
        return new static($container->get('user.flood_control'), $container->get('entity_type.manager')
            ->getStorage('user'), $container->get('user.auth'), $container->get('renderer'), $container->get('bare_html_page_renderer'));
    }
    
    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'user_login_form';
    }
    
    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state) {
        $config = $this->config('system.site');
        // Display login form:
        $form['name'] = [
            '#type' => 'textfield',
            '#title' => $this->t('Username'),
            '#size' => 60,
            '#maxlength' => UserInterface::USERNAME_MAX_LENGTH,
            '#description' => $this->t('Enter your @s username.', [
                '@s' => $config->get('name'),
            ]),
            '#required' => TRUE,
            '#attributes' => [
                'autocorrect' => 'none',
                'autocapitalize' => 'none',
                'spellcheck' => 'false',
                'autofocus' => 'autofocus',
            ],
        ];
        $form['pass'] = [
            '#type' => 'password',
            '#title' => $this->t('Password'),
            '#size' => 60,
            '#description' => $this->t('Enter the password that accompanies your username.'),
            '#required' => TRUE,
        ];
        $form['actions'] = [
            '#type' => 'actions',
        ];
        $form['actions']['submit'] = [
            '#type' => 'submit',
            '#value' => $this->t('Log in'),
        ];
        $form['#validate'][] = '::validateName';
        $form['#validate'][] = '::validateAuthentication';
        $form['#validate'][] = '::validateFinal';
        $this->renderer
            ->addCacheableDependency($form, $config);
        return $form;
    }
    
    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        if (empty($uid = $form_state->get('uid'))) {
            return;
        }
        $account = $this->userStorage
            ->load($uid);
        // A destination was set, probably on an exception controller.
        if (!$this->getRequest()->request
            ->has('destination')) {
            $form_state->setRedirect('entity.user.canonical', [
                'user' => $account->id(),
            ]);
        }
        else {
            $this->getRequest()->query
                ->set('destination', $this->getRequest()->request
                ->get('destination'));
        }
        user_login_finalize($account);
    }
    
    /**
     * Sets an error if supplied username has been blocked.
     */
    public function validateName(array &$form, FormStateInterface $form_state) {
        if (!$form_state->isValueEmpty('name') && user_is_blocked($form_state->getValue('name'))) {
            // Blocked in user administration.
            $form_state->setErrorByName('name', $this->t('The username %name has not been activated or is blocked.', [
                '%name' => $form_state->getValue('name'),
            ]));
        }
    }
    
    /**
     * Checks supplied username/password against local users table.
     *
     * If successful, $form_state->get('uid') is set to the matching user ID.
     */
    public function validateAuthentication(array &$form, FormStateInterface $form_state) {
        $password = trim($form_state->getValue('pass'));
        $flood_config = $this->config('user.flood');
        if (!$form_state->isValueEmpty('name') && strlen($password) > 0) {
            // Do not allow any login from the current user's IP if the limit has been
            // reached. Default is 50 failed attempts allowed in one hour. This is
            // independent of the per-user limit to catch attempts from one IP to log
            // in to many different user accounts.  We have a reasonably high limit
            // since there may be only one apparent IP for all users at an institution.
            if (!$this->userFloodControl
                ->isAllowed('user.failed_login_ip', $flood_config->get('ip_limit'), $flood_config->get('ip_window'))) {
                $form_state->set('flood_control_triggered', 'ip');
                return;
            }
            $accounts = $this->userStorage
                ->loadByProperties([
                'name' => $form_state->getValue('name'),
                'status' => 1,
            ]);
            $account = reset($accounts);
            if ($account) {
                if ($flood_config->get('uid_only')) {
                    // Register flood events based on the uid only, so they apply for any
                    // IP address. This is the most secure option.
                    $identifier = $account->id();
                }
                else {
                    // The default identifier is a combination of uid and IP address. This
                    // is less secure but more resistant to denial-of-service attacks that
                    // could lock out all users with public user names.
                    $identifier = $account->id() . '-' . $this->getRequest()
                        ->getClientIP();
                }
                $form_state->set('flood_control_user_identifier', $identifier);
                // Don't allow login if the limit for this user has been reached.
                // Default is to allow 5 failed attempts every 6 hours.
                if (!$this->userFloodControl
                    ->isAllowed('user.failed_login_user', $flood_config->get('user_limit'), $flood_config->get('user_window'), $identifier)) {
                    $form_state->set('flood_control_triggered', 'user');
                    return;
                }
            }
            // We are not limited by flood control, so try to authenticate.
            // Store $uid in form state as a flag for self::validateFinal().
            $uid = $this->userAuth
                ->authenticate($form_state->getValue('name'), $password);
            $form_state->set('uid', $uid);
        }
    }
    
    /**
     * Checks if user was not authenticated, or if too many logins were attempted.
     *
     * This validation function should always be the last one.
     */
    public function validateFinal(array &$form, FormStateInterface $form_state) {
        $flood_config = $this->config('user.flood');
        if (!$form_state->get('uid')) {
            // Always register an IP-based failed login event.
            $this->userFloodControl
                ->register('user.failed_login_ip', $flood_config->get('ip_window'));
            // Register a per-user failed login event.
            if ($flood_control_user_identifier = $form_state->get('flood_control_user_identifier')) {
                $this->userFloodControl
                    ->register('user.failed_login_user', $flood_config->get('user_window'), $flood_control_user_identifier);
            }
            if ($flood_control_triggered = $form_state->get('flood_control_triggered')) {
                if ($flood_control_triggered == 'user') {
                    $message = $this->formatPlural($flood_config->get('user_limit'), 'There has been more than one failed login attempt for this account. It is temporarily blocked. Try again later or <a href=":url">request a new password</a>.', 'There have been more than @count failed login attempts for this account. It is temporarily blocked. Try again later or <a href=":url">request a new password</a>.', [
                        ':url' => Url::fromRoute('user.pass')->toString(),
                    ]);
                }
                else {
                    // We did not find a uid, so the limit is IP-based.
                    $message = $this->t('Too many failed login attempts from your IP address. This IP address is temporarily blocked. Try again later or <a href=":url">request a new password</a>.', [
                        ':url' => Url::fromRoute('user.pass')->toString(),
                    ]);
                }
                $response = $this->bareHtmlPageRenderer
                    ->renderBarePage([
                    '#markup' => $message,
                ], $this->t('Login failed'), 'maintenance_page');
                $response->setStatusCode(403);
                $form_state->setResponse($response);
            }
            else {
                // Use $form_state->getUserInput() in the error message to guarantee
                // that we send exactly what the user typed in. The value from
                // $form_state->getValue() may have been modified by validation
                // handlers that ran earlier than this one.
                $user_input = $form_state->getUserInput();
                $query = isset($user_input['name']) ? [
                    'name' => $user_input['name'],
                ] : [];
                $form_state->setErrorByName('name', $this->t('Unrecognized username or password. <a href=":password">Forgot your password?</a>', [
                    ':password' => Url::fromRoute('user.pass', [], [
                        'query' => $query,
                    ])->toString(),
                ]));
                $accounts = $this->userStorage
                    ->loadByProperties([
                    'name' => $form_state->getValue('name'),
                ]);
                if (!empty($accounts)) {
                    $this->logger('user')
                        ->notice('Login attempt failed for %user.', [
                        '%user' => $form_state->getValue('name'),
                    ]);
                }
                else {
                    // If the username entered is not a valid user,
                    // only store the IP address.
                    $this->logger('user')
                        ->notice('Login attempt failed from %ip.', [
                        '%ip' => $this->getRequest()
                            ->getClientIp(),
                    ]);
                }
            }
        }
        elseif ($flood_control_user_identifier = $form_state->get('flood_control_user_identifier')) {
            // Clear past failures for this user so as not to block a user who might
            // log in and out more than once in an hour.
            $this->userFloodControl
                ->clear('user.failed_login_user', $flood_control_user_identifier);
        }
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 3
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 3
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route.
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 73
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 17
MessengerTrait::messenger public function Gets the messenger. 17
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a &#039;destination&#039; URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 3
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UserLoginForm::$bareHtmlPageRenderer protected property The bare HTML renderer.
UserLoginForm::$renderer protected property The renderer.
UserLoginForm::$userAuth protected property The user authentication object.
UserLoginForm::$userFloodControl protected property The user flood control service.
UserLoginForm::$userStorage protected property The user storage.
UserLoginForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
UserLoginForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
UserLoginForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
UserLoginForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
UserLoginForm::validateAuthentication public function Checks supplied username/password against local users table.
UserLoginForm::validateFinal public function Checks if user was not authenticated, or if too many logins were attempted.
UserLoginForm::validateName public function Sets an error if supplied username has been blocked.
UserLoginForm::__construct public function Constructs a new UserLoginForm.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.