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

RefreshTokenMutationCreator::attributes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 0
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