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

RefreshTokenMutationCreator::resolve()   D

Complexity

Conditions 10
Paths 8

Size

Total Lines 37
Code Lines 22

Duplication

Lines 3
Ratio 8.11 %

Importance

Changes 0
Metric Value
dl 3
loc 37
rs 4.8196
c 0
b 0
f 0
cc 10
eloc 22
nc 8
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
     * @todo Make it refresh things
36
     * @param mixed $object
37
     * @param array $args
38
     * @param mixed $context
39
     * @param ResolveInfo $info
40
     * @return Member|null
41
     * @throws \BadMethodCallException
42
     * @throws \OutOfBoundsException
43
     */
44
    public function resolve($object, array $args, $context, ResolveInfo $info)
45
    {
46
        $request = Controller::curr()->getRequest();
47
        $authHeader = $request->getHeader('Authorization');
48
        $authenticator = Injector::inst()->get(JWTAuthenticator::class);
49
        $member = null;
50
        $result = new ValidationResult();
51 View Code Duplication
        if ($authHeader && preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
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 ($message['message'] === 'Token is expired') {
59
                    // If expired is true, the rest of the token is valid, so we can refresh
60
                    $expired = true;
61
                    // @todo fix code duplication
62
                    if (!$member && preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
63
                        // We need a member, even if the result is false
64
                        $parser = new Parser();
65
                        $parsedToken = $parser->parse((string)$matches[1]);
66
                        $member = Member::get()->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...
67
                    }
68
                }
69
            }
70
        }
71
72
        if ($expired && $member) {
73
            $member->Token = $authenticator->generateToken($member);
74
        } else {
75
            // Everything is wrong, give an empty member without token
76
            $member = Member::create();
77
        }
78
79
        return $member;
80
    }
81
}
82