Handle a login request.

@param Request $request

@return mixed
500679
public function postLogin(Request $request)
    {
        $credentials = $request->only([$this->username(), 'password']);

        /** @var \Illuminate\Validation\Validator $validator */
        $validator = Validator::make($credentials, [
            $this->username()   => 'required',
            'password'          => 'required',
        ]);

        if ($validator->fails()) {
            return back()->withInput()->withErrors($validator);
        }

        if ($this->guard()->attempt($credentials)) {
            return $this->sendLoginResponse($request);
        }

        return back()->withInput()->withErrors([
            $this->username() => $this->getFailedLoginMessage(),
        ]);
    }
161700
protected function sendFailedLoginResponse(Request $request)
    {
        $credentials = $this->credentials($request);

        $user = User::where('email', $credentials['email'])->first();
        if (!$user) {
            $error = __('This user was not found.');
        } elseif (!$user->activated) {
            $error = __('This user is not activated.');
        } else {
            $error = __('The password is incorrect.');
        }

        $errors = [$this->username() => $error];

        if ($request->expectsJson()) {
            return response()->json($errors, 422);
        }

        return redirect()->back()
            ->withInput($request->only($this->username(), 'remember'))
            ->withErrors($errors);
    }
1138168
public function login(AuthenticationRequest $request)
    {
        // Prepare variables
        $loginField = get_login_field($request->input($this->username()));
        $credentials = [
            'is_active' => true,
            $loginField => $request->input('loginfield'),
            'password' => $request->input('password'),
        ];

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        if (auth()->guard($this->getGuard())->attempt($credentials, $request->filled('remember'))) {
            return $this->sendLoginResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }
603784
public function postLogout (Request $request)
    {
        if ($redirect = $request->getSession ()->get ('post-login-redirect'))
        {
            $request->getSession ()->set ('post-login-redirect', null);
            $request->getSession ()->set ('cancel-login-redirect', null);

            return Response::redirect ($redirect);
        }

        return Response::redirect (URLBuilder::getURL ('/'));
    }
1331174
public function run(Request $request) {
		$page = $this->getServiceContainer()->getKernel()->getApplication()->getPage();
		$page->setTitle($this->getServiceContainer()->getTranslator()->trans('change_password'));

		$payload = new Blank();
		if ($request->isMethod('POST')) {
			$post = $request->request;
			$auth = $this->getServiceContainer()->getAuthManager();
			$user = $auth->getUser();
			$payload = new Failed();

			if ($post->has('password') && $auth->verifyUser($user, $post->get('password'))) {
				$pwA = $post->get('new_password');
				$pwB = $post->get('new_password_confirm');

				if ($pwA == $pwB) {
					$user->setPassword($auth->encryptPassword($pwA));
					$user->save();
					$payload = new Success();
				}
			}
		}

		return $this->responder->run($request, $payload);
	}
1074079
public function authenticate(Request $request)
    {
        $email    = $request->input(self::AUTH_PARAM_EMAIL, null);
        $password = $request->input(self::AUTH_PARAM_PASSWORD, null);

        if ($email !== null &&
            $password !== null &&
            ($user = User::query()->where(User::FIELD_EMAIL, '=', strtolower($email))->first()) !== null
        ) {
            /** @var HasherInterface $hasher */
            $hasher = app(HasherInterface::class);
            if ($hasher->check($password, $user->{User::FIELD_PASSWORD_HASH}) === true) {
                /** @var TokenCodecInterface $codec */
                $codec = app(TokenCodecInterface::class);
                $token = $codec->encode($user);

                $this->getLogger()->debug(
                    'Account login success.',
                    [User::FIELD_EMAIL => $email, User::FIELD_ID => $user->getKey()]
                );

                return response($token);
            }
        }

        $this->getLogger()->debug('Account login failed.', [User::FIELD_EMAIL => $email]);

        return response(null, Response::HTTP_UNAUTHORIZED);
    }
352123
public function handle(Request $request)
	{
		$response = $this->next($request);

		if ($content = $response->original)
		{
			$content = $this->traverse($request, $content);

			$response->setContent($content);
		}

		return $response;
	}
324973
public function store(Request $request)
    {
        try {
            $this->dispatch(new AttemptUserLogin($request->get('email'), $request->get('password'), $request->get('remember')));
            return redirect()->intended($this->config->get('authentication.login.redirectUri'));
        } catch (LoginFailed $e) {
            return redirect()->back()->withInput()->withErrors([
                'authentication::login_error' => $e->getMessage()
            ]);
        } catch (UserIsBanned $e) {
            return redirect()->back()->withInput()->withErrors([
                'authentication::login_error' => $e->getMessage()
            ]);
        }
    }
864900
protected function sendLoginResponse(Request $request)
    {
        $user = auth()->guard($this->getGuard())->user();

        $twofactor = $user->getTwoFactor();
        $totpStatus = $twofactor['totp']['enabled'] ?? false;
        $phoneStatus = $twofactor['phone']['enabled'] ?? false;

        $request->session()->regenerate();
        $this->clearLoginAttempts($request);

        // Enforce TwoFactor authentication
        if ($totpStatus || $phoneStatus) {
            $this->processLogout($request);

            $request->session()->put('cortex.auth.twofactor', ['user_id' => $user->getKey(), 'remember' => $request->filled('remember'), 'totp' => $totpStatus, 'phone' => $phoneStatus]);

            $route = $totpStatus
                ? route('adminarea.verification.phone.verify')
                : route('adminarea.verification.phone.request');

            return intend([
                'url' => $route,
                'with' => ['warning' => trans('cortex/auth::messages.verification.twofactor.totp.required')],
            ]);
        }

        return intend([
            'intended' => route('adminarea.home'),
            'with' => ['success' => trans('cortex/auth::messages.auth.login')],
        ]);
    }
189321
public function handle(Request $request)
	{
		// Get response
		$response = $this->next($request);

		// Get authentication
		$token = $this->app['auth']->token();

		// Rate limit application/user id and get data
		$rateLimitData = $this->app['ratelimiter']->rateLimit($token['application_id'], $token['uidNumber']);

		// Calculate header values
		$limit     = $rateLimitData->limit_short;
		$remaining = $rateLimitData->limit_short - $rateLimitData->count_short;
		$reset     = with(new Date($rateLimitData->expires_short))->toUnix();

		// If we exceeded out rate limit lets respond accordingly
		if ($rateLimitData->exceeded_long || $rateLimitData->exceeded_short)
		{
			throw new \Exception('You have exceeded your rate limit allowance. Please see rate limit headers for details.', 429);

			// Use different values for long
			if ($rateLimitData->exceeded_long)
			{
				$limit = $rateLimitData->limit_long;
				$reset = with(new Date($rateLimitData->expires_long))->toUnix();
			}

			// Always 0 if exceeded
			$remaining = 0;
		}

		// Add rate limit headers
		$response->headers->set('X-RateLimit-Limit', $limit);
		$response->headers->set('X-RateLimit-Remaining', $remaining);
		$response->headers->set('X-RateLimit-Reset', $reset);

		// Return response
		return $response;
	}
846650
protected function _cookieLogin(Request $request)
    {
        $controller = $this->_registry->getController();
        if (empty($controller->Cookie)) {
            $controller->loadComponent('Cookie');
        }

        $cookie = $controller->Cookie->read('User.Cookie');
        if ($cookie) {
            $cookie = json_decode($cookie, true);
            if (isset($cookie['user']) &&
                isset($cookie['hash']) &&
                $cookie['hash'] == Security::hash($cookie['user'], 'sha1', true)
            ) {
                $cookie['user'] = json_decode($cookie['user'], true);
                $user = $this->_findUser($cookie['user']['username']);
                if (!empty($user) && is_array($user)) {
                    if (isset($user['password'])) {
                        unset($user['password']);
                    }
                    $controller->Auth->setUser($user);

                    return true;
                }
            }
        }

        $cacheKey = 'permissions_anonymous';
        $permissions = Cache::read($cacheKey, 'permissions');
        $action = $this->action($request);

        if ($permissions === false) {
            $permissions = $this->_rolePermissions(ROLE_ID_ANONYMOUS);
            Cache::write($cacheKey, $permissions, 'permissions');
        }

        if (isset($permissions[$action])) {
            return true;
        }

        return false;
    }
427349
public function login(Request $request)
    {
        $data = $request->getParsedBody();
        $this->checkingRequirements($data);

        /** @var UserPasswordInterface $user */
        if (null === $user = $this->findByUsername($data['username'])) {
            $this->logger->warning(
                'security.authentication.form: user not found with criteria {criteria}',
                ['criteria' => $this->getCriteriaAsSting(['username' => $data['username']])]
            );

            throw UserNotFoundException::create(['username' => $data['username']]);
        }

        if (!$this->passwordManager->verify($data['password'], $user->getPassword())) {
            $this->logger->warning(
                'security.authentication.form: invalid password for user with criteria {criteria}',
                ['criteria' => $this->getCriteriaAsSting(['username' => $data['username']])]
            );

            throw InvalidPasswordException::create(['username' => $data['username']]);
        }

        $this->logger->info(
            'security.authentication.form: login successful for user with id {id}', ['id' => $user->getId()]
        );

        $this->session->set($request, self::USER_KEY, $user->getId());
    }
442974
public function login(Request $request)
    {
        $this->validate($request, [
            'email'    => 'required|max:255',
            'password' => 'required|max:255',
        ]);

        if (Auth::attempt(['email' => $request->email, 'password' => $request->password], $request->remember ? true : false)) {
            return redirect()->intended(route('laralum::index'));
        }

        return redirect()->route('laralum::login')->with('error', trans('auth.failed'))->withInput();
    }
1086742
public function login(Request $request)
    {
        $form = $this->form(new LoginForm());
        $form->handleRequest($request);

        if ($form->isValid()) {
            if ($this->attemptLogin($request, $form)) {
                return $this->sendLoginResponse($request);
            }
        }

        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }

        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        $this->incrementLoginAttempts($request);

        $this->sendFailedLoginResponse($request);
    }
