mirror of
https://github.com/ceratic/MediaCollectorLibary.git
synced 2026-05-13 23:56:46 +02:00
Enhance API functionality and improve JWT authentication
- Added JWT authentication support in AuthService and JwtService. - Implemented token generation and refresh mechanisms. - Updated ApiAuthMiddleware to handle authentication for protected routes. - Created ApiController and BaseApiController for standardized API responses. - Developed MediaController for managing media items with pagination and search capabilities. - Introduced DocsController for serving API documentation via Swagger UI. - Added routes for API documentation and media management. - Improved error handling and response formatting across API endpoints. - Updated composer.json to include necessary JWT and Swagger UI dependencies.
This commit is contained in:
63
app/Services/JwtService.php
Normal file
63
app/Services/JwtService.php
Normal file
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use Firebase\JWT\JWT;
|
||||
use Firebase\JWT\Key;
|
||||
use Firebase\JWT\ExpiredException;
|
||||
use DomainException;
|
||||
use UnexpectedValueException;
|
||||
|
||||
class JwtService
|
||||
{
|
||||
private $secret;
|
||||
private $algo;
|
||||
private $expiration;
|
||||
private $leeway;
|
||||
|
||||
public function __construct(array $config)
|
||||
{
|
||||
$this->secret = $config['secret'];
|
||||
$this->algo = $config['algo'];
|
||||
$this->expiration = $config['expiration'] ?? 3600;
|
||||
$this->leeway = $config['leeway'] ?? 60;
|
||||
|
||||
JWT::$leeway = $this->leeway;
|
||||
}
|
||||
|
||||
public function encode(array $payload): string
|
||||
{
|
||||
$now = time();
|
||||
$payload = array_merge([
|
||||
'iat' => $now,
|
||||
'exp' => $now + $this->expiration,
|
||||
], $payload);
|
||||
|
||||
return JWT::encode($payload, $this->secret, $this->algo);
|
||||
}
|
||||
|
||||
public function decode(string $token): ?array
|
||||
{
|
||||
try {
|
||||
$decoded = JWT::decode($token, new Key($this->secret, $this->algo));
|
||||
return (array) $decoded;
|
||||
} catch (ExpiredException $e) {
|
||||
// Token expired
|
||||
return null;
|
||||
} catch (DomainException | UnexpectedValueException $e) {
|
||||
// Invalid token
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public function refresh(string $token): ?string
|
||||
{
|
||||
$payload = $this->decode($token);
|
||||
if (!$payload) {
|
||||
return null;
|
||||
}
|
||||
|
||||
unset($payload['iat'], $payload['exp'], $payload['nbf']);
|
||||
return $this->encode($payload);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user