/** * {@inheritdoc} */ public function validate($items, Constraint $constraint) { /** @var CommentNameConstraint $constraint */ if (!isset($items)) { return; } /** @var CommentInterface $comment */ $comment = $items->getEntity(); if (!isset($comment)) { // Looks like we are validating a field not being part of a comment, // nothing we can do then. return; } $author_name = $items->first()->value; // Do not allow unauthenticated comment authors to use a name that is // taken by a registered user. if (isset($author_name) && $author_name !== '' && $comment->getOwnerId() === 0) { $users = $this->userStorage->loadByProperties(array('name' => $author_name)); if (!empty($users)) { $this->context->addViolation($constraint->messageNameTaken, array('%name' => $author_name)); } } elseif (isset($author_name) && $author_name !== '' && $comment->getOwnerId()) { $owner = $comment->getOwner(); if ($owner->getUsername() != $author_name) { $this->context->addViolation($constraint->messageMatch); } } // Anonymous account might be required - depending on field settings. if ($comment->getOwnerId() === 0 && empty($author_name) && $this->getAnonymousContactDetailsSetting($comment) === COMMENT_ANONYMOUS_MUST_CONTACT) { $this->context->addViolation($constraint->messageRequired); } }
/** * {@inheritdoc} */ public function onBlockActiveContext(BlockContextEvent $event) { $current_user = $this->userStorage->load($this->account->id()); $context = new Context(new ContextDefinition('entity:user', $this->t('Current user'))); $context->setContextValue($current_user); $event->setContext('user.current_user', $context); }
/** * {@inheritdoc} */ public function validate($items, Constraint $constraint) { if (!isset($items)) { return; } /* @var \Drupal\Core\Field\FieldItemListInterface $items */ $field = $items->getFieldDefinition(); /* @var \Drupal\user\UserInterface $account */ $account = $items->getEntity(); if (!isset($account) || !empty($account->_skipProtectedUserFieldConstraint)) { // Looks like we are validating a field not being part of a user, or the // constraint should be skipped, so do nothing. return; } // Only validate for existing entities and if this is the current user. if (!$account->isNew() && $account->id() == $this->currentUser->id()) { /* @var \Drupal\user\UserInterface $account_unchanged */ $account_unchanged = $this->userStorage->loadUnchanged($account->id()); $changed = FALSE; // Special case for the password, it being empty means that the existing // password should not be changed, ignore empty password fields. $value = $items->value; if ($field->getName() != 'pass' || !empty($value)) { // Compare the values of the field this is being validated on. $changed = $items->getValue() != $account_unchanged->get($field->getName())->getValue(); } if ($changed && !$account->checkExistingPassword($account_unchanged)) { $this->context->addViolation($constraint->message, array('%name' => $field->getLabel())); } } }
/** * {@inheritdoc} */ protected function determineBlockContext() { $current_user = $this->userStorage->load($this->account->id()); $context = new Context(new ContextDefinition('entity:user', $this->t('Current user'))); $context->setContextValue($current_user); $this->addContext('current_user', $context); }
/** * Adds in the current user as a context. * * @param \Drupal\page_manager\Event\PageManagerContextEvent $event * The page entity context event. */ public function onPageContext(PageManagerContextEvent $event) { $id = $this->account->id(); $current_user = $this->userStorage->load($id); $context = new Context(new ContextDefinition('entity:user', $this->t('Current user'))); $context->setContextValue($current_user); $event->getPageExecutable()->addContext('current_user', $context); }
/** * Adds in the current user as a context. * * @param \Drupal\page_manager\Event\PageManagerContextEvent $event * The page entity context event. */ public function onPageContext(PageManagerContextEvent $event) { $id = $this->account->id(); $current_user = $this->userStorage->load($id); $context = new Context(new ContextDefinition('entity:user', $this->t('Current user')), $current_user); $cacheability = new CacheableMetadata(); $cacheability->setCacheContexts(['user']); $context->addCacheableDependency($cacheability); $event->getPage()->addContext('current_user', $context); }
/** * {@inheritdoc} */ public function getRuntimeContexts(array $unqualified_context_ids) { $current_user = $this->userStorage->load($this->account->id()); $context = new Context(new ContextDefinition('entity:user', $this->t('Current user')), $current_user); $cacheability = new CacheableMetadata(); $cacheability->setCacheContexts(['user']); $context->addCacheableDependency($cacheability); $result = ['current_user' => $context]; return $result; }
/** * {@inheritdoc} */ public function getRuntimeContexts(array $unqualified_context_ids) { $current_user = $this->userStorage->load($this->account->id()); $context1 = new Context(new ContextDefinition('entity:user', 'User 1'), $current_user); $context2 = new Context(new ContextDefinition('entity:user', 'User 2'), $current_user); $cacheability = new CacheableMetadata(); $cacheability->setCacheContexts(['user']); $context1->addCacheableDependency($cacheability); $context2->addCacheableDependency($cacheability); return ['user1' => $context1, 'user2' => $context2]; }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $this->config('system.site')->set('name', (string) $form_state->getValue('site_name'))->set('mail', (string) $form_state->getValue('site_mail'))->save(TRUE); $this->config('system.date')->set('timezone.default', (string) $form_state->getValue('date_default_timezone'))->set('country.default', (string) $form_state->getValue('site_default_country'))->save(TRUE); $account_values = $form_state->getValue('account'); // Enable update.module if this option was selected. $update_status_module = $form_state->getValue('update_status_module'); if ($update_status_module[1]) { $this->moduleInstaller->install(array('file', 'update'), FALSE); // Add the site maintenance account's email address to the list of // addresses to be notified when updates are available, if selected. if ($update_status_module[2]) { // Reset the configuration factory so it is updated with the new module. $this->resetConfigFactory(); $this->config('update.settings')->set('notification.emails', array($account_values['mail']))->save(TRUE); } } // We precreated user 1 with placeholder values. Let's save the real values. $account = $this->userStorage->load(1); $account->init = $account->mail = $account_values['mail']; $account->roles = $account->getRoles(); $account->activate(); $account->timezone = $form_state->getValue('date_default_timezone'); $account->pass = $account_values['pass']; $account->name = $account_values['name']; $account->save(); // Record when this install ran. $this->state->set('install_time', $_SERVER['REQUEST_TIME']); }
/** * {@inheritdoc} */ public function submitForm(array &$form, array &$form_state) { $current_user_id = $this->currentUser()->id(); // Clear out the accounts from the temp store. $this->tempStoreFactory->get('user_user_operations_cancel')->delete($current_user_id); if ($form_state['values']['confirm']) { foreach ($form_state['values']['accounts'] as $uid => $value) { // Prevent programmatic form submissions from cancelling user 1. if ($uid <= 1) { continue; } // Prevent user administrators from deleting themselves without confirmation. if ($uid == $current_user_id) { $admin_form_mock = array(); $admin_form_state = $form_state; unset($admin_form_state['values']['user_cancel_confirm']); // The $user global is not a complete user entity, so load the full // entity. $account = $this->userStorage->load($uid); $admin_form = $this->entityManager->getFormObject('user', 'cancel'); $admin_form->setEntity($account); // Calling this directly required to init form object with $account. $admin_form->buildForm($admin_form_mock, $admin_form_state); $admin_form->submit($admin_form_mock, $admin_form_state); } else { user_cancel($form_state['values'], $uid, $form_state['values']['user_cancel_method']); } } } $form_state['redirect_route']['route_name'] = 'user.admin_account'; }
/** * 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', format_plural($flood_config->get('user_limit'), 'Sorry, 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>.', 'Sorry, 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>.', array('@url' => $this->url('user.pass')))); } else { // We did not find a uid, so the limit is IP-based. $form_state->setErrorByName('name', $this->t('Sorry, 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>.', array('@url' => $this->url('user.pass')))); } } else { $form_state->setErrorByName('name', $this->t('Sorry, unrecognized username or password. <a href="@password">Have you forgotten your password?</a>', array('@password' => $this->url('user.pass', [], array('query' => array('name' => $form_state->getValue('name'))))))); $accounts = $this->userStorage->loadByProperties(array('name' => $form_state->getValue('name'))); if (!empty($accounts)) { $this->logger('user')->notice('Login attempt failed for %user.', array('%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.', array('%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); } }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { if ($roles = array_filter($form_state->getValue('roles'))) { foreach ($roles as $key => $role) { $roles[$key] = $this->roleStorage->load($role)->label(); } // Authenticated role includes all users so we can ignore all other roles. $properties = []; if (!array_key_exists(AccountInterface::AUTHENTICATED_ROLE, $roles)) { $properties['roles'] = array_keys($roles); } $users = $this->userStorage->loadByProperties($properties); $exclude_myself = $form_state->getValue('exclude_myself') == '1'; $account = \Drupal::currentUser(); /** @var \Drupal\user\UserInterface $user */ foreach ($users as $user) { if ($exclude_myself && $user->id() == $account->id()) { continue; } if ($user->hasRole(AccountInterface::ANONYMOUS_ROLE)) { continue; } $user->set('field_password_expiration', '1'); $user->save(); } drupal_set_message($this->formatPlural(count($roles), 'Reset the %roles role.', 'Reset the %roles roles.', ['%roles' => implode(', ', array_values($roles))])); } else { drupal_set_message($this->t('No roles selected.'), 'warning'); } $form_state->setRedirectUrl(new Url('entity.password_policy.collection')); }
/** * {@inheritdoc} */ public function entityQueryAlter(SelectInterface $query) { // Bail out early if we do not need to match the Anonymous user. $handler_settings = $this->configuration['handler_settings']; if (isset($handler_settings['include_anonymous']) && !$handler_settings['include_anonymous']) { return; } if ($this->currentUser->hasPermission('administer users')) { // In addition, if the user is administrator, we need to make sure to // match the anonymous user, that doesn't actually have a name in the // database. $conditions =& $query->conditions(); foreach ($conditions as $key => $condition) { if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'users_field_data.name') { // Remove the condition. unset($conditions[$key]); // Re-add the condition and a condition on uid = 0 so that we end up // with a query in the form: // WHERE (name LIKE :name) OR (:anonymous_name LIKE :name AND uid = 0) $or = db_or(); $or->condition($condition['field'], $condition['value'], $condition['operator']); // Sadly, the Database layer doesn't allow us to build a condition // in the form ':placeholder = :placeholder2', because the 'field' // part of a condition is always escaped. // As a (cheap) workaround, we separately build a condition with no // field, and concatenate the field and the condition separately. $value_part = db_and(); $value_part->condition('anonymous_name', $condition['value'], $condition['operator']); $value_part->compile($this->connection, $query); $or->condition(db_and()->where(str_replace('anonymous_name', ':anonymous_name', (string) $value_part), $value_part->arguments() + array(':anonymous_name' => user_format_name($this->userStorage->load(0))))->condition('base_table.uid', 0)); $query->condition($or); } } } }
/** * Validates user, hash, and timestamp; logs the user in if correct. * * @param int $uid * User ID of the user requesting reset. * @param int $timestamp * The current timestamp. * @param string $hash * Login link hash. * * @return \Symfony\Component\HttpFoundation\RedirectResponse * Returns a redirect to the user edit form if the information is correct. * If the information is incorrect redirects to 'user.pass' route with a * message for the user. * * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException * If $uid is for a blocked user or invalid user ID. */ public function resetPassLogin($uid, $timestamp, $hash) { // The current user is not logged in, so check the parameters. $current = REQUEST_TIME; /** @var \Drupal\user\UserInterface $user */ $user = $this->userStorage->load($uid); // Verify that the user exists and is active. if ($user === NULL || !$user->isActive()) { // Blocked or invalid user ID, so deny access. The parameters will be in // the watchdog's URL for the administrator to check. throw new AccessDeniedHttpException(); } // Time out, in seconds, until login URL expires. $timeout = $this->config('user.settings')->get('password_reset_timeout'); // No time out for first time login. if ($user->getLastLoginTime() && $current - $timestamp > $timeout) { drupal_set_message($this->t('You have tried to use a one-time login link that has expired. Please request a new one using the form below.'), 'error'); return $this->redirect('user.pass'); } elseif ($user->isAuthenticated() && $timestamp >= $user->getLastLoginTime() && $timestamp <= $current && Crypt::hashEquals($hash, user_pass_rehash($user, $timestamp))) { user_login_finalize($user); $this->logger->notice('User %name used one-time login link at time %timestamp.', ['%name' => $user->getDisplayName(), '%timestamp' => $timestamp]); drupal_set_message($this->t('You have just used your one-time login link. It is no longer necessary to use this link to log in. Please change your password.')); // Let the user's password be changed without the current password // check. $token = Crypt::randomBytesBase64(55); $_SESSION['pass_reset_' . $user->id()] = $token; return $this->redirect('entity.user.edit_form', ['user' => $user->id()], ['query' => ['pass-reset-token' => $token], 'absolute' => TRUE]); } drupal_set_message($this->t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.'), 'error'); return $this->redirect('user.pass'); }
/** * @covers ::getOwner * * @depends testGetOwnerId */ public function testGetOwner() { $owner = $this->getMock(UserInterface::class); $id = mt_rand(); $this->userStorage->expects($this->atLeastOnce())->method('load')->with($id)->willReturn($owner); $this->sut->setOwnerId($id); $this->assertSame($owner, $this->sut->getOwner()); }
/** * Returns the user password reset page. * * @param int $uid * UID of user requesting reset. * @param int $timestamp * The current timestamp. * @param string $hash * Login link hash. * * @return array|\Symfony\Component\HttpFoundation\RedirectResponse * The form structure or a redirect response. * * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException * If the login link is for a blocked user or invalid user ID. */ public function resetPass($uid, $timestamp, $hash) { $account = $this->currentUser(); $config = $this->config('user.settings'); // When processing the one-time login link, we have to make sure that a user // isn't already logged in. if ($account->isAuthenticated()) { // The current user is already logged in. if ($account->id() == $uid) { drupal_set_message($this->t('You are logged in as %user. <a href="!user_edit">Change your password.</a>', array('%user' => $account->getUsername(), '!user_edit' => $this->url('user.edit', array('user' => $account->id()))))); } else { if ($reset_link_user = $this->userStorage->load($uid)) { drupal_set_message($this->t('Another user (%other_user) is already logged into the site on this computer, but you tried to use a one-time link for user %resetting_user. Please <a href="!logout">logout</a> and try using the link again.', array('%other_user' => $account->getUsername(), '%resetting_user' => $reset_link_user->getUsername(), '!logout' => $this->url('user.logout')))); } else { // Invalid one-time link specifies an unknown user. drupal_set_message($this->t('The one-time login link you clicked is invalid.')); } } return $this->redirect('<front>'); } else { // The current user is not logged in, so check the parameters. // Time out, in seconds, until login URL expires. $timeout = $config->get('password_reset_timeout'); $current = REQUEST_TIME; /* @var \Drupal\user\UserInterface $user */ $user = $this->userStorage->load($uid); // Verify that the user exists and is active. if ($user && $user->isActive()) { // No time out for first time login. if ($user->getLastLoginTime() && $current - $timestamp > $timeout) { drupal_set_message($this->t('You have tried to use a one-time login link that has expired. Please request a new one using the form below.')); return $this->redirect('user.pass'); } elseif ($user->isAuthenticated() && $timestamp >= $user->getLastLoginTime() && $timestamp <= $current && $hash === user_pass_rehash($user->getPassword(), $timestamp, $user->getLastLoginTime())) { $expiration_date = $user->getLastLoginTime() ? $this->dateFormatter->format($timestamp + $timeout) : NULL; return $this->formBuilder()->getForm('Drupal\\user\\Form\\UserPasswordResetForm', $user, $expiration_date, $timestamp, $hash); } else { drupal_set_message($this->t('You have tried to use a one-time login link that has either been used or is no longer valid. Please request a new one using the form below.')); return $this->redirect('user.pass'); } } } // Blocked or invalid user ID, so deny access. The parameters will be in the // watchdog's URL for the administrator to check. throw new AccessDeniedHttpException(); }
/** * Displays details about a specific database log message. * * @param int $event_id * Unique ID of the database log message. * * @return array * If the ID is located in the Database Logging table, a build array in the * format expected by drupal_render(); * */ public function eventDetails($event_id) { $build = array(); if ($dblog = $this->database->query('SELECT w.*, u.uid FROM {watchdog} w LEFT JOIN {users} u ON u.uid = w.uid WHERE w.wid = :id', array(':id' => $event_id))->fetchObject()) { $severity = RfcLogLevel::getLevels(); $message = $this->formatMessage($dblog); $username = array('#theme' => 'username', '#account' => $dblog->uid ? $this->userStorage->load($dblog->uid) : User::getAnonymousUser()); $rows = array(array(array('data' => $this->t('Type'), 'header' => TRUE), $this->t($dblog->type)), array(array('data' => $this->t('Date'), 'header' => TRUE), $this->dateFormatter->format($dblog->timestamp, 'long')), array(array('data' => $this->t('User'), 'header' => TRUE), array('data' => $username)), array(array('data' => $this->t('Location'), 'header' => TRUE), $this->l($dblog->location, $dblog->location ? Url::fromUri($dblog->location) : Url::fromRoute('<none>'))), array(array('data' => $this->t('Referrer'), 'header' => TRUE), $this->l($dblog->referer, $dblog->referer ? Url::fromUri($dblog->referer) : Url::fromRoute('<none>'))), array(array('data' => $this->t('Message'), 'header' => TRUE), $message), array(array('data' => $this->t('Severity'), 'header' => TRUE), $severity[$dblog->severity]), array(array('data' => $this->t('Hostname'), 'header' => TRUE), SafeMarkup::checkPlain($dblog->hostname)), array(array('data' => $this->t('Operations'), 'header' => TRUE), SafeMarkup::checkAdminXss($dblog->link))); $build['dblog_table'] = array('#type' => 'table', '#rows' => $rows, '#attributes' => array('class' => array('dblog-event')), '#attached' => array('library' => array('dblog/drupal.dblog'))); } return $build; }
/** * {@inheritdoc} */ public function validateForm(array &$form, FormStateInterface $form_state) { $name = trim($form_state->getValue('name')); // Try to load by email. $users = $this->userStorage->loadByProperties(array('mail' => $name)); if (empty($users)) { // No success, try to load by name. $users = $this->userStorage->loadByProperties(array('name' => $name)); } $account = reset($users); if ($account && $account->id()) { // Blocked accounts cannot request a new password. if (!$account->isActive()) { $form_state->setErrorByName('name', $this->t('%name is blocked or has not been activated yet.', array('%name' => $name))); } else { $form_state->setValueForElement(array('#parents' => array('account')), $account); } } else { $form_state->setErrorByName('name', $this->t('%name is not recognized as a username or an email address.', array('%name' => $name))); } }
/** * {@inheritdoc} */ public function validate($entity, Constraint $constraint) { $author_name = $entity->name->value; $owner_id = (int) $entity->uid->target_id; // Do not allow unauthenticated comment authors to use a name that is // taken by a registered user. if (isset($author_name) && $author_name !== '' && $owner_id === 0) { $users = $this->userStorage->loadByProperties(array('name' => $author_name)); if (!empty($users)) { $this->context->buildViolation($constraint->messageNameTaken, array('%name' => $author_name))->atPath('name')->addViolation(); } } elseif (isset($author_name) && $author_name !== '' && $owner_id) { $owner = $this->userStorage->load($owner_id); if ($owner->getUsername() != $author_name) { $this->context->buildViolation($constraint->messageMatch)->atPath('name')->addViolation(); } } // Anonymous account might be required - depending on field settings. if ($owner_id === 0 && empty($author_name) && $this->getAnonymousContactDetailsSetting($entity) === COMMENT_ANONYMOUS_MUST_CONTACT) { $this->context->buildViolation($constraint->messageRequired)->atPath('name')->addViolation(); } }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $roles = $form_state->getValue('roles'); $role_names = []; foreach ($roles as $role) { if ($role_obj = $this->role_storage->load($role)) { $role_names[] = $role_obj->label(); } else { $role_names[] = $role; } $users = $this->user_storage->loadByProperties(['roles' => $role]); foreach ($users as $user) { if ($form_state->getValue('exclude_myself') == '1' and $user->id() == \Drupal::currentUser()->id()) { continue; } $user->set('field_password_expiration', '1'); $user->save(); } } drupal_set_message($this->t('Reset the %roles roles.', array('%roles' => implode(', ', $role_names)))); $form_state->setRedirectUrl(new Url('entity.password_policy.collection')); }
protected function setUp($import_test_views = TRUE) { parent::setUp($import_test_views); ViewTestData::createTestViews(get_class($this), ['comment_test_views']); $this->installEntitySchema('user'); $this->installEntitySchema('comment'); $this->installConfig(['user']); $entity_manager = $this->container->get('entity.manager'); $this->commentStorage = $entity_manager->getStorage('comment'); $this->userStorage = $entity_manager->getStorage('user'); // Insert a row for the anonymous user. $this->userStorage->create(['uid' => 0, 'name' => '', 'status' => 0])->save(); $admin_role = Role::create(['id' => 'admin']); $admin_role->grantPermission('administer comments'); $admin_role->save(); /* @var \Drupal\user\RoleInterface $anonymous_role */ $anonymous_role = Role::load(Role::ANONYMOUS_ID); $anonymous_role->grantPermission('access comments'); $anonymous_role->save(); $this->adminUser = $this->userStorage->create(['name' => $this->randomMachineName()]); $this->adminUser->addRole('admin'); $this->adminUser->save(); }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { $account_values = $form_state->getValue('account'); // We precreated user 1 with placeholder values. Let's save the real values. $account = $this->userStorage->load(1); $account->init = $account->mail = $account_values['mail']; $account->roles = $account->getRoles(); $account->activate(); $account->timezone = $form_state->getValue('date_default_timezone'); $account->pass = $account_values['pass']; $account->name = $account_values['name']; $account->save(); // Record when this install ran. $this->state->set('install_time', $_SERVER['REQUEST_TIME']); }
/** * {@inheritdoc} */ public function validateForm(array &$form, FormStateInterface $form_state) { $name = trim($form_state->getValue('name')); // Try to load by email. $users = $this->userStorage->loadByProperties(array('mail' => $name, 'status' => '1')); if (empty($users)) { // No success, try to load by name. $users = $this->userStorage->loadByProperties(array('name' => $name, 'status' => '1')); } $account = reset($users); if ($account && $account->id()) { $form_state->setValueForElement(array('#parents' => array('account')), $account); } else { $form_state->setErrorByName('name', $this->t('Sorry, %name is not recognized as a username or an email address.', array('%name' => $name))); } }
/** * {@inheritdoc} */ public function validateForm(array &$form, array &$form_state) { $name = trim($form_state['values']['name']); // Try to load by email. $users = $this->userStorage->loadByProperties(array('mail' => $name, 'status' => '1')); if (empty($users)) { // No success, try to load by name. $users = $this->userStorage->loadByProperties(array('name' => $name, 'status' => '1')); } $account = reset($users); if ($account && $account->id()) { form_set_value(array('#parents' => array('account')), $account, $form_state); } else { $this->setFormError('name', $form_state, $this->t('Sorry, %name is not recognized as a username or an email address.', array('%name' => $name))); } }
/** * Gets the login identifier for user login flood control. * * @param \Symfony\Component\HttpFoundation\Request $request * The current request. * @param string $username * The username supplied in login credentials. * * @return string * The login identifier or if the user does not exist an empty string. */ protected function getLoginFloodIdentifier(Request $request, $username) { $flood_config = $this->config('user.flood'); $accounts = $this->userStorage->loadByProperties(['name' => $username, 'status' => 1]); if ($account = reset($accounts)) { 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() . '-' . $request->getClientIp(); } return $identifier; } return ''; }
/** * 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>.', array(':url' => $this->url('user.pass')))); } 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>.', array(':url' => $this->url('user.pass')))); } } 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']) ? array('name' => $user_input['name']) : array(); $form_state->setErrorByName('name', $this->t('Unrecognized username or password. <a href=":password">Have you forgotten your password?</a>', array(':password' => $this->url('user.pass', [], array('query' => $query))))); $accounts = $this->userStorage->loadByProperties(array('name' => $form_state->getValue('name'))); if (!empty($accounts)) { $this->logger('user')->notice('Login attempt failed for %user.', array('%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.', array('%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); } }