Check if user-agent is authenticated

1. Check state according to OAuth 2.0
2. Try to retrieve access token with authorization code

@param ServerRequestInterface $request
@return bool|ResponseInterface
@throws Exception
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;
    }
175100
protected function authentication(RequestInterface $request)
	{
		if ($this->tokenRequired)
		{
			return $request->withHeader('Authorization', sprintf('OAuth %s', $this->getAccessToken()));
		}

		return $request;
	}
330778
protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        abort(401);

        return redirect()->guest(route(\Platform::port()->slug().'::login'));
    }
194952
protected function validateUser(ServerRequestInterface $request, ClientEntityInterface $client)
	{
		$accessToken = $this->getRequestParameter('accessToken', $request);
		if (is_null($accessToken)) {
		  throw OAuthServerException::invalidRequest('accessToken');
		}

		$provider = $this->getRequestParameter('provider', $request);
		if (is_null($provider)) {
		  throw OAuthServerException::invalidRequest('provider');
		}

		$user = $this->userRepository->getUserFromSocialProvider(
		  $accessToken,
		  $provider,
		  $this->getIdentifier(),
		  $client
		);
		if ($user instanceof UserEntityInterface === false) {
		  $this->getEmitter()->emit(new RequestEvent(RequestEvent::USER_AUTHENTICATION_FAILED, $request));

		  throw OAuthServerException::invalidCredentials();
		}

		return $user;
	}
1180399
protected function authenticateViaBearerToken($request)
    {
        // First, we will convert the Symfony request to a PSR-7 implementation which will
        // be compatible with the base OAuth2 library. The Symfony bridge can perform a
        // conversion for us to a Zend Diactoros implementation of the PSR-7 request.
        $psr = (new DiactorosFactory)->createRequest($request);

        try {
            $psr = $this->server->validateAuthenticatedRequest($psr);

            // If the access token is valid we will retrieve the user according to the user ID
            // associated with the token. We will use the provider implementation which may
            // be used to retrieve users from Eloquent. Next, we'll be ready to continue.
            $user = $this->provider->retrieveById(
                $psr->getAttribute('oauth_user_id')
            );

            if (! $user) {
                return;
            }

            // Next, we will assign a token instance to this user which the developers may use
            // to determine if the token has a given scope, etc. This will be useful during
            // authorization such as within the developer's Laravel model policy classes.
            $token = $this->tokens->find(
                $psr->getAttribute('oauth_access_token_id')
            );

            $clientId = $psr->getAttribute('oauth_client_id');

            // Finally, we will verify if the client that issued this token is still valid and
            // its tokens may still be used. If not, we will bail out since we don't want a
            // user to be able to send access tokens for deleted or revoked applications.
            if ($this->clients->revoked($clientId)) {
                return;
            }

            return $token ? $user->withAccessToken($token) : null;
        } catch (OAuthServerException $e) {
            return Container::getInstance()->make(
                ExceptionHandler::class
            )->report($e);
        }
    }
619393
public function issueToken(ServerRequestInterface $request)
    {
        $response = $this->withErrorHandling(function () use ($request) {
            $input = (array) $request->getParsedBody();
            $clientId = isset($input['client_id']) ? $input['client_id'] : null;

            // Overwrite password grant at the last minute to add support for customized TTLs
            $this->server->enableGrantType(
                $this->makePasswordGrant(), LumenPassport::tokensExpireIn(null, $clientId)
            );

            return $this->server->respondToAccessTokenRequest($request, new Psr7Response);
        });

        if ($response->getStatusCode() < 200 || $response->getStatusCode() > 299) {
            return $response;
        }

        $payload = json_decode($response->getBody()->__toString(), true);

        if (isset($payload['access_token'])) {
            $tokenId = $this->jwt->parse($payload['access_token'])->getClaim('jti');
            $token = $this->tokens->find($tokenId);

            if ($token->client->firstParty() && LumenPassport::$allowMultipleTokens) {
                // We keep previous tokens for password clients
            } else {
                $this->revokeOrDeleteAccessTokens($token, $tokenId);
            }
        }

        return $response;
    }
