Skip to content

Commit

Permalink
Merge pull request #257 from canvural/add-user-id-method
Browse files Browse the repository at this point in the history
feat: add getUserId method
  • Loading branch information
Messhias authored Jul 11, 2024
2 parents 0d354ac + 9bf31be commit 7e91edf
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ You can find and compare releases at the GitHub release page.

### Added
- Support for lcobucci/jwt^5.0 (and dropped support for ^4.0)
- New `getUserId` method

## [2.3.0] 2024-05-09

Expand Down
20 changes: 20 additions & 0 deletions src/JWTGuard.php
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,26 @@ public function user()
}
}

/**
* @return int|string|null
*/
public function getUserId()
{
if (null !== $this->user) {
return $this->user->getAuthIdentifier();
}

if (
$this->jwt->setRequest($this->request)->getToken()
&& ($payload = $this->jwt->check(true))
&& $this->validateSubject()
) {
return $payload['sub'];
}

return null;
}

/**
* Get the currently authenticated user or throws an exception.
*
Expand Down
31 changes: 31 additions & 0 deletions tests/JWTGuardTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,37 @@ public function testItShouldThrowAnExceptionIfNoTokenIsProvided()
$this->guard->userOrFail(); // throws the exception
}

public function testItShouldGetTheAuthenticatedUserIdIfAValidTokenIsProvided()
{
$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->assertSame(1, $this->guard->getUserId());
}

public function testItShouldReturnNullForUserIdIfNoTokenIsProvided()
{
$this->jwt->shouldReceive('setRequest')->andReturn($this->jwt);
$this->jwt->shouldReceive('getToken')->andReturn(false);
$this->jwt->shouldReceive('check')->never();
$this->jwt->shouldReceive('getPayload->get')->never();
$this->provider->shouldReceive('retrieveById')->never();

$this->assertNull($this->guard->getUserId());
}

public function testItShouldReturnATokenIfCredentialsAreOkAndUserIsFound()
{
$credentials = ['foo' => 'bar', 'baz' => 'bob'];
Expand Down

0 comments on commit 7e91edf

Please sign in to comment.