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:
Lars Behrends
2025-12-31 10:08:49 +01:00
parent 1b053148f0
commit b728b0c72d
18 changed files with 858 additions and 27 deletions

View File

@@ -0,0 +1,73 @@
<?php
namespace App\Middleware;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use App\Services\AuthService;
class ApiAuthMiddleware implements MiddlewareInterface
{
private AuthService $authService;
private array $publicRoutes = [
'/api/auth/check',
'/api/auth/login',
'/api/auth/register',
'/api/status'
];
public function __construct(AuthService $authService)
{
$this->authService = $authService;
}
public function process(Request $request, RequestHandler $handler): Response
{
$path = $request->getUri()->getPath();
// Skip authentication for public routes
if (in_array($path, $this->publicRoutes)) {
return $handler->handle($request);
}
// Get token from Authorization header
$authHeader = $request->getHeaderLine('Authorization');
if (empty($authHeader) || !preg_match('/Bearer\s(\S+)/', $authHeader, $matches)) {
return $this->createErrorResponse(401, 'Missing or invalid authorization token');
}
$token = $matches[1];
try {
// Verify token and get user
$user = $this->authService->verifyToken($token);
if (!$user) {
return $this->createErrorResponse(401, 'Invalid or expired token');
}
// Add user to request attributes for use in controllers
$request = $request->withAttribute('user', $user);
return $handler->handle($request);
} catch (\Exception $e) {
return $this->createErrorResponse(500, 'Authentication error');
}
}
private function createErrorResponse(int $status, string $message): Response
{
$response = new \Slim\Psr7\Response($status);
$response->getBody()->write(json_encode([
'success' => false,
'error' => [
'code' => $status,
'message' => $message
]
]));
return $response->withHeader('Content-Type', 'application/json');
}
}