Skip to content

Commit ce08363

Browse files
authored
Merge pull request #300 from NielsJanssen/main
fix: Prevent null pointer when provider cannot find a user for a token
2 parents 734f269 + da1d3b4 commit ce08363

2 files changed

Lines changed: 31 additions & 1 deletion

File tree

src/JWTGuard.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,11 @@ public function user()
104104
&& ($payload = $this->jwt->check(true))
105105
&& $this->validateSubject()
106106
) {
107-
$this->setUser($this->provider->retrieveById($payload['sub']));
107+
$user = $this->provider->retrieveById($payload['sub']);
108+
109+
if ($user) {
110+
$this->setUser($user);
111+
}
108112

109113
return $this->user;
110114
}

tests/JWTGuardTest.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,32 @@ public function testItShouldGetTheAuthenticatedUserIfAValidTokenIsProvidedAndNot
127127
$this->assertTrue($this->guard->check());
128128
}
129129

130+
public function testItShouldReturnNullIfAProviderCannotdTheUser()
131+
{
132+
$payload = \Mockery::mock(Payload::class);
133+
$payload->shouldReceive('offsetGet')->once()->with('sub')->andReturn(1);
134+
135+
$this->jwt->shouldReceive('setRequest')->andReturn($this->jwt);
136+
$this->jwt->shouldReceive('getToken')->once()->andReturn('foo.bar.baz');
137+
$this->jwt->shouldReceive('check')->once()->with(true)->andReturn($payload);
138+
$this->jwt->shouldReceive('checkSubjectModel')
139+
->once()
140+
->with('\PHPOpenSourceSaver\JWTAuth\Test\Stubs\LaravelUserStub')
141+
->andReturn(true);
142+
143+
$this->provider->shouldReceive('getModel')
144+
->once()
145+
->andReturn('\PHPOpenSourceSaver\JWTAuth\Test\Stubs\LaravelUserStub');
146+
$this->provider->shouldReceive('retrieveById')
147+
->once()
148+
->with(1)
149+
->andReturn(null);
150+
151+
$this->eventDispatcher->shouldReceive('dispatch')->never();
152+
153+
$this->assertNull($this->guard->user());
154+
}
155+
130156
public function testItShouldReturnNullIfAnInvalidTokenIsProvided()
131157
{
132158
$this->jwt->shouldReceive('setRequest')->andReturn($this->jwt);

0 commit comments

Comments
 (0)