Passed
Push — master ( 291050...8bc8e6 )
by Simon
01:52
created

RefreshTokenMutationCreator::resolve()   C

Complexity

Conditions 11
Paths 24

Size

Total Lines 44
Code Lines 26

Duplication

Lines 3
Ratio 6.82 %

Importance

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

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\Mutations;
4
5
use Firesphere\GraphQLJWT\Authentication\JWTAuthenticator;
6
use Firesphere\GraphQLJWT\Helpers\HeaderExtractor;
7
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...
8
use Lcobucci\JWT\Parser;
9
use SilverStripe\Control\Controller;
10
use SilverStripe\Core\Injector\Injector;
11
use SilverStripe\GraphQL\MutationCreator;
12
use SilverStripe\GraphQL\OperationResolver;
13
use SilverStripe\ORM\ValidationResult;
14
use SilverStripe\Security\Member;
15
16
class RefreshTokenMutationCreator extends MutationCreator implements OperationResolver
17
{
18
    public function attributes()
19
    {
20
        return [
21
            'name'        => 'refreshToken',
22
            'description' => 'Refreshes a JWT token for a valid user. To be done'
23
        ];
24
    }
25
26
    public function type()
27
    {
28
        return $this->manager->getType('MemberToken');
29
    }
30
31
    public function args()
32
    {
33
        return [];
34
    }
35
36
    /**
37
     * @param mixed $object
38
     * @param array $args
39
     * @param mixed $context
40
     * @param ResolveInfo $info
41
     * @return Member|null
42
     * @throws \Psr\Container\NotFoundExceptionInterface
43
     * @throws \SilverStripe\ORM\ValidationException
44
     * @throws \BadMethodCallException
45
     * @throws \OutOfBoundsException
46
     */
47
    public function resolve($object, array $args, $context, ResolveInfo $info)
48
    {
49
        $request = Controller::curr()->getRequest();
50
        $authenticator = Injector::inst()->get(JWTAuthenticator::class);
51
        $member = null;
52
        $result = new ValidationResult();
53
        $matches = HeaderExtractor::getAuthorizationHeader($request);
54
55 View Code Duplication
        if (!empty($matches[1])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
56
            $member = $authenticator->authenticate(['token' => $matches[1]], $request, $result);
57
        }
58
59
        $expired = false;
60
        // If we have a valid member, or there are no matches, there's no reason to go in here
61
        if ($member === null && !empty($matches[1])) {
62
            foreach ($result->getMessages() as $message) {
63
                if (strpos($message['message'], 'Token is expired') !== false) {
64
                    // If expired is true, the rest of the token is valid, so we can refresh
65
                    $expired = true;
66
                    // We need a member, even if the result is false
67
                    $parser = new Parser();
68
                    $parsedToken = $parser->parse((string)$matches[1]);
69
                    /** @var Member $member */
70
                    $member = Member::get()
71
                        ->filter(['JWTUniqueID' => $parsedToken->getClaim('jti')])
72
                        ->byID($parsedToken->getClaim('uid'));
73
                }
74
            }
75
        } elseif ($member) {
76
            $expired = true;
77
        }
78
79
        if ($expired && $member) {
80
            $member->Token = $authenticator->generateToken($member);
81
        } else {
82
            // Everything is wrong, give an empty member without token
83
            $member = Member::create(['ID' => 0, 'FirstName' => 'Anonymous']);
84
        }
85
        // Maybe not _everything_, we possibly have an anonymous allowed user
86
        if ($member->ID === 0 && JWTAuthenticator::config()->get('anonymous_allowed')) {
87
            $member->Token = $authenticator->generateToken($member);
88
        }
89
90
        return $member;
91
    }
92
}
93