Completed
Push — master ( dd6027...6d621d )
by Tobias
06:47
created

ValidateTokenQueryCreator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 6

Importance

Changes 0
Metric Value
wmc 7
lcom 0
cbo 6
dl 0
loc 50
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A attributes() 0 7 1
A args() 0 4 1
A type() 0 4 1
B resolve() 0 22 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
     */
41
    public function resolve($object, array $args, $context, ResolveInfo $info)
42
    {
43
        $validator = Injector::inst()->get(JWTAuthenticator::class);
44
        $msg = [];
45
        $request = Controller::curr()->getRequest();
46
        $authHeader = $request->getHeader('Authorization');
47
        $result = new ValidationResult();
48
49
        if ($authHeader && preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
50
            $validator->authenticate(['token' => $matches[1]], $request, $result);
51
        } else {
52
            $result->addError('No Bearer token found');
53
        }
54
55
        foreach($result->getMessages() as $message) {
56
            $msg[] = $message['message'];
57
        }
58
59
        $return = ['Valid' => $result->isValid(),'Message' => implode('; ', $msg)];
60
61
        return $return;
62
    }
63
}
64