Passed
Push — master ( 897bc8...5aa273 )
by Derek Stephen
02:48
created

ResourceServerController   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 83.33%

Importance

Changes 0
Metric Value
eloc 27
dl 0
loc 56
ccs 20
cts 24
cp 0.8333
rs 10
c 0
b 0
f 0
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A scopeCheck() 0 9 3
A init() 0 22 2
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 1
    public function init()
31
    {
32 1
        $container = ContainerService::getInstance()->getContainer();
33 1
        $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 1
        $accessTokenRepository = $container['repository.AccessToken'];
37 1
        $publicKeyPath = 'file://' . APPLICATION_PATH . '/data/keys/public.key';
38 1
        $server = new ResourceServer(
39 1
            $accessTokenRepository,
40 1
            $publicKeyPath
41
        );
42
        try {
43 1
            $request = $server->validateAuthenticatedRequest($this->getRequest());
44 1
            $this->setRequest($request);
45 1
            $this->accessToken = $accessTokenRepository->findOneBy(['identifier' => $request->getAttribute('oauth_access_token_id')]);
46 1
            $this->client = $request->getAttribute('oauth_client_id');
47 1
            $this->scopes = $request->getAttribute('oauth_scopes');
48 1
            $this->user = $request->getAttribute('user');
49
        } catch (OAuthServerException $e) {
50
            $response = $e->generateHttpResponse(new Response());
51
            $this->sendResponse($response);
52
        }
53 1
    }
54
55
    /**
56
     * @param array $scopes
57
     * @return bool
58
     * @throws OAuthException
59
     */
60 1
    protected function scopeCheck(array $scopes): bool
61
    {
62 1
        $grantedScopes = $this->scopes;
63 1
        foreach ($scopes as $scope) {
64 1
            if (!in_array($scope, $grantedScopes)) {
65
                throw new OAuthException('Required scope has not been granted.');
66
            }
67
        }
68 1
        return true;
69
    }
70
}