35 lines
1.2 KiB
PHP
Executable File
35 lines
1.2 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Classes;
|
|
|
|
class JWT
|
|
{
|
|
public function __construct(private string $secret = '') {}
|
|
|
|
public function create(array $payload): string
|
|
{
|
|
$payload['created_at'] = time();
|
|
$payload['expire_at'] = time() + ($payload['expire_at'] ?? 3600);
|
|
|
|
$h = $this->b64(json_encode(['typ'=>'JWT','alg'=>'HS256']));
|
|
$p = $this->b64(json_encode($payload));
|
|
$s = $this->b64(hash_hmac('sha256', "$h.$p",'mobinEshaghi'. $this->secret, true));
|
|
|
|
return "$h.$p.$s";
|
|
}
|
|
|
|
public function decode(string $jwt): false|array
|
|
{
|
|
[$h,$p,$s] = explode('.', $jwt) + [null,null,null];
|
|
if (!$h || !$p || !$s) return false;
|
|
|
|
if (!hash_equals($this->b64(hash_hmac('sha256', "$h.$p", 'mobinEshaghi'.$this->secret, true)), $s)) return false;
|
|
|
|
$d = json_decode($this->b64Decode($p), true);
|
|
return isset($d['expire_at']) && ($d['timeLeft']=$d['expire_at']-time())<=0 ? false : $d;
|
|
}
|
|
|
|
private function b64(string $data): string { return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); }
|
|
private function b64Decode(string $data): string { return base64_decode(strtr($data, '-_', '+/')); }
|
|
}
|