Skip to content

Commit 2dc1252

Browse files
committed
feat: improve Exception handling for FirebaseAdapter
- add InvalidTokenException and use it - change Exception classes - add lang items for error messages
1 parent 61f06fa commit 2dc1252

File tree

18 files changed

+110
-15
lines changed

18 files changed

+110
-15
lines changed

src/Authentication/JWT/Adapters/FirebaseAdapter.php

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,11 @@
44

55
namespace CodeIgniter\Shield\Authentication\JWT\Adapters;
66

7+
use CodeIgniter\Shield\Authentication\JWT\Exceptions\InvalidTokenException;
78
use CodeIgniter\Shield\Authentication\JWT\JWSAdapterInterface;
89
use CodeIgniter\Shield\Config\AuthJWT;
9-
use CodeIgniter\Shield\Exceptions\RuntimeException;
10+
use CodeIgniter\Shield\Exceptions\InvalidArgumentException as ShieldInvalidArgumentException;
11+
use CodeIgniter\Shield\Exceptions\LogicException;
1012
use DomainException;
1113
use Firebase\JWT\BeforeValidException;
1214
use Firebase\JWT\ExpiredException;
@@ -48,29 +50,40 @@ public static function decode(string $encodedToken, $keyset): stdClass
4850
return JWT::decode($encodedToken, $keys);
4951
} catch (InvalidArgumentException $e) {
5052
// provided key/key-array is empty or malformed.
51-
throw new RuntimeException('Invalid JWT: ' . $e->getMessage(), 0, $e);
53+
throw new ShieldInvalidArgumentException(
54+
'Invalid Keyset: "' . $keyset . '". ' . $e->getMessage(),
55+
0,
56+
$e
57+
);
5258
} catch (DomainException $e) {
5359
// provided algorithm is unsupported OR
5460
// provided key is invalid OR
5561
// unknown error thrown in openSSL or libsodium OR
5662
// libsodium is required but not available.
57-
throw new RuntimeException('Invalid JWT: ' . $e->getMessage(), 0, $e);
63+
throw new LogicException('Cannot decode JWT: ' . $e->getMessage(), 0, $e);
5864
} catch (SignatureInvalidException $e) {
5965
// provided JWT signature verification failed.
60-
throw new RuntimeException('Invalid JWT: ' . $e->getMessage(), 0, $e);
66+
throw InvalidTokenException::forInvalidToken($e);
6167
} catch (BeforeValidException $e) {
6268
// provided JWT is trying to be used before "nbf" claim OR
6369
// provided JWT is trying to be used before "iat" claim.
64-
throw new RuntimeException('Expired JWT: ' . $e->getMessage(), 0, $e);
70+
throw InvalidTokenException::forBeforeValidToken($e);
6571
} catch (ExpiredException $e) {
6672
// provided JWT is trying to be used after "exp" claim.
67-
throw new RuntimeException('Expired JWT: ' . $e->getMessage(), 0, $e);
73+
throw InvalidTokenException::forExpiredToken($e);
6874
} catch (UnexpectedValueException $e) {
6975
// provided JWT is malformed OR
7076
// provided JWT is missing an algorithm / using an unsupported algorithm OR
7177
// provided JWT algorithm does not match provided key OR
7278
// provided key ID in key/key-array is empty or invalid.
73-
throw new RuntimeException('Invalid JWT: ' . $e->getMessage(), 0, $e);
79+
log_message(
80+
'error',
81+
'[Shield] ' . class_basename(self::class) . '::' . __FUNCTION__
82+
. '(' . __LINE__ . ') '
83+
. get_class($e) . ': ' . $e->getMessage()
84+
);
85+
86+
throw InvalidTokenException::forInvalidToken($e);
7487
}
7588
}
7689

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace CodeIgniter\Shield\Authentication\JWT\Exceptions;
6+
7+
use CodeIgniter\Shield\Exceptions\ValidationException;
8+
use Exception;
9+
10+
class InvalidTokenException extends ValidationException
11+
{
12+
public static function forInvalidToken(Exception $e): self
13+
{
14+
return new self(lang('Auth.invalidJWT'), 1, $e);
15+
}
16+
17+
public static function forExpiredToken(Exception $e): self
18+
{
19+
return new self(lang('Auth.expiredJWT'), 2, $e);
20+
}
21+
22+
public static function forBeforeValidToken(Exception $e): self
23+
{
24+
return new self(lang('Auth.beforeValidJWT'), 3, $e);
25+
}
26+
}

src/Language/de/Auth.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@
2020
'unableSendEmailToUser' => 'Leider gab es ein Problem beim Senden der E-Mail. Wir konnten keine E-Mail an "{0}" senden.',
2121
'throttled' => 'Es wurden zu viele Anfragen von dieser IP-Adresse gestellt. Sie können es in {0} Sekunden erneut versuchen.',
2222
'notEnoughPrivilege' => 'Sie haben nicht die erforderliche Berechtigung, um den gewünschten Vorgang auszuführen.',
23+
// JWT Exceptions
24+
'invalidJWT' => '(To be translated) The token is invalid.',
25+
'expiredJWT' => '(To be translated) The token has expired.',
26+
'beforeValidJWT' => '(To be translated) The token is not yet available.',
2327

2428
'email' => 'E-Mail-Adresse',
2529
'username' => 'Benutzername',

