ExternalAuthMiddleware.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace Middlewares;
  3. use Libs\ResponseLib;
  4. use Models\ApplicationModel;
  5. use Psr\Http\Message\ServerRequestInterface;
  6. use Middlewares\JwtAuthMiddleware;
  7. use Middlewares\HmacAuthMiddleware;
  8. use Middlewares\ExternalJwtAuthMiddleware;
  9. class ExternalAuthMiddleware
  10. {
  11. private ApplicationModel $apps;
  12. private string $appIdHeader;
  13. public function __construct()
  14. {
  15. $this->apps = new ApplicationModel();
  16. $this->appIdHeader = $_ENV['APP_ID_HEADER'] ?? 'x-app-id';
  17. }
  18. public function __invoke(ServerRequestInterface $request, callable $next)
  19. {
  20. // 1) Discover application by ID header (or default)
  21. $idHeaderVal = $request->getHeaderLine($this->appIdHeader);
  22. $id = $idHeaderVal !== '' ? (int)$idHeaderVal : (int)($_ENV['DEFAULT_APPLICATION_ID'] ?? 0);
  23. if ($id <= 0) {
  24. return ResponseLib::sendFail('Unauthorized: Missing application id', [], 'E_VALIDATE')->withStatus(401);
  25. }
  26. $app = $this->apps->getById($id);
  27. if (!$app) {
  28. return ResponseLib::sendFail('Unauthorized: Application not found', [], 'E_VALIDATE')->withStatus(401);
  29. }
  30. // must be active
  31. if (($app['aplication_flag'] ?? '') !== 'a') {
  32. return ResponseLib::sendFail('Unauthorized: Inactive application', [], 'E_VALIDATE')->withStatus(401);
  33. }
  34. $method = strtolower($app['aplication_auth_method'] ?? 'external_jwt');
  35. // 2) Route based on method
  36. if ($method === 'jwt') {
  37. $jwt = new JwtAuthMiddleware();
  38. return $jwt($request, $next);
  39. }
  40. if ($method === 'hmac') {
  41. $hmac = new HmacAuthMiddleware();
  42. return $hmac($request, $next);
  43. }
  44. // Default: external_jwt
  45. if (empty($app['aplication_url'])) {
  46. return ResponseLib::sendFail('Unauthorized: Application URL not configured for external auth', [], 'E_VALIDATE')->withStatus(401);
  47. }
  48. $external = new ExternalJwtAuthMiddleware($app['aplication_url']);
  49. return $external($request, $next);
  50. }
  51. }