From 117f212cc839defb6dfcaf38d838f2ef2f23a4c7 Mon Sep 17 00:00:00 2001 From: Damilola Date: Wed, 24 Jul 2024 10:40:52 +0100 Subject: [PATCH] feat: JWT for user and get auth attempt result --- src/Auth.php | 52 +++++++++++++++++++++++++++++++++--- src/AuthJwtAttemptResult.php | 14 ++++++++++ 2 files changed, 63 insertions(+), 3 deletions(-) create mode 100644 src/AuthJwtAttemptResult.php diff --git a/src/Auth.php b/src/Auth.php index 4fa2d87..c791961 100644 --- a/src/Auth.php +++ b/src/Auth.php @@ -11,6 +11,7 @@ use Cube\Packages\Auth\Exceptions\AuthSetupException; use Firebase\JWT\JWT; use Firebase\JWT\Key; +use InvalidArgumentException; class Auth { @@ -118,9 +119,9 @@ public static function attemptJwt(string $token): AuthJwtResult * @param string $field Model field name * @param string $secret Password * @param array $options Other options to add to jwt - * @return string + * @return AuthJwtAttemptResult */ - public static function attempt2json(string $field, string $secret, array $options = []): string + public static function attempt2json(string $field, string $secret, array $options = []): AuthJwtAttemptResult { [$key, $alg] = self::getJwtConfig(); $config = self::getConfig(); @@ -137,11 +138,16 @@ public static function attempt2json(string $field, string $secret, array $option $options ); - return JWT::encode( + $token = JWT::encode( $payload, $key, $alg ); + + return new AuthJwtAttemptResult( + token: $token, + user: $user, + ); } /** @@ -280,6 +286,46 @@ public static function auth(string $field, string $secret) return $query; } + /** + * Generate jwt for $user + * + * @param ModelInterface $user + * @param array $options + * @return AuthJwtAttemptResult + */ + public static function jwtFor(ModelInterface $user, array $options = array()): AuthJwtAttemptResult + { + $model = self::getConfigField(AuthConfig::MODEL); + + if ($user::class !== $model) { + throw new InvalidArgumentException( + sprintf('$user is not an instance of "%s"', $model) + ); + } + + [$key, $alg] = self::getJwtConfig(); + + $primary_key = array( + 'id' > $user->id + ); + + $payload = array_merge( + $primary_key, + $options + ); + + $token = JWT::encode( + $payload, + $key, + $alg + ); + + return new AuthJwtAttemptResult( + token: $token, + user: $user, + ); + } + /** * Get authenticated user from session * diff --git a/src/AuthJwtAttemptResult.php b/src/AuthJwtAttemptResult.php new file mode 100644 index 0000000..4079b63 --- /dev/null +++ b/src/AuthJwtAttemptResult.php @@ -0,0 +1,14 @@ +