src/Language/en/Auth.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@
2020
'unableSendEmailToUser' => 'Sorry, there was a problem sending the email. We could not send an email to "{0}".',
2121
'throttled' => 'Too many requests made from this IP address. You may try again in {0} seconds.',
2222
'notEnoughPrivilege' => 'You do not have the necessary permission to perform the desired operation.',
23+
// JWT Exceptions
24+
'invalidJWT' => 'The token is invalid.',
25+
'expiredJWT' => 'The token has expired.',
26+
'beforeValidJWT' => 'The token is not yet available.',
2327

2428
'email' => 'Email Address',
2529
'username' => 'Username',

src/Language/es/Auth.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@
2020
'unableSendEmailToUser' => 'Lo siento, hubo un problema al enviar el correo electrónico. No pudimos enviar un correo electrónico a "{0}".',
2121
'throttled' => 'Se han realizado demasiadas solicitudes desde esta dirección IP. Puedes intentarlo de nuevo en {0} segundos.',
2222
'notEnoughPrivilege' => 'No tienes los permisos necesarios para realizar la operación deseada.',
23+
// JWT Exceptions
24+
'invalidJWT' => '(To be translated) The token is invalid.',
25+
'expiredJWT' => '(To be translated) The token has expired.',
26+
'beforeValidJWT' => '(To be translated) The token is not yet available.',
2327

2428
'email' => 'Correo Electrónico',
2529
'username' => 'Nombre de usuario',

src/Language/fa/Auth.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@
2020
'unableSendEmailToUser' => 'متاسفانه, در ارسال ایمیل مشکلی پیش آمد. ما نتوانستیم ایمیلی را به "{0}" ارسال کنیم.',
2121
'throttled' => 'درخواست های بسیار زیادی از این آدرس IP انجام شده است. می توانید بعد از {0} ثانیه دوباره امتحان کنید.',
2222
'notEnoughPrivilege' => 'شما مجوز لازم برای انجام عملیات مورد نظر را ندارید.',
23+
// JWT Exceptions
24+
'invalidJWT' => '(To be translated) The token is invalid.',
25+
'expiredJWT' => '(To be translated) The token has expired.',
26+
'beforeValidJWT' => '(To be translated) The token is not yet available.',
2327

2428
'email' => 'آدرس ایمیل',
2529
'username' => 'نام کاربری',

src/Language/fr/Auth.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@
2020
'unableSendEmailToUser' => 'Désolé, il y a eu un problème lors de l\'envoi de l\'email. Nous ne pouvons pas envoyer un email à "{0}".',
2121
'throttled' => 'Trop de requêtes faites depuis cette adresse IP. Vous pouvez réessayer dans {0} secondes.',
2222
'notEnoughPrivilege' => 'Vous n\'avez pas l\'autorisation nécessaire pour effectuer l\'opération souhaitée.',
23+
// JWT Exceptions
24+
'invalidJWT' => '(To be translated) The token is invalid.',
25+
'expiredJWT' => '(To be translated) The token has expired.',
26+
'beforeValidJWT' => '(To be translated) The token is not yet available.',
2327

2428
'email' => 'Adresse email',
2529
'username' => 'Identifiant',

src/Language/id/Auth.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@
2020
'unableSendEmailToUser' => 'Maaf, ada masalah saat mengirim email. Kami tidak dapat mengirim email ke "{0}".',
2121
'throttled' => 'Terlalu banyak permintaan yang dibuat dari alamat IP ini. Anda dapat mencoba lagi dalam {0} detik.',
2222
'notEnoughPrivilege' => 'Anda tidak memiliki izin yang diperlukan untuk melakukan operasi yang diinginkan.',
23+
// JWT Exceptions
24+
'invalidJWT' => '(To be translated) The token is invalid.',
25+
'expiredJWT' => '(To be translated) The token has expired.',
26+
'beforeValidJWT' => '(To be translated) The token is not yet available.',
2327

2428
'email' => 'Alamat Email',
2529
'username' => 'Nama Pengguna',

src/Language/it/Auth.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@
2020
'unableSendEmailToUser' => 'Spiacente, c\'è stato un problema inviando l\'email. Non possiamo inviare un\'email a "{0}".',
2121
'throttled' => 'Troppe richieste effettuate da questo indirizzo IP. Potrai riprovare tra {0} secondi.',
2222
'notEnoughPrivilege' => 'Non si dispone dell\'autorizzazione necessaria per eseguire l\'operazione desiderata.',
23+
// JWT Exceptions
24+
'invalidJWT' => '(To be translated) The token is invalid.',
25+
'expiredJWT' => '(To be translated) The token has expired.',
26+
'beforeValidJWT' => '(To be translated) The token is not yet available.',
2327

2428
'email' => 'Indirizzo Email',
2529
'username' => 'Nome Utente',

src/Language/ja/Auth.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@
2020
'unableSendEmailToUser' => '申し訳ありませんが、メールの送信に問題がありました。 "{0}"にメールを送信できませんでした。', // 'Sorry, there was a problem sending the email. We could not send an email to "{0}".',
2121
'throttled' => 'このIPアドレスからのリクエストが多すぎます。 {0}秒後に再試行できます。', // Too many requests made from this IP address. You may try again in {0} seconds.
2222
'notEnoughPrivilege' => '目的の操作を実行するために必要な権限がありません。', // You do not have the necessary permission to perform the desired operation.
23+
// JWT Exceptions
24+
'invalidJWT' => '(To be translated) The token is invalid.',
25+
'expiredJWT' => '(To be translated) The token has expired.',
26+
'beforeValidJWT' => '(To be translated) The token is not yet available.',
2327

2428
'email' => 'メールアドレス', // 'Email Address',
2529
'username' => 'ユーザー名', // 'Username',

0 commit comments

Comments
 (0)