Completed
Push — master ( 6d621d...1a0788 )
by Simon
11:55
created

ValidateTokenQueryCreator::resolve()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 13
nc 4
nop 4
1
<?php
2
3
namespace Firesphere\GraphQLJWT;
4
5
use GraphQL\Type\Definition\ResolveInfo;
6
use GraphQL\Type\Definition\Type;
7
use SilverStripe\Control\Controller;
8
use SilverStripe\Core\Injector\Injector;
9
use SilverStripe\GraphQL\OperationResolver;
10
use SilverStripe\GraphQL\QueryCreator;
11
use SilverStripe\ORM\ValidationResult;
12
use SilverStripe\Security\Member;
13
14
class ValidateTokenQueryCreator extends QueryCreator implements OperationResolver
15
{
16
    public function attributes()
17
    {
18
        return [
19
            'name' => 'validateToken',
20
            'description' => 'Validates a given token from the Bearer header'
21
        ];
22
    }
23
24
    public function args()
25
    {
26
        return [];
27
    }
28
29
    public function type()
30
    {
31
        return $this->manager->getType('ValidateToken');
32
    }
33
34
    /**
35
     * @param mixed $object
36
     * @param array $args
37
     * @param mixed $context
38
     * @param ResolveInfo $info
39
     * @return array
40
     * @throws \BadMethodCallException
41
     */
42
    public function resolve($object, array $args, $context, ResolveInfo $info)
43
    {
44
        $validator = Injector::inst()->get(JWTAuthenticator::class);
45
        $msg = [];
46
        $request = Controller::curr()->getRequest();
47
        $matches = HeaderExtractor::getAuthorizationHeader($request);
48
        $result = new ValidationResult();
49
50
        if (!empty($matches[1])) {
51
            $validator->authenticate(['token' => $matches[1]], $request, $result);
52
        } else {
53
            $result->addError('No Bearer token found');
54
        }
55
56
        foreach ($result->getMessages() as $message) {
57
            $msg[] = $message['message'];
58
        }
59
60
        return ['Valid' => $result->isValid(), 'Message' => implode('; ', $msg)];
61
    }
62
}
63