Validate the token scopes against the registered scope

@param string[]|Scope[] $scopes

@throws OAuth2Exception (invalid_scope) When one or more of the given scopes where not registered
324538
protected function validateTokenScopes(array $scopes)
    {
        $scopes = array_map(function ($scope) {
            return (string) $scope;
        }, $scopes);

        $registeredScopes = $this->scopeService->getAll();

        $registeredScopes = array_map(function ($scope) {
            return (string) $scope;
        }, $registeredScopes);

        $diff = array_diff($scopes, $registeredScopes);

        if (count($diff) > 0) {
            throw OAuth2Exception::invalidScope(sprintf(
                'Some scope(s) do not exist: %s',
                implode(', ', $diff)
            ));
        }
    }
506828
public static function actingAs($user, $scopes = [], $guard = 'api')
    {
        $token = Mockery::mock(self::tokenModel())->shouldIgnoreMissing(false);

        foreach ($scopes as $scope) {
            $token->shouldReceive('can')->with($scope)->andReturn(true);
        }

        $user->withAccessToken($token);

        if (isset($user->wasRecentlyCreated) && $user->wasRecentlyCreated) {
            $user->wasRecentlyCreated = false;
        }

        app('auth')->guard($guard)->setUser($user);

        app('auth')->shouldUse($guard);

        return $user;
    }
480306
public function clientCredentials($scope = 'public')
    {
        if (is_array($scope)) {
            $scope = implode(' ', $scope);
        }

        $token_response = $this->request(self::CLIENT_CREDENTIALS_TOKEN_ENDPOINT, array(
            'grant_type' => 'client_credentials',
            'scope' => $scope
        ), "POST", false);

        return $token_response;
    }
303543
protected function scopes($scopes, array $options = [])
    {
        $scopes = $this->getPropertyValue($scopes);

        $this->scopes[] = \compact('scopes', 'options');
    }
725451
public function exploits($scopes = []) {
        if (!$this->id) {
            throw new Exception("The software has no ID, can\'t get exploits");
        }

        if (!$this->server_id) {
            throw new Exception("The software has no server ID, can\'t get exploits");
        }

        $exploit = new Exploit($this->patrol);

        $exploit->defaults([
            'software_id' => $this->id,
            'server_id' => $this->server_id
        ]);

        return $exploit->all();
    }
760649
public function createToken($owner, $client, array $scopes = []): AccessToken
    {
        if (empty($scopes)) {
            $scopes = $this->scopeService->getDefaultScopes();
        } else {
            $this->validateTokenScopes($scopes);
        }

        do {
            $token = AccessToken::createNewAccessToken(
                $this->serverOptions->getAccessTokenTtl(),
                $owner,
                $client,
                $scopes
            );
        } while ($this->tokenRepository->tokenExists($token->getToken()));

        return $this->tokenRepository->save($token);
    }
1134984
public static function getAccessToken(
        ContextInterface $context,
        array $scopes = null,
        array $options = []
    ): AccessToken
	{
		$formParams = [
			'grant_type' => 'client_credentials',
			'client_id' => $context->getClientId(),
			'client_secret' => $context->getClientSecret(),
		];

		if ($scopes !== null) {
			$formParams['scope'] = implode(',', $scopes);
		}

        $client = SumUp::getClient($options);

		$response = $client->request(
			'POST',
			self::OAUTH_TOKEN,
			[
				'form_params' => $formParams,
			]);

		$code = $response->getStatusCode();
		if ($code !== 200) {
			$message = " Request code: $code \n Message: " . $response->getReasonPhrase();
			throw new BadRequestException($message);
		}

		$body = json_decode($response->getBody()->getContents(), true);
		$token_params = [
			$body['access_token'],
			$body['token_type'],
			$body['expires_in'],
		];

		if (isset($body['scope'])) {
			$token_params[] = $body['scope'];
		}

		return new AccessToken(...$token_params);
	}
