Files
Claudecio Martins a951944997 first commit
2026-06-16 10:04:10 -03:00

47 lines
1.4 KiB
PHP

<?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
)
);
}
}