Skip to content

Commit 8681dbd

Browse files
committed
feat: ✨ add authentication exception
Added InvalidCredentialsException for failed authentication attempts
1 parent edd72ca commit 8681dbd

File tree

4 files changed

+19
-9
lines changed

4 files changed

+19
-9
lines changed

README.md

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -130,14 +130,13 @@ $jwtAuth = new JWTAuth($authProvider, $jwtProvider, $claims);
130130

131131
### Attempt Authentication
132132

133-
Authenticate a user by providing their credentials. If successful, a JWT token will be returned.
133+
Authenticate a user by providing their credentials. If successful, a JWT token will be returned. If the credentials are invalid, an `InvalidCredentialsException` will be thrown.
134134

135135
```php
136-
$token = $jwtAuth->attempt('admin', 'secret');
137-
138-
if ($token) {
136+
try {
137+
$token = $jwtAuth->attempt('admin', 'secret');
139138
echo "Token: " . $token;
140-
} else {
139+
} catch (\Anddye\JWTAuth\Exceptions\InvalidCredentialsException $e) {
141140
echo "Invalid credentials";
142141
}
143142
```
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
<?php
2+
3+
namespace Anddye\JWTAuth\Exceptions;
4+
5+
use Exception;
6+
7+
class InvalidCredentialsException extends Exception
8+
{
9+
protected $message = 'Invalid credentials provided.';
10+
}

src/JwtAuth.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ public function __construct(AuthProviderInterface $authProvider, JWTProviderInte
2525
public function attempt(string $username, string $password): ?string
2626
{
2727
if (!$user = $this->authProvider->byCredentials($username, $password)) {
28-
return null;
28+
throw new Exceptions\InvalidCredentialsException();
2929
}
3030

3131
return $this->fromSubject($user);

tests/JWTAuthTest.php

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Anddye\JWTAuth\Tests;
44

5+
use Anddye\JWTAuth\Exceptions\InvalidCredentialsException;
56
use Anddye\JWTAuth\Factory\ClaimsFactory;
67
use Anddye\JWTAuth\JWTAuth;
78
use Anddye\JWTAuth\Tests\Stubs\Providers\AuthProvider;
@@ -42,11 +43,11 @@ public function testCanGetTokenWithValidLoginCredentials()
4243

4344
public function testCantGetTokenWithIncorrectLoginCredentials()
4445
{
46+
$this->expectException(InvalidCredentialsException::class);
47+
4548
$username = 'andrewdyer';
4649
$password = 'pa55w0rd';
4750

48-
$token = $this->jwtAuth->attempt($username, $password);
49-
50-
$this->assertNull($token);
51+
$this->jwtAuth->attempt($username, $password);
5152
}
5253
}

0 commit comments

Comments
 (0)