Login or check the user credentials.

@param ServerRequestInterface $request
@param string|null            $username

@return bool
359711
private function login(ServerRequestInterface $request, &$username)
    {
        //Check header
        $authorization = self::parseAuthorizationHeader($request->getHeaderLine('Authorization'));

        if (!$authorization) {
            return false;
        }

        //Check whether user exists
        if (!isset($this->users[$authorization['username']])) {
            return false;
        }

        $username = $authorization['username'];

        //Check authentication
        return $this->checkAuthentication($authorization, $request->getMethod(), $this->users[$username]);
    }
203369
public function getAuthenticatedUser(Request $request)
    {
        foreach ($this->authentications as $authentication) {
            if (null !== $user = $authentication->getAuthenticatedUser($request)) {
                return $user;
            }
        }

        return null;
    }
1365221
public function checkFailures($username, Request $request)
    {
        $failures = $this->repository->findLockedFailuresMatching($username, $request->getClientIp());

        if (0 === count($failures)) {
            return $this;
        }

        if ($this->trials < count($failures) && $this->captcha->isSetup()) {
            $response = $this->captcha->bind($request);

            if (!$response->isValid()) {
                throw new RequireCaptchaException('Too many failures, require captcha');
            }

            foreach ($failures as $failure) {
                $failure->setLocked(false);
            }

            $this->em->flush($failures);
        }

        return $this;
    }
85580
public function getUser(ServerRequest $request)
    {
        $digest = $this->_getDigest($request);
        if (empty($digest)) {
            return false;
        }

        $user = $this->_findUser($digest['username']);
        if (empty($user)) {
            return false;
        }

        if (!$this->validNonce($digest['nonce'])) {
            return false;
        }

        $field = $this->_config['fields']['password'];
        $password = $user[$field];
        unset($user[$field]);

        $hash = $this->generateResponseHash($digest, $password, $request->getEnv('ORIGINAL_REQUEST_METHOD'));
        if (hash_equals($hash, $digest['response'])) {
            return $user;
        }

        return false;
    }
13280
public function autoLogin($username)
    {
        $this->loadCookiesFor($username);

        if (!$this->httpClient->cookie('_auth')) {
            return false;
        }

        $this->login();

        return true;
    }
161590
protected function getUser(Request $request)
    {
        // find the user
        $user = $this->userRepository->findOneByUsername($request->headers->get('username'));
        if (!$user) {
            throw new BadUserCredentialsHttpException();
        }

        // Check the validity of the password
        $encoder = $this->encoderFactory->getEncoder($user);
        if (!$encoder->isPasswordValid($user->getPassword(), $request->headers->get('password'), $user->getSalt())) {
            throw new BadUserCredentialsHttpException();
        }

        return $user;
    }
60140
private function attemptSwitchUser(Request $request, $username)
    {
        $token = $this->tokenStorage->getToken();
        $originalToken = $this->getOriginalToken($token);

        if (null !== $originalToken) {
            if ($token->getUsername() === $username) {
                return $token;
            }

            throw new \LogicException(sprintf('You are already switched to "%s" user.', $token->getUsername()));
        }

        $user = $this->provider->loadUserByUsername($username);

        if (false === $this->accessDecisionManager->decide($token, [$this->role], $user)) {
            $exception = new AccessDeniedException();
            $exception->setAttributes($this->role);

            throw $exception;
        }

        if (null !== $this->logger) {
            $this->logger->info('Attempting to switch to user.', ['username' => $username]);
        }

        $this->userChecker->checkPostAuth($user);

        $roles = $user->getRoles();
        $roles[] = new SwitchUserRole('ROLE_PREVIOUS_ADMIN', $this->tokenStorage->getToken(), false);

        $token = new SwitchUserToken($user, $user->getPassword(), $this->providerKey, $roles, $token);

        if (null !== $this->dispatcher) {
            $switchEvent = new SwitchUserEvent($request, $token->getUser(), $token);
            $this->dispatcher->dispatch($switchEvent, SecurityEvents::SWITCH_USER);
            // use the token from the event in case any listeners have replaced it.
            $token = $switchEvent->getToken();
        }

        return $token;
    }
725034
protected function loginHeaders(ServerRequestInterface $request)
    {
        $server = $request->getServerParams();
        $realm = $this->_config['realm'] ?: $server['SERVER_NAME'];

        $options = [
            'realm' => $realm,
            'qop' => $this->_config['qop'],
            'nonce' => $this->generateNonce(),
            'opaque' => $this->_config['opaque'] ?: md5($realm)
        ];

        $digest = $this->_getDigest($request);
        if ($digest !== null && isset($digest['nonce']) && !$this->validNonce($digest['nonce'])) {
            $options['stale'] = true;
        }

        $opts = [];
        foreach ($options as $k => $v) {
            if (is_bool($v)) {
                $v = $v ? 'true' : 'false';
                $opts[] = sprintf('%s=%s', $k, $v);
            } else {
                $opts[] = sprintf('%s="%s"', $k, $v);
            }
        }

        return ['WWW-Authenticate' => 'Digest ' . implode(',', $opts)];
    }
