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:
58
app/Controllers/Api/ApiController.php
Normal file
58
app/Controllers/Api/ApiController.php
Normal file
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\Api;
|
||||
|
||||
use Psr\Http\Message\ResponseInterface as Response;
|
||||
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||
|
||||
abstract class ApiController
|
||||
{
|
||||
protected function success(Response $response, $data = null, int $status = 200): Response
|
||||
{
|
||||
$responseData = ['success' => true];
|
||||
|
||||
if ($data !== null) {
|
||||
$responseData['data'] = $data;
|
||||
}
|
||||
|
||||
return $this->json($response, $responseData, $status);
|
||||
}
|
||||
|
||||
protected function error(Response $response, string $message, int $status = 400, array $errors = []): Response
|
||||
{
|
||||
$responseData = [
|
||||
'success' => false,
|
||||
'error' => [
|
||||
'message' => $message,
|
||||
'code' => $status
|
||||
]
|
||||
];
|
||||
|
||||
if (!empty($errors)) {
|
||||
$responseData['error']['details'] = $errors;
|
||||
}
|
||||
|
||||
return $this->json($response, $responseData, $status);
|
||||
}
|
||||
|
||||
protected function json(Response $response, $data, int $status = 200): Response
|
||||
{
|
||||
$response->getBody()->write(json_encode($data));
|
||||
return $response
|
||||
->withHeader('Content-Type', 'application/json')
|
||||
->withStatus($status);
|
||||
}
|
||||
|
||||
protected function getPaginationParams(Request $request): array
|
||||
{
|
||||
$params = $request->getQueryParams();
|
||||
$page = max(1, (int)($params['page'] ?? 1));
|
||||
$perPage = min(100, max(1, (int)($params['per_page'] ?? 20)));
|
||||
|
||||
return [
|
||||
'page' => $page,
|
||||
'per_page' => $perPage,
|
||||
'offset' => ($page - 1) * $perPage
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user