Passed
Push — master ( 42aa8f...8137e8 )
by Simon
02:14
created

RefreshTokenMutationCreator::resolve()   C

Complexity

Conditions 11
Paths 24

Size

Total Lines 44
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 44
rs 5.2653
c 0
b 0
f 0
cc 11
eloc 26
nc 24
nop 4

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Firesphere\GraphQLJWT;
4
5
use GraphQL\Type\Definition\ResolveInfo;
0 ignored issues
show
Bug introduced by
The type GraphQL\Type\Definition\ResolveInfo was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
6
use Lcobucci\JWT\Parser;
7
use SilverStripe\Control\Controller;
8
use SilverStripe\Core\Injector\Injector;
9
use SilverStripe\GraphQL\MutationCreator;
10
use SilverStripe\GraphQL\OperationResolver;
11
use SilverStripe\ORM\ValidationResult;
12
use SilverStripe\Security\Member;
13
14
class RefreshTokenMutationCreator extends MutationCreator implements OperationResolver
15
{
16
    public function attributes()
17
    {
18
        return [
19
            'name'        => 'refreshToken',
20
            'description' => 'Refreshes a JWT token for a valid user. To be done'
21
        ];
22
    }
23
24
    public function type()
25
    {
26
        return $this->manager->getType('MemberToken');
27
    }
28
29
    public function args()
30
    {
31
        return [];
32
    }
33
34
    /**
35
     * @param mixed $object
36
     * @param array $args
37
     * @param mixed $context
38
     * @param ResolveInfo $info
39
     * @return Member|null
40
     * @throws \Psr\Container\NotFoundExceptionInterface
41
     * @throws \SilverStripe\ORM\ValidationException
42
     * @throws \BadMethodCallException
43
     * @throws \OutOfBoundsException
44
     */
45
    public function resolve($object, array $args, $context, ResolveInfo $info)
46
    {
47
        $request = Controller::curr()->getRequest();
48
        $authenticator = Injector::inst()->get(JWTAuthenticator::class);
49
        $member = null;
50
        $result = new ValidationResult();
51
        $matches = HeaderExtractor::getAuthorizationHeader($request);
52
53
        if (!empty($matches[1])) {
54
            $member = $authenticator->authenticate(['token' => $matches[1]], $request, $result);
55
        }
56
57
        $expired = false;
58
        // If we have a valid member, or there are no matches, there's no reason to go in here
59
        if ($member === null && !empty($matches[1])) {
60
            foreach ($result->getMessages() as $message) {
61
                if (strpos($message['message'], 'Token is expired') !== false) {
62
                    // If expired is true, the rest of the token is valid, so we can refresh
63
                    $expired = true;
64
                    // We need a member, even if the result is false
65
                    $parser = new Parser();
66
                    $parsedToken = $parser->parse((string)$matches[1]);
67
                    /** @var Member $member */
68
                    $member = Member::get()
69
                        ->filter(['JWTUniqueID' => $parsedToken->getClaim('jti')])
70
                        ->byID($parsedToken->getClaim('uid'));
71
                }
72
            }
73
        } elseif ($member) {
74
            $expired = true;
75
        }
76
77
        if ($expired && $member) {
78
            $member->Token = $authenticator->generateToken($member);
79
        } else {
80
            // Everything is wrong, give an empty member without token
81
            $member = Member::create(['ID' => 0, 'FirstName' => 'Anonymous']);
82
        }
83
        // Maybe not _everything_, we possibly have an anonymous allowed user
84
        if ($member->ID === 0 && JWTAuthenticator::config()->get('anonymous_allowed')) {
85
            $member->Token = $authenticator->generateToken($member);
86
        }
87
88
        return $member;
89
    }
90
}
91