Completed
Push — master ( 9fef6b...b1fa31 )
by Simon
01:38
created

ValidateTokenQueryCreator::resolve()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 28
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 28
rs 8.439
c 0
b 0
f 0
cc 5
eloc 18
nc 9
nop 4
1
<?php
2
3
namespace Firesphere\GraphQLJWT;
4
5
use GraphQL\Type\Definition\ResolveInfo;
6
use SilverStripe\Control\Controller;
7
use SilverStripe\Core\Injector\Injector;
8
use SilverStripe\GraphQL\OperationResolver;
9
use SilverStripe\GraphQL\QueryCreator;
10
use SilverStripe\ORM\ValidationResult;
11
12
class ValidateTokenQueryCreator extends QueryCreator implements OperationResolver
13
{
14
    public function attributes()
15
    {
16
        return [
17
            'name' => 'validateToken',
18
            'description' => 'Validates a given token from the Bearer header'
19
        ];
20
    }
21
22
    public function args()
23
    {
24
        return [];
25
    }
26
27
    public function type()
28
    {
29
        return $this->manager->getType('ValidateToken');
30
    }
31
32
    /**
33
     * @param mixed $object
34
     * @param array $args
35
     * @param mixed $context
36
     * @param ResolveInfo $info
37
     * @return array
38
     * @throws \Psr\Container\NotFoundExceptionInterface
39
     * @throws \OutOfBoundsException
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
        $code = 401;
50
51
        if (!empty($matches[1])) {
52
            $validator->authenticate(['token' => $matches[1]], $request, $result);
53
            if ($result->isValid()) {
54
                $code = 200;
55
            }
56
        } else {
57
            $result->addError('No Bearer token found');
58
        }
59
60
        foreach ($result->getMessages() as $message) {
61
            if (strpos($message['message'], 'Token is expired') === 0) {
62
                // An expired token is code 423 `Update required`
63
                $code = 426;
64
            }
65
            $msg[] = $message['message'];
66
        }
67
68
        return ['Valid' => $result->isValid(), 'Message' => implode('; ', $msg), 'Code' => $code];
69
    }
70
}
71