class UserLoginForm

Same name in other branches
  1. 9 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 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 20

Namespace

Drupal\user\Form
View source
class UserLoginForm extends FormBase {
    
    /**
     * The flood service.
     *
     * @var \Drupal\Core\Flood\FloodInterface
     */
    protected $flood;
    
    /**
     * 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;
    
    /**
     * Constructs a new UserLoginForm.
     *
     * @param \Drupal\Core\Flood\FloodInterface $flood
     *   The flood 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.
     */
    public function __construct(FloodInterface $flood, UserStorageInterface $user_storage, UserAuthInterface $user_auth, RendererInterface $renderer) {
        $this->flood = $flood;
        $this->userStorage = $user_storage;
        $this->userAuth = $user_auth;
        $this->renderer = $renderer;
    }
    
    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container) {
        return new static($container->get('flood'), $container->get('entity_type.manager')
            ->getStorage('user'), $container->get('user.auth'), $container->get('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) {
        $account = $this->userStorage
            ->load($form_state->get('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->flood
                ->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->flood
                    ->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->flood
                ->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->flood
                    ->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') {
                    $form_state->setErrorByName('name', $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.
                    $form_state->setErrorByName('name', $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(),
                    ]));
                }
            }
            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->flood
                ->clear('user.failed_login_user', $flood_control_user_identifier);
        }
    }

}

Members

Title Sort descending Deprecated Modifiers Object type Summary Overriden Title Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
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. Overrides UrlGeneratorTrait::redirect
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
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
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.
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.
UserLoginForm::$flood protected property The flood service.
UserLoginForm::$renderer protected property The renderer.
UserLoginForm::$userAuth protected property The user authentication object.
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.