first commit
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
namespace WorkbloomERP\Utils;
|
||||
|
||||
use Exception;
|
||||
use Firebase\JWT\JWT;
|
||||
use Firebase\JWT\Key;
|
||||
use DateTimeImmutable;
|
||||
|
||||
class JwtUtil {
|
||||
private int $ttl;
|
||||
private string $issuer;
|
||||
private string $secretKey;
|
||||
private string $algorithm;
|
||||
|
||||
public function __construct(string $secretKey, string $algorithm = 'HS256', int $ttl = 3600, string $issuer = 'workbloomerp') {
|
||||
if (empty($secretKey)) {
|
||||
throw new Exception(message: 'JWT secret não configurado.');
|
||||
}
|
||||
$this->ttl = $ttl;
|
||||
$this->secretKey = $secretKey;
|
||||
$this->algorithm = $algorithm;
|
||||
$this->issuer = $issuer;
|
||||
}
|
||||
|
||||
public function generate(array $payload): string {
|
||||
$defaultClaims = [];
|
||||
$defaultClaims['iat'] = $payload['iat'] ?? (new DateTimeImmutable())->getTimestamp();
|
||||
$defaultClaims['exp'] = $payload['exp'] ?? ((new DateTimeImmutable())->modify("+{$this->ttl} seconds")->getTimestamp());
|
||||
|
||||
$finalPayload = array_merge($payload, $defaultClaims);
|
||||
return JWT::encode(
|
||||
payload: $finalPayload,
|
||||
key: $this->secretKey,
|
||||
alg: $this->algorithm
|
||||
);
|
||||
}
|
||||
|
||||
public function validate(string $token): object {
|
||||
return JWT::decode(
|
||||
jwt: $token,
|
||||
keyOrKeyArray: new Key(
|
||||
keyMaterial: $this->secretKey,
|
||||
algorithm: $this->algorithm
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user