| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960 |
- <?php
- namespace Middlewares;
- use Libs\ResponseLib;
- use Models\ApplicationModel;
- use Psr\Http\Message\ServerRequestInterface;
- use Middlewares\JwtAuthMiddleware;
- use Middlewares\HmacAuthMiddleware;
- use Middlewares\ExternalJwtAuthMiddleware;
- class ExternalAuthMiddleware
- {
- private ApplicationModel $apps;
- private string $appIdHeader;
- public function __construct()
- {
- $this->apps = new ApplicationModel();
- $this->appIdHeader = $_ENV['APP_ID_HEADER'] ?? 'x-app-id';
- }
- public function __invoke(ServerRequestInterface $request, callable $next)
- {
- // 1) Discover application by ID header (or default)
- $idHeaderVal = $request->getHeaderLine($this->appIdHeader);
- $id = $idHeaderVal !== '' ? (int)$idHeaderVal : (int)($_ENV['DEFAULT_APPLICATION_ID'] ?? 0);
- if ($id <= 0) {
- return ResponseLib::sendFail('Unauthorized: Missing application id', [], 'E_VALIDATE')->withStatus(401);
- }
- $app = $this->apps->getById($id);
- if (!$app) {
- return ResponseLib::sendFail('Unauthorized: Application not found', [], 'E_VALIDATE')->withStatus(401);
- }
- // must be active
- if (($app['aplication_flag'] ?? '') !== 'a') {
- return ResponseLib::sendFail('Unauthorized: Inactive application', [], 'E_VALIDATE')->withStatus(401);
- }
- $method = strtolower($app['aplication_auth_method'] ?? 'external_jwt');
-
- // 2) Route based on method
- if ($method === 'jwt') {
- $jwt = new JwtAuthMiddleware();
- return $jwt($request, $next);
- }
- if ($method === 'hmac') {
- $hmac = new HmacAuthMiddleware();
- return $hmac($request, $next);
- }
- // Default: external_jwt
- if (empty($app['aplication_url'])) {
- return ResponseLib::sendFail('Unauthorized: Application URL not configured for external auth', [], 'E_VALIDATE')->withStatus(401);
- }
- $external = new ExternalJwtAuthMiddleware($app['aplication_url']);
- return $external($request, $next);
- }
- }
|