diff --git a/src/JWTGuard.php b/src/JWTGuard.php index c1f52b3a..5ab0f542 100644 --- a/src/JWTGuard.php +++ b/src/JWTGuard.php @@ -104,7 +104,11 @@ public function user() && ($payload = $this->jwt->check(true)) && $this->validateSubject() ) { - $this->setUser($this->provider->retrieveById($payload['sub'])); + $user = $this->provider->retrieveById($payload['sub']); + + if ($user) { + $this->setUser($user); + } return $this->user; } diff --git a/tests/JWTGuardTest.php b/tests/JWTGuardTest.php index 30a53fb8..bb09514d 100644 --- a/tests/JWTGuardTest.php +++ b/tests/JWTGuardTest.php @@ -127,6 +127,32 @@ public function testItShouldGetTheAuthenticatedUserIfAValidTokenIsProvidedAndNot $this->assertTrue($this->guard->check()); } + public function testItShouldReturnNullIfAProviderCannotdTheUser() + { + $payload = \Mockery::mock(Payload::class); + $payload->shouldReceive('offsetGet')->once()->with('sub')->andReturn(1); + + $this->jwt->shouldReceive('setRequest')->andReturn($this->jwt); + $this->jwt->shouldReceive('getToken')->once()->andReturn('foo.bar.baz'); + $this->jwt->shouldReceive('check')->once()->with(true)->andReturn($payload); + $this->jwt->shouldReceive('checkSubjectModel') + ->once() + ->with('\PHPOpenSourceSaver\JWTAuth\Test\Stubs\LaravelUserStub') + ->andReturn(true); + + $this->provider->shouldReceive('getModel') + ->once() + ->andReturn('\PHPOpenSourceSaver\JWTAuth\Test\Stubs\LaravelUserStub'); + $this->provider->shouldReceive('retrieveById') + ->once() + ->with(1) + ->andReturn(null); + + $this->eventDispatcher->shouldReceive('dispatch')->never(); + + $this->assertNull($this->guard->user()); + } + public function testItShouldReturnNullIfAnInvalidTokenIsProvided() { $this->jwt->shouldReceive('setRequest')->andReturn($this->jwt);