Passed
Push — master ( 14778d...75312f )
by Conrad
01:43
created

Authenticator::isApplicable()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
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()->byID($clientId);
33
34
                $member->FirstName = $client->Name;
35
36
                return $member;
37
            }
38
39
            throw new ValidationException('Could not find a valid client/user');
40
        } catch (AuthenticationException $exception) {
41
            throw new ValidationException($exception->getMessage());
42
        }
43
    }
44
45
    public function isApplicable(HTTPRequest $request)
46
    {
47
        return !is_null($this->getToken($request));
48
    }
49
50
    /**
51
     * Extract the token from the authorization header.
52
     *
53
     * @param HTTPRequest $request The request container the token.
54
     *
55
     * @return null|string
56
     */
57
    protected function getToken(HTTPRequest $request): ?string
58
    {
59
        if ($authHeader = $request->getHeader('Authorization')) {
60
            if (stripos($authHeader, 'Bearer ') === 0) {
61
                return substr($authHeader, 6);
62
            }
63
        }
64
65
        return null;
66
    }
67
}
68