487796
public static function validateScope(ContainerInterface $container, int $userId, array $scope = null): ?array
    {
        // Here is the place you can implement your scope limitation for users. Such as
        // limiting scopes that could be assigned for the user token.
        // It could be role based system or any other system that suits your application.
        //
        // Possible return values:
        // - `null` means no scope changes for the user.
        // - `array` with scope identities. Token issued for the user will be limited to this scope.
        // - authorization exception if you want to stop token issuing process and notify the user
        //   do not have enough rights to issue requested scopes.

        $result = null;
        if ($scope !== null) {
            /** @var UsersApi $usersApi */
            /** @var FactoryInterface $factory */
            $factory  = $container->get(FactoryInterface::class);
            $usersApi = $factory->createApi(UsersApi::class);

            $userScopes    = $usersApi->readScopes($userId);
            $adjustedScope = array_intersect($userScopes, $scope);
            if (count($adjustedScope) !== count($scope)) {
                $result = $adjustedScope;
            }
        }

        return $result;
    }
353873
private function validateRates(array $rates)
    {
        foreach ($rates as $rate) {
            if (!is_scalar($rate)) {
                throw new \InvalidArgumentException(sprintf(
                    'Rates passed to the PhpArray service must be scalars, "%s" given.',
                    gettype($rate)
                ));
            }
        }
    }
530676
public static function actingAs($user, $scopes = [], $guard = 'api')
    {
        $token = Mockery::mock(Token::class)->shouldIgnoreMissing(false);

        foreach ($scopes as $scope) {
            $token->shouldReceive('can')->with($scope)->andReturn(true);
        }

        $user->withAccessToken($token);

        app('auth')->guard($guard)->setUser($user);

        app('auth')->shouldUse($guard);
    }
22651
public function can(string $method, string $uri, array $scopes): bool
    {

        if (! array_key_exists($uri, $this->scope_map[$method])) {

            Configuration::getInstance()->getLogger()
                ->warning('An unknown URI was called. Allowing ' . $uri);

            return true;
        }

        $required_scope = $this->scope_map[$method][$uri];

        // Public scopes require no authentication!
        if ($required_scope == 'public')
            return true;

        if (! in_array($required_scope, $scopes))
            return false;

        return true;
    }
963231
protected function _getScopes($scopes = [])
    {
        if ($scopes) {
            $returnScopes = [];
            foreach ($scopes as $scope) {
                $returnScopes[$scope] = $this->_scopes[$scope];
            }
            return $returnScopes;
        } else {
            return $this->_scopes;
        }
    }
710968
protected function validateScopes($psr, $scopes)
    {
        if (in_array('*', $tokenScopes = $psr->getAttribute('oauth_scopes'))) {
            return;
        }

        foreach ($scopes as $scope) {
            if (! in_array($scope, $tokenScopes)) {
                throw new MissingScopeException($scope);
            }
        }
    }
423328
public function allSoftware($scopes = []) {
        if (!$this->id) {
            throw new Exception("The server has no ID, can\'t get software");
        }

        $software = new Software($this->patrol);

        $software->defaults([
            'server_id' => $this->id
        ]);

        return $software->all($scopes);
    }
730042
public function validateScopes($scopes, $redirectUri = null)
    {
        if (!\is_array($scopes)) {
            $scopes = $this->convertScopesQueryStringToArray($scopes);
        }

        $validScopes = [];

        foreach ($scopes as $scopeItem) {
            $scope = $this->scopeRepository->getScopeEntityByIdentifier($scopeItem);

            if ($scope instanceof ScopeEntityInterface === false) {
                throw OAuthServerException::invalidScope($scopeItem, $redirectUri);
            }

            $validScopes[] = $scope;
        }

        return $validScopes;
    }
223411
public function setAuthenticationScopes()
    {

        $scopes = $this->verifyToken()['Scopes'];

        // Add the internal 'public' scope
        $scopes = $scopes . ' public';
        $this->authentication->scopes = explode(' ', $scopes);
    }
1256779
public function handle($request, Closure $next, ...$scopes)
    {
        $psr = (new DiactorosFactory)->createRequest($request);

        try {
            $psr = $this->server->validateAuthenticatedRequest($psr);
        } catch (OAuthServerException $e) {
            throw new AuthenticationException;
        }

        $this->validateScopes($psr, $scopes);

        return $next($request);
    }