Completed
Push — develop ( 112c74...31322a )
by Nate
10:28
created

Route::verifyToken()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 0
cts 11
cp 0
rs 9.5555
c 0
b 0
f 0
cc 5
nc 8
nop 1
crap 30
1
<?php
2
3
/**
4
 * @copyright  Copyright (c) Flipbox Digital Limited
5
 * @license    https://flipboxfactory.com/software/jwt/license
6
 * @link       https://www.flipboxfactory.com/jwt/organization/
7
 */
8
9
namespace flipbox\craft\jwt\services;
10
11
use Craft;
12
use craft\elements\User;
13
use flipbox\craft\jwt\Jwt;
14
use flipbox\craft\jwt\helpers\TokenHelper;
15
use flipbox\craft\jwt\helpers\UserHelper;
16
use Lcobucci\JWT\Token;
17
use yii\base\Component;
18
use yii\web\IdentityInterface;
19
20
/**
21
 * @author Flipbox Factory <[email protected]>
22
 * @since 1.0.0
23
 */
24
class Route extends Component
25
{
26
    /**
27
     * The CSRF claim identifier
28
     */
29
    const CLAIM_ROUTE = 'route';
30
31
    /**
32
     * Issue an authorization JWT token on behalf of a user.
33
     *
34
     * An $action may come in the form of:
35
     *
36
     * STRING - Route to a controller action
37
     * 'action/path'
38
     *
39
     * ARRAY - Route to a template
40
     * ['templates/render', ['template' => 'template/path']]
41
     *
42
     * ARRAY w/ PARAMS - Route to a controller action with params
43
     * ['action/path', [
44
     *     'foo' => 'bar'
45
     * ]]
46
     *
47
     * @param string|array $action
48
     * @param string|int|IdentityInterface $user
49
     * @param string|null $audience
50
     * @param int|null $expiration
51
     * @return Token|null
52
     * @throws \craft\errors\SiteNotFoundException
53
     * @throws \yii\base\InvalidConfigException
54
     */
55
    public function issue(
56
        $action,
57
        $user = null,
58
        int $expiration = null,
59
        string $audience = null
60
    ) {
61
        $identity = UserHelper::resolveUser($user);
62
63
        $builder = Jwt::getInstance()->getBuilder()
64
            ->setIssuer(Jwt::getInstance()->getSettings()->getIssuer())
65
            ->setAudience($this->resolveAudience($audience))
66
            ->setIssuedAt(time())
67
            ->setNotBefore(time())
68
            ->setExpiration($this->resolveTokenExpiration($expiration))
69
            ->set(TokenHelper::CLAIM_CSRF, Craft::$app->getRequest()->getCsrfToken())
70
            ->set(self::CLAIM_ROUTE, serialize($action))
71
            ->sign(Jwt::getInstance()->getSettings()->getSigner(), TokenHelper::getSignatureKey($identity));
72
73
        if ($identity) {
74
            $builder->setId($identity->getId(), true);
75
        }
76
77
        return $builder->getToken();
78
    }
79
80
    /**
81
     * @param string $token
82
     * @param bool $assumeIdentity
83
     * @return string|array
84
     * @throws \craft\errors\SiteNotFoundException
85
     */
86
    public function claim(string $token, bool $assumeIdentity = true)
87
    {
88
        if (null === ($token = $this->parse($token))) {
89
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by flipbox\craft\jwt\services\Route::claim of type string|array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
90
        }
91
92
        // Assume the identity token
93
        if ($assumeIdentity && null !== ($identity = $this->tokenIdentity($token))) {
94
            Craft::$app->getUser()->setIdentity($identity);
95
        }
96
97
        return unserialize($token->getClaim(static::CLAIM_ROUTE));
98
    }
99
100
    /**
101
     * @param Token $token
102
     * @return null|IdentityInterface
103
     */
104
    private function tokenIdentity(Token $token)
105
    {
106
        if (!$token->hasClaim(TokenHelper::CLAIM_IDENTITY)) {
107
            return null;
108
        }
109
110
        return UserHelper::resolveUser($token->getClaim(TokenHelper::CLAIM_IDENTITY));
111
    }
112
113
    /**
114
     * @param $token
115
     * @param bool $validate
116
     * @param bool $verify
117
     * @return Token|null
118
     * @throws \craft\errors\SiteNotFoundException
119
     */
120
    public function parse(string $token, bool $validate = true, bool $verify = true)
121
    {
122
        if (null === ($token = TokenHelper::parse($token, $validate))) {
123
            return null;
124
        }
125
126
        if ($verify && !$this->verifyToken($token)) {
127
            return null;
128
        }
129
130
        return $token;
131
    }
132
133
    /**
134
     * @param Token $token
135
     * @return bool
136
     * @throws \craft\errors\SiteNotFoundException
137
     */
138
    public function verifyToken(Token $token): bool
139
    {
140
        $identity = null;
141
        if ($token->hasClaim(TokenHelper::CLAIM_IDENTITY)) {
142
            $identity = UserHelper::resolveUser($token->getClaim(TokenHelper::CLAIM_IDENTITY));
143
        }
144
145
        return TokenHelper::verifyTokenCsrfClaim($token) &&
146
            TokenHelper::verifyIssuer($token, Jwt::getInstance()->getSettings()->getRouteIssuers()) &&
147
            TokenHelper::verifyAudience($token) &&
148
            TokenHelper::verifyTokenSignature($token, $identity);
149
    }
150
151
    /**
152
     * @param string|null $audience
153
     * @return string
154
     * @throws \craft\errors\SiteNotFoundException
155
     */
156
    private function resolveAudience(string $audience = null): string
157
    {
158
        if ($audience === null) {
159
            $audience = Jwt::getInstance()->getSettings()->getRouteAudience();
160
        }
161
162
        return (string)$audience;
163
    }
164
165
    /**
166
     * @param int|null $expiration
167
     * @return int
168
     * @throws \yii\base\InvalidConfigException
169
     */
170
    private function resolveTokenExpiration(int $expiration = null): int
171
    {
172
        if ($expiration === null) {
173
            $expiration = Jwt::getInstance()->getSettings()->getRouteTokenDuration();
174
        }
175
176
        return time() + (int)$expiration;
177
    }
178
}
179