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:
62
app/Controllers/Api/BaseApiController.php
Normal file
62
app/Controllers/Api/BaseApiController.php
Normal file
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
|
||||
namespace App\Controllers\Api;
|
||||
|
||||
use Psr\Http\Message\ResponseInterface as Response;
|
||||
use Psr\Http\Message\ServerRequestInterface as Request;
|
||||
use App\Controllers\Controller;
|
||||
|
||||
class BaseApiController extends Controller
|
||||
{
|
||||
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 getPaginationParams(Request $request): array
|
||||
{
|
||||
$params = $request->getQueryParams();
|
||||
$page = max(1, (int)($params['page'] ?? 1));
|
||||
$perPage = min(50, max(1, (int)($params['per_page'] ?? 20)));
|
||||
|
||||
return [
|
||||
'page' => $page,
|
||||
'per_page' => $perPage,
|
||||
'offset' => ($page - 1) * $perPage
|
||||
];
|
||||
}
|
||||
|
||||
protected function getAuthUser(Request $request): ?array
|
||||
{
|
||||
return $request->getAttribute('user');
|
||||
}
|
||||
|
||||
protected function isAdmin(Request $request): bool
|
||||
{
|
||||
$user = $this->getAuthUser($request);
|
||||
return $user && ($user['is_admin'] ?? false);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user