Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 49 additions & 3 deletions src/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use Cube\Packages\Auth\Exceptions\AuthSetupException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use InvalidArgumentException;

class Auth
{
Expand Down Expand Up @@ -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();
Expand All @@ -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,
);
}

/**
Expand Down Expand Up @@ -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
*
Expand Down
14 changes: 14 additions & 0 deletions src/AuthJwtAttemptResult.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace Cube\Packages\Auth;

use Cube\Interfaces\ModelInterface;

readonly class AuthJwtAttemptResult
{
public function __construct(
public ModelInterface $user,
public string $token
) {
}
}