912920
protected function getRequestUser(HTTPRequest $request)
    {
        // Check authentication
        $member = $this->getAuthHandler()->requireAuthentication($request);

        // Check authorisation
        $permissions = $request->param('Permissions');
        if (!$permissions) {
            return $member;
        }

        // If permissions requested require authentication
        if (!$member) {
            throw new Exception("Authentication required");
        }

        // Check authorisation for this member
        $allowed = Permission::checkMember($member, $permissions);
        if (!$allowed) {
            throw new Exception("Not authorised");
        }
        return $member;
    }
428992
public function validateAuthorizationHeader(Request $request)
    {
        try {
            return parent::validateAuthorizationHeader($request);
        } catch (BadRequestHttpException $exception) {
            if (empty($request->query('token', ''))) {
                throw $exception;
            }
        }

        return true;
    }
624777
private function getTokenFromRequestBody(ServerRequestInterface $request): ?string
    {
        try {
            $parameters = RequestBodyParser::parseFormUrlEncoded($request);

            return $this->getAccessTokenFromParameters($parameters);
        } catch (\Exception $e) {
            return null;
        }
    }
81361
protected function _checkUrl(ServerRequestInterface $request)
    {
        return $this->_getUrlChecker()->check(
            $request,
            $this->getConfig('loginUrl'),
            (array)$this->getConfig('urlChecker')
        );
    }
353341
public function handle(ServerRequestInterface $request): ResponseInterface
    {
        if (false === $this->booted) {
            $this->boot();
        }

        try {
            return $this->pipe->handle($request);
        } catch (Exception $e) {
            $this->getContainer()->get('logger')->error($e);
        }
    }
1225311
protected function getServiceFromRequest(ServerRequestInterface $request)
    {
        $serviceAttribute = $this->getConfig('authorizationAttribute');
        $service = ($request->getAttribute($serviceAttribute));

        if (!$service instanceof AuthorizationServiceInterface) {
            $errorMessage = __CLASS__ . ' could not find the authorization service in the request attribute. ' .
                'Make sure you added the AuthorizationMiddleware before this middleware or that you ' .
                'somehow else added the service to the requests `' . $serviceAttribute . '` attribute.';

            throw new RuntimeException($errorMessage);
        }

        return $service;
    }
102832
public function checkForToken(Request $request)
    {
        if (! $this->auth->parser()->setRequest($request)->hasToken()) {
            throw new UnauthorizedHttpException('jwTauth', 'Token not provided');
        }
    }
1044696
public function auth(string $requestHandler, ServerRequestInterface $request): bool
    {
        throw new AuthException(ErrorCode::POST_DATA_NOT_PROVIDED, sprintf('AuthUserService::auth() method should be implemented in %s', static::class));
    }
281740
private function onRequest(ServerRequestInterface $request)
    {
        $start = microtime(true);
        $psrResponse = $this->requestHandler->dispatch($request);
        $this->logger->debug('Processing took ' . number_format((microtime(true) - $start) * 1000, 3) . ' milliseconds');

        return $psrResponse;
    }
23052
protected function getToken(ServerRequestInterface $request)
    {
        $token = $this->getTokenFromHeader($request, $this->getConfig('header'));
        if ($token === null) {
            $token = $this->getTokenFromQuery($request, $this->getConfig('queryParam'));
        }

        $prefix = $this->getConfig('tokenPrefix');
        if ($prefix !== null && is_string($token)) {
            return $this->stripTokenPrefix($token, $prefix);
        }

        return $token;
    }
780507
private function getEncryptionKey(ServerRequestInterface $request) : EncryptionKeyInterface
    {
        if (!$request->hasHeader('x-hashid')) {
            throw new Exception('Unable to decrypt request.');
        }

        $hashKey = $request->getHeaderLine('x-hashid');

        try {
            $result = $this->cache->get($hashKey);

            if (!$result) {
                throw new Exception('Unable to extract key from cache.');
            }

            if (\function_exists('igbinary_unserialize')) {
                return \igbinary_unserialize($result);
            }

            return \unserialize($result);
        } catch (InvalidArgumentException $e) {
            throw new Exception('Unable to decrypt request.', null, $e);
        }
    }