Completed
Push — develop ( 1b547a...2f6a53 )
by Sean
02:41
created

JWTGuard::onceUsingId()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
ccs 0
cts 8
cp 0
rs 9.4285
cc 2
eloc 5
nc 2
nop 1
crap 6
1
<?php
2
3
/*
4
 * This file is part of jwt-auth
5
 *
6
 * (c) Sean Tymon <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Tymon\JWTAuth;
13
14
use Illuminate\Http\Request;
15
use Illuminate\Auth\GuardHelpers;
16
use Illuminate\Contracts\Auth\Guard;
17
use Illuminate\Contracts\Auth\UserProvider;
18
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
19
20
class JWTGuard implements Guard
21
{
22
    use GuardHelpers;
23
24
    /**
25
     * The user we last attempted to retrieve.
26
     *
27
     * @var \Illuminate\Contracts\Auth\Authenticatable
28
     */
29
    protected $lastAttempted;
30
31
    /**
32
     * The JWTAuth instance.
33
     *
34
     * @var \Tymon\JWTAuth\JWTAuth
35
     */
36
    protected $auth;
37
38
    /**
39
     * The request instance.
40
     *
41
     * @var \Illuminate\Http\Request
42
     */
43
    protected $request;
44
45
    public function __construct(JWTAuth $auth, UserProvider $provider, Request $request)
1 ignored issue
show
Bug introduced by
You have injected the Request via parameter $request. This is generally not recommended as there might be multiple instances during a request cycle (f.e. when using sub-requests). Instead, it is recommended to inject the RequestStack and retrieve the current request each time you need it via getCurrentRequest().
Loading history...
46
    {
47
        $this->auth = $auth;
48
        $this->provider = $provider;
49
        $this->request = $request;
50
    }
51
52
    /**
53
     * Get the currently authenticated user.
54
     *
55
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
56
     */
57
    public function user()
58
    {
59
        if (! is_null($this->user)) {
60
            return $this->user;
61
        }
62
63
        if (! $this->requireToken()->check()) {
64
            return null;
65
        }
66
67
        $id = $this->auth->getPayload()->get('sub');
68
69
        return $this->user = $this->provider->retrieveById($id);
70
    }
71
72
    /**
73
     * Validate a user's credentials.
74
     *
75
     * @param  array $credentials
76
     *
77
     * @return boolean
78
     */
79
    public function validate(array $credentials = [])
80
    {
81
        return $this->attempt($credentials, false);
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->attempt($credentials, false); of type string|boolean adds the type string to the return on line 81 which is incompatible with the return type declared by the interface Illuminate\Contracts\Auth\Guard::validate of type boolean.
Loading history...
82
    }
83
84
    /**
85
     * Attempt to authenticate the user using the given credentials and return the token.
86
     *
87
     * @param  array  $credentials
88
     *
89
     * @return boolean
90
     */
91
    public function attempt(array $credentials = [], $login = true)
92
    {
93
        $this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);
94
95
        if ($this->hasValidCredentials($user, $credentials)) {
96
            if ($login) {
97
                $this->setUser($user);
0 ignored issues
show
Bug introduced by
It seems like $user defined by $this->provider->retriev...edentials($credentials) on line 93 can be null; however, Illuminate\Auth\GuardHelpers::setUser() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
98
99
                return $this->auth->fromUser($user);
0 ignored issues
show
Documentation introduced by
$user is of type object<Illuminate\Contra...h\Authenticatable>|null, but the function expects a object<Tymon\JWTAuth\Contracts\JWTSubject>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
100
            }
101
102
            return true;
103
        }
104
105
        return false;
106
    }
107
108
    /**
109
     * Logout the user, thus invalidating the token.
110
     *
111
     * @param  boolean  $forceForever
112
     *
113
     * @return void
114
     */
115
    public function logout($forceForever = false)
116
    {
117
        $this->requireToken()->invalidate($forceForever);
118
119
        $this->user = null;
120
        $this->auth->unsetToken();
121
    }
122
123
    /**
124
     * Refresh the token
125
     *
126
     * @return  string
127
     */
128
    public function refresh()
129
    {
130
        return $this->requireToken()->refresh();
131
    }
132
133
    /**
134
     * Create a new token by User id
135
     *
136
     * @param   mixed  $id
137
     *
138
     * @return  string|null
139
     */
140
    public function tokenById($id)
