File size: 1,995 Bytes
cf14c12 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | <?php
declare(strict_types=1);
namespace Presentation\Jwt;
use DateTime;
use DateTimeInterface;
use DomainException;
use Firebase\JWT\BeforeValidException;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use InvalidArgumentException;
use Firebase\JWT\SignatureInvalidException;
use Ramsey\Uuid\Uuid;
use UnexpectedValueException;
class UserJwt
{
/**
* @param string $jwt
* @return UserJwt
* @throws InvalidArgumentException
* @throws DomainException
* @throws UnexpectedValueException
* @throws SignatureInvalidException
* @throws BeforeValidException
* @throws ExpiredException
*/
public static function createFromJwtString(string $jwt): UserJwt
{
$key = new Key(env('JWT_TOKEN'), 'HS256');
$payload = JWT::decode($jwt, $key);
$exp = null;
if (isset($payload->exp)) {
$exp = new DateTime('@' . $payload->exp);
}
return new UserJwt(
$payload->uuid,
$payload->is_admin,
$exp
);
}
/**
* @param string $uuid
* @param bool $isAdmin
* @param null|DateTimeInterface $expiresAt
* @return void
*/
public function __construct(
private string $uuid,
private bool $isAdmin = false,
private ?DateTimeInterface $expiresAt = null
) {
}
/**
* @return string
* @throws DomainException
*/
public function getJwtString(): string
{
$payload = [
'uuid' => $this->uuid,
'iat' => time(),
'jti' => Uuid::uuid4()->toString(),
'is_admin' => $this->isAdmin
];
if ($this->expiresAt) {
$payload['exp'] = $this->expiresAt->getTimestamp();
}
return JWT::encode($payload, env('JWT_TOKEN'), 'HS256');
}
/** @return string */
public function getUuid(): string
{
return $this->uuid;
}
}
|