/** * 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); } }
/** * Logs in a user. * * @param \Symfony\Component\HttpFoundation\Request $request * The request. * * @return \Symfony\Component\HttpFoundation\Response * A response which contains the ID and CSRF token. */ public function login(Request $request) { $format = $this->getRequestFormat($request); $content = $request->getContent(); $credentials = $this->serializer->decode($content, $format); if (!isset($credentials['name']) && !isset($credentials['pass'])) { throw new BadRequestHttpException('Missing credentials.'); } if (!isset($credentials['name'])) { throw new BadRequestHttpException('Missing credentials.name.'); } if (!isset($credentials['pass'])) { throw new BadRequestHttpException('Missing credentials.pass.'); } $this->floodControl($request, $credentials['name']); if ($this->userIsBlocked($credentials['name'])) { throw new BadRequestHttpException('The user has not been activated or is blocked.'); } if ($uid = $this->userAuth->authenticate($credentials['name'], $credentials['pass'])) { $this->flood->clear('user.http_login', $this->getLoginFloodIdentifier($request, $credentials['name'])); /** @var \Drupal\user\UserInterface $user */ $user = $this->userStorage->load($uid); $this->userLoginFinalize($user); // Send basic metadata about the logged in user. $response_data = []; if ($user->get('uid')->access('view', $user)) { $response_data['current_user']['uid'] = $user->id(); } if ($user->get('roles')->access('view', $user)) { $response_data['current_user']['roles'] = $user->getRoles(); } if ($user->get('name')->access('view', $user)) { $response_data['current_user']['name'] = $user->getAccountName(); } $response_data['csrf_token'] = $this->csrfToken->get('rest'); $logout_route = $this->routeProvider->getRouteByName('user.logout.http'); // Trim '/' off path to match \Drupal\Core\Access\CsrfAccessCheck. $logout_path = ltrim($logout_route->getPath(), '/'); $response_data['logout_token'] = $this->csrfToken->get($logout_path); $encoded_response_data = $this->serializer->encode($response_data, $format); return new Response($encoded_response_data); } $flood_config = $this->config('user.flood'); if ($identifier = $this->getLoginFloodIdentifier($request, $credentials['name'])) { $this->flood->register('user.http_login', $flood_config->get('user_window'), $identifier); } // Always register an IP-based failed login event. $this->flood->register('user.failed_login_ip', $flood_config->get('ip_window')); throw new BadRequestHttpException('Sorry, unrecognized username or password.'); }
/** * {@inheritdoc} */ public function authenticate(Request $request) { $flood_config = $this->configFactory->get('user.flood'); $username = $request->headers->get('PHP_AUTH_USER'); $password = $request->headers->get('PHP_AUTH_PW'); // Flood protection: this is very similar to the user login form code. // @see \Drupal\user\Form\UserLoginForm::validateAuthentication() // 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('basic_auth.failed_login_ip', $flood_config->get('ip_limit'), $flood_config->get('ip_window'))) { $accounts = $this->entityManager->getStorage('user')->loadByProperties(array('name' => $username, '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() . '-' . $request->getClientIP(); } // 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('basic_auth.failed_login_user', $flood_config->get('user_limit'), $flood_config->get('user_window'), $identifier)) { $uid = $this->userAuth->authenticate($username, $password); if ($uid) { $this->flood->clear('basic_auth.failed_login_user', $identifier); return $this->entityManager->getStorage('user')->load($uid); } else { // Register a per-user failed login event. $this->flood->register('basic_auth.failed_login_user', $flood_config->get('user_window'), $identifier); } } } } // Always register an IP-based failed login event. $this->flood->register('basic_auth.failed_login_ip', $flood_config->get('ip_window')); 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); } }