141
    {
142
        if (! is_null($user = $this->provider->retrieveById($id))) {
143
            return $this->auth->fromUser($user);
0 ignored issues
show
Documentation introduced by
$user is of type object<Illuminate\Contracts\Auth\Authenticatable>, but the function expects a object<Tymon\JWTAuth\Contracts\JWTSubject>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
144
        }
145
146
        return null;
147
    }
148
149
    /**
150
     * Log a user into the application using their credentials.
151
     *
152
     * @param  array $credentials
153
     *
154
     * @return boolean
155
     */
156
    public function once(array $credentials = [])
157
    {
158
        if ($this->validate($credentials)) {
159
            $this->setUser($this->lastAttempted);
160
161
            return true;
162
        }
163
164
        return false;
165
    }
166
167
    /**
168
     * Log the given User into the application.
169
     *
170
     * @param  mixed $id
171
     *
172
     * @return boolean
173
     */
174
    public function onceUsingId($id)
175
    {
176
        if (! is_null($user = $this->provider->retrieveById($id))) {
177
            $this->setUser($user);
178
179
            return true;
180
        }
181
182
        return false;
183
    }
184
185
    /**
186
     * Alias for onceUsingId
187
     *
188
     * @param   mixed  $id
189
     *
190
     * @return  boolean
191
     */
192
    public function byId($id)
193
    {
194
        return $this->onceUsingId($id);
195
    }
196
197
    /**
198
     * Get the raw Payload instance.
199
     *
200
     * @return \Tymon\JWTAuth\Payload
201
     */
202
    public function getPayload()
203
    {
204
        return $this->auth->getPayload();
205
    }
206
207
    /**
208
     * Set the token.
209
     *
210
     * @param  Token|string  $token
211
     *
212
     * @return JWTGuard
213
     */
214
    public function setToken($token)
215
    {
216
        $this->auth->setToken($token);
217
218
        return $this;
219
    }
220
221
    /**
222
     * Get the user provider used by the guard.
223
     *
224
     * @return \Illuminate\Contracts\Auth\UserProvider
225
     */
226
    public function getProvider()
227
    {
228
        return $this->provider;
229
    }
230
231
    /**
232
     * Set the user provider used by the guard.
233
     *
234
     * @param  \Illuminate\Contracts\Auth\UserProvider  $provider
235
     *
236
     * @return void
237
     */
238
    public function setProvider(UserProvider $provider)
239
    {
240
        $this->provider = $provider;
241
    }
242
243
    /**
244
     * Return the currently cached user.
245
     *
246
     * @return \Illuminate\Contracts\Auth\Authenticatable|null
247
     */
248
    public function getUser()
249
    {
250
        return $this->user;
251
    }
252
253
    /**
254
     * Get the current request instance.
255
     *
256
     * @return \Symfony\Component\HttpFoundation\Request
257
     */
258
    public function getRequest()
259
    {
260
        return $this->request ?: Request::createFromGlobals();
261
    }
262
263
    /**
264
     * Set the current request instance.
265
     *
266
     * @param  \Symfony\Component\HttpFoundation\Request  $request
267
     *
268
     * @return $this
269
     */
270
    public function setRequest(Request $request)
1 ignored issue
show
Bug introduced by
You have injected the Request via parameter $request. This is generally not recommended as there might be multiple instances during a request cycle (f.e. when using sub-requests). Instead, it is recommended to inject the RequestStack and retrieve the current request each time you need it via getCurrentRequest().
Loading history...
271
    {
272
        $this->request = $request;
273
274
        return $this;
275
    }
276
277
    /**
278
     * Get the last user we attempted to authenticate.
279
     *
280
     * @return \Illuminate\Contracts\Auth\Authenticatable
281
     */
282
    public function getLastAttempted()
283
    {
284
        return $this->lastAttempted;
285
    }
286
287
    /**
288
     * Determine if the user matches the credentials.
289
     *
290
     * @param  mixed  $user
291
     * @param  array  $credentials
292
     *
293
     * @return boolean
294
     */
295
    protected function hasValidCredentials($user, $credentials)
296
    {
297
        return ! is_null($user) && $this->provider->validateCredentials($user, $credentials);
298
    }
299
300
    /**
301
     * Ensure that a token is available in the request
302
     *
303
     * @throws \Symfony\Component\HttpKernel\Exception\BadRequestHttpException
304
     *
305
     * @return \Tymon\JWTAuth\JWTAuth
306
     */
307
    protected function requireToken()
308
    {
309
        if (! $this->auth->getToken()) {
310
            throw new BadRequestHttpException($e->getMessage());
311
        }
312
313
        return $this->auth;
314
    }
315
}
316