Completed
Push — master ( c58af8...f68037 )
by Derek Stephen
02:57
created

ResourceServerController::scopeCheck()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 1
dl 0
loc 9
ccs 0
cts 9
cp 0
crap 12
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace App\Controller;
4
5
use Del\Common\ContainerService;
6
use League\OAuth2\Server\Exception\OAuthServerException;
7
use League\OAuth2\Server\ResourceServer;
8
use OAuth\AccessToken;
9
use OAuth\Exception\OAuthException;
10
use OAuth\Repository\AccessTokenRepository;
11
use Zend\Diactoros\Response;
12
13
class ResourceServerController extends BaseController
14
{
15
    /** @var AccessToken $accessToken*/
16
    protected $accessToken;
17
18
    /** @var string $client */
19
    protected $client;
20
21
    /** @var array $scopes */
22
    protected $scopes;
23
24
    /** @var null|int $user */
25
    protected $user;
26
27
    /**
28
     * @throws OAuthServerException
29
     */
30
    public function init()
31
    {
32
        $container = ContainerService::getInstance()->getContainer();
33
        $container['repository.Client']; // this is a weird doctrine/pimple bug?
34
        // comment this ^ out and you cant get the repo below! mapping from access token to scope!
35
        /** @var AccessTokenRepository $accessTokenRepository */
36
        $accessTokenRepository = $container['repository.AccessToken'];
37
        $publicKeyPath = 'file://' . APPLICATION_PATH . '/data/keys/public.key';
38
        $server = new ResourceServer(
39
            $accessTokenRepository,
40
            $publicKeyPath
41
        );
42
        try {
43
            $request = $server->validateAuthenticatedRequest($this->getRequest());
44
            $this->setRequest($request);
45
            $this->accessToken = $accessTokenRepository->findOneBy(['identifier' => $request->getAttribute('oauth_access_token_id')]);
46
            $this->client = $request->getAttribute('oauth_client_id');
47
            $this->scopes = $request->getAttribute('oauth_scopes');
48
            $this->user = $request->getAttribute('user');
49
        } catch (OAuthServerException $e) {
50
            $response = $e->generateHttpResponse(new Response());
51
            $this->sendResponse($response);
52
        }
53
    }
54
55
    /**
56
     * @param array $scopes
57
     * @return bool
58
     * @throws OAuthException
59
     */
60
    protected function scopeCheck(array $scopes): bool
61
    {
62
        $grantedScopes = $this->scopes;
63
        foreach ($scopes as $scope) {
64
            if (!in_array($scope, $grantedScopes)) {
65
                throw new OAuthException('Required scope has not been granted.');
66
            }
67
        }
68
        return true;
69
    }
70
}