Files
wasl/Backend/app/Services/JwtService.php
2026-06-20 21:55:06 +03:00

57 lines
1.3 KiB
PHP

<?php
namespace App\Services;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use App\Models\User;
use Illuminate\Support\Str;
class JwtService
{
protected string $secret;
protected string $algo;
protected int $ttl;
public function __construct()
{
$this->secret = config('jwt.secret') ?? config('app.key') ?? 'default-secret-key-wasl';
$this->algo = config('jwt.algo', 'HS256');
$this->ttl = config('jwt.ttl', 15); // in minutes
}
/**
* Generate access token for a user.
*/
public function generateToken(User $user, ?string $deviceId = null): string
{
$now = time();
$payload = [
'iss' => config('app.url'),
'iat' => $now,
'nbf' => $now,
'exp' => $now + ($this->ttl * 60),
'sub' => $user->uuid,
'jti' => Str::random(16),
'dev' => $deviceId,
'kyc' => $user->kyc_level,
];
return JWT::encode($payload, $this->secret, $this->algo);
}
/**
* Validate and decode token.
*/
public function validateToken(string $token): ?array
{
try {
$decoded = JWT::decode($token, new Key($this->secret, $this->algo));
return (array) $decoded;
} catch (\Throwable $e) {
report($e);
return null;
}
}
}