Authenticator::getToken()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
cc 3
nc 3
nop 1
1
<?php
2
3
namespace AdvancedLearning\Oauth2Server\GraphQL;
4
5
6
use AdvancedLearning\Oauth2Server\Exceptions\AuthenticationException;
7
use AdvancedLearning\Oauth2Server\Models\Client;
8
use function is_null;
9
use SilverStripe\Control\HTTPRequest;
10
use SilverStripe\Core\Injector\Injector;
11
use SilverStripe\GraphQL\Auth\AuthenticatorInterface;
12
use SilverStripe\ORM\ValidationException;
13
use SilverStripe\Security\Member;
14
use function substr;
15
16
class Authenticator implements AuthenticatorInterface
17
{
18
    public function authenticate(HTTPRequest $request)
19
    {
20
        $authenticator = Injector::inst()->get(\AdvancedLearning\Oauth2Server\Services\Authenticator::class);
21
22
        try {
23
            $request = $authenticator->authenticate($request);
24
25
26
            if ($userId = $request->getHeader('oauth_user_id')) {
27
                return Member::get()->filter(['Email' => $userId])->first();
28
29
                // return a fake member for the client
30
            } else if ($clientId = $request->getHeader('oauth_client_id')) {
31
                $member = new Member();
32
                $client = Client::get()->filter(['Identifier' => $clientId])->first();
33
34
                if (!$client) {
35
                    throw new ValidationException('Could not find a valid client/user', 403);
36
                }
37
38
                $member->FirstName = $client->Name;
39
40
                return $member;
41
            }
42
43
            throw new ValidationException('Could not find a valid client/user', 403);
44
        } catch (AuthenticationException $exception) {
45
            throw new ValidationException($exception->getMessage(), 403);
46
        }
47
    }
48
49
    public function isApplicable(HTTPRequest $request)
50
    {
51
        return !is_null($this->getToken($request));
52
    }
53
54
    /**
55
     * Extract the token from the authorization header.
56
     *
57
     * @param HTTPRequest $request The request container the token.
58
     *
59
     * @return null|string
60
     */
61
    protected function getToken(HTTPRequest $request): ?string
62
    {
63
        if ($authHeader = $request->getHeader('Authorization')) {
64
            if (stripos($authHeader, 'Bearer ') === 0) {
65
                return substr($authHeader, 6);
66
            }
67
        }
68
69
        return null;
70
    }
71
}
72