1031176
protected function authenticateUser(Request $request, UserInterface $user, $resourceOwnerName, $accessToken, $fakeLogin = true)
    {
        try {
            $this->container->get('hwi_oauth.user_checker')->checkPreAuth($user);
            $this->container->get('hwi_oauth.user_checker')->checkPostAuth($user);
        } catch (AccountStatusException $e) {
            // Don't authenticate locked, disabled or expired users
            return;
        }

        $token = new OAuthToken($accessToken, $user->getRoles());
        $token->setResourceOwnerName($resourceOwnerName);
        $token->setUser($user);
        $token->setAuthenticated(true);

        $this->get('security.token_storage')->setToken($token);

        if ($fakeLogin) {
            // Since we're "faking" normal login, we need to throw our INTERACTIVE_LOGIN event manually
            $this->container->get('event_dispatcher')->dispatch(
                SecurityEvents::INTERACTIVE_LOGIN,
                new InteractiveLoginEvent($request, $token)
            );
        }
    }
56210
public function authenticate($username, $password)
    {
        try {
            $user = $this->userProvider->loadUserByUsername($username);
        } catch (UsernameNotFoundException $e) {
            return null;
        }

        $valid = $this->encoderFactory->getEncoder($user)->isPasswordValid(
            $user->getPassword(),
            $password,
            $user->getSalt()
        );

        if ($valid) {
            return $user;
        }

        return null;
    }
992678
public function login(Request $request)
    {
        $this->validate($request, [
            $this->username() => 'required|string|email|max:240',
            'password'        => 'required|string|min:4|max:240',
        ]);

        // 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);
        }

        // make sure the account has been activated
        if (!User::where($this->username(), input($this->username()))
            ->whereNotNull('confirmed_at')
            ->first()) {
            $this->logLogin($request, 'inactive');

            return $this->sendFailedLoginResponse($request,
                'Please activate your account before trying to login.');
        }

        // try to login
        if (Auth::attempt($request->only([$this->username(), 'password']),
            input('remember', false))) {
            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);

        $this->logLogin($request, 'invalid');

        return $this->sendFailedLoginResponse($request);
    }
1265906
final public function autoLogin(Request $request): ?TokenInterface
    {
        if (null === $cookie = $request->cookies->get($this->options['name'])) {
            return null;
        }

        if (null !== $this->logger) {
            $this->logger->debug('Remember-me cookie detected.');
        }

        $cookieParts = $this->decodeCookie($cookie);

        try {
            $user = $this->processAutoLoginCookie($cookieParts, $request);

            if (!$user instanceof UserInterface) {
                throw new \RuntimeException('processAutoLoginCookie() must return a UserInterface implementation.');
            }

            if (null !== $this->logger) {
                $this->logger->info('Remember-me cookie accepted.');
            }

            return new RememberMeToken($user, $this->providerKey, $this->secret);
        } catch (CookieTheftException $e) {
            $this->loginFail($request, $e);

            throw $e;
        } catch (UsernameNotFoundException $e) {
            if (null !== $this->logger) {
                $this->logger->info('User for remember-me cookie not found.', ['exception' => $e]);
            }

            $this->loginFail($request, $e);
        } catch (UnsupportedUserException $e) {
            if (null !== $this->logger) {
                $this->logger->warning('User class for remember-me cookie not supported.', ['exception' => $e]);
            }

            $this->loginFail($request, $e);
        } catch (AuthenticationException $e) {
            if (null !== $this->logger) {
                $this->logger->debug('Remember-Me authentication failed.', ['exception' => $e]);
            }

            $this->loginFail($request, $e);
        } catch (\Exception $e) {
            $this->loginFail($request, $e);

            throw $e;
        }

        return null;
    }
219089
private function authBasic(Request $request) {
		$user = $this->findUser($request->getUser());
		if ($user !== null && $this->verifyUser($user, $request->getPassword())) {
			$session = $this->findSession($user);
			if ($session === null) {
				$session = $this->createSession($user);
			}
			$this->authenticated = true;

			return $session;
		}
		return null;
	}
198023
public function isOAuthAuthenticated(ServerRequestInterface $request)
    {
        $queryParams = $request->getQueryParams();
        $code = $queryParams[GoogleClient::KEY_CODE] ?? null;
        $state = $queryParams[GoogleClient::KEY_STATE] ?? null;

        $this->logger->debug(
            json_encode(
                [
                    'Incoming authorization code: ' . $code,
                    'Incoming state: ' . $state,
                    'Redirect uri: ' . $this->getConfig('redirectUri'),
                ]
            )
        );

        if ($this->getSession($request)->get(GoogleClient::KEY_STATE) != $state) {
            $this->logger->debug("Invalid incoming state");

            return false;
        }

        if (!$this->googleClient->authenticateWithAuthCode($code)) {
            $this->logger->debug("Authentication with authorization code failed");

            return false;
        }

        return true;
    }
736035
public function log(RequestInterface $request = null, User $user = null)
    {
        if ($request === null) {
            $request = ServerRequest::fromGlobals();
        }

        if ($user === null) {
            $user = \common_session_SessionManager::getSession()->getUser();
        }
       return  $this->getStorage()->log($request, $user);
    }
480032
private function isValid(ServerRequestInterface $request)
    {
        $data = $request->getParsedBody();

        return isset($data[$this->inputName]) && $data[$this->inputName] === '';
    }
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());
    }