Completed
Push — master ( 37c07d...bb5899 )
by Simon
01:38
created

RefreshTokenMutationCreator::resolve()   C

Complexity

Conditions 11
Paths 24

Size

Total Lines 46
Code Lines 28

Duplication

Lines 3
Ratio 6.52 %

Importance

Changes 0
Metric Value
dl 3
loc 46
rs 5.2653
c 0
b 0
f 0
cc 11
eloc 28
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;
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 \BadMethodCallException
41
     * @throws \OutOfBoundsException
42
     */
43
    public function resolve($object, array $args, $context, ResolveInfo $info)
44
    {
45
        $request = Controller::curr()->getRequest();
46
        $authenticator = Injector::inst()->get(JWTAuthenticator::class);
47
        $member = null;
48
        $result = new ValidationResult();
49
        $matches = HeaderExtractor::getAuthorizationHeader($request);
50
51 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...
52
            $member = $authenticator->authenticate(['token' => $matches[1]], $request, $result);
53
        }
54
55
        $expired = false;
56
        if ($member === null) {
57
            foreach ($result->getMessages() as $message) {
58
                if (strpos($message['message'], 'Token is expired') === 0) {
59
                    // If expired is true, the rest of the token is valid, so we can refresh
60
                    $expired = true;
61
                    if (!empty($matches[1])) {
62
                        // We need a member, even if the result is false
63
                        $parser = new Parser();
64
                        $parsedToken = $parser->parse((string)$matches[1]);
65
                        /** @var Member $member */
66
                        $member = Member::get()
67
                            ->filter(['JWTUniqueID' => $parsedToken->getClaim('jti')])
0 ignored issues
show
Deprecated Code introduced by
The method Lcobucci\JWT\Token::getClaim() has been deprecated with message: This method will be removed on v4

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
68
                            ->byID($parsedToken->getClaim('uid'));
0 ignored issues
show
Deprecated Code introduced by
The method Lcobucci\JWT\Token::getClaim() has been deprecated with message: This method will be removed on v4

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
69
                    }
70
                }
71
            }
72
        } elseif ($member) {
73
            $expired = true;
74
        }
75
76
        if ($expired && $member) {
77
            $member->Token = $authenticator->generateToken($member);
78
        } else {
79
            // Everything is wrong, give an empty member without token
80
            $member = Member::create(['ID' => 0, 'FirstName' => 'Anonymous']);
81
        }
82
        // Maybe not _everything_, we possibly have an anonymous allowed user
83
        if ($member->ID === 0 && JWTAuthenticator::config()->get('anonymous_allowed')) {
84
            $member->Token = $authenticator->generateToken($member);
85
        }
86
87
        return $member;
88
    }
89
}
90