889255
public function authentication(Request $request)
    {
        try {
            $this->authRepositoryInterface->authenticate($request->all());
        } catch (FormValidationException $e) {
            Flash::error($e->getMessage());

            return redirect()
              ->route('auth.login')
              ->withErrors($e->getErrors());
        } catch (AuthenticationException $e) {
            Flash::error($e->getMessage());

            return redirect()->route('auth.login');
        }

        return redirect()->route('dashboard.index');
    }
1132904
public function authenticateAction(Request $request) {
        $data = $request->request->all();
        try {
            $data = $this->getAuthCredentials($request);
            $this->info('> Authenticate request', ['method' => $request->getMethod(), 'query' => $data]);
            // exports $client_id, $redirect_uri, $username and $password
            extract($data);

            $accessCredentials = $this->accessProvider->generate($request, $client_id, $redirect_uri, $username, $password);
            $response = new RedirectResponse($redirect_uri . '?code=' . $accessCredentials->getAuthCode());
        }catch (BadDataException $e) {
            $data['errors'] = $e->getErrors();
            $this->error('Bad Data Exception: ' . $e->getMessage(), ['errors' => $data['errors'], 'exception' => $e]);
            $response = $this->getBadFormRequestResponse($data);
        } catch (SoauthException $e) {
            $this->error('Soauth Exception: ' . $e->getMessage(), ['exception' => $e]);
            $response = $this->getBadFormRequestResponse($data);
        }

        $this->info('< Response', ['status_code' => $response->getStatusCode(), 'target' => $response instanceOf RedirectResponse ? $response->getTargetUrl() : null]);
        return $response;
    }
721789
private function sendLoginResponse(Request $request)
    {
        $user = user();

        // notify message
        if ($user->getAttribute('logged_in_at')) {
            notify()->info('Info',
                'Last time you logged in was ' . $user->logged_in_at->diffForHumans(),
                'clock-o rotateIn animated', 8000);
        }
        else {
            notify()->info('Welcome',
                'Hi ' . $user->fullname . '. Welcome to ' . config('app.name'),
                'bell swing animated', 8000);
        }

        // log
        $this->logLogin($request, 'success');

        // update logged_in_at
        $user->update(['logged_in_at' => Carbon::now()]);

        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        log_activity('Login', $user->fullname . ' logged in.');

        // if admin - go to admin - else website
        $url = $user->hasRole('admin') ? "/admin" : "/";

        // if ajax (can be from a login modal)
        if (request()->ajax()) {
            return json_response(['redirect' => config('app.url') . $url]);
        }

        return redirect()->intended($url);
    }