JwtAuthMiddleware.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace Middlewares;
  3. use Firebase\JWT\JWT;
  4. use Firebase\JWT\Key;
  5. use Libs\ResponseLib;
  6. use Psr\Http\Message\ServerRequestInterface;
  7. class JwtAuthMiddleware
  8. {
  9. private string $jwtSecret;
  10. public function __construct()
  11. {
  12. // Carrega a chave secreta do .env (ex: JWT_SECRET=seu-segredo-aqui)
  13. $this->jwtSecret = $_ENV['JWT_SECRET'] ?? 'default-secret-fallback'; // Use um fallback seguro em dev
  14. }
  15. public function __invoke(ServerRequestInterface $request, callable $next)
  16. {
  17. $authHeader = $request->getHeaderLine('Authorization');
  18. if (empty($authHeader) || !preg_match('/Bearer\s+(.*)/', $authHeader, $matches)) {
  19. return ResponseLib::sendFail("Unauthorized: Missing or invalid Authorization header", [], "E_VALIDATE")->withStatus(401);
  20. }
  21. $token = $matches[1];
  22. try {
  23. $decoded = JWT::decode($token, new Key($this->jwtSecret, 'HS256'));
  24. $userId = $decoded->sub ?? null;
  25. $email = $decoded->email ?? null;
  26. if (empty($userId) || empty($email)) {
  27. return ResponseLib::sendFail("Unauthorized: Invalid JWT claims", [], "E_VALIDATE")->withStatus(401);
  28. }
  29. if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof \PDO) {
  30. $pdo = $GLOBALS['pdo'];
  31. }
  32. $stmt = $pdo->prepare('SELECT user_id FROM "user" WHERE user_id = :user_id AND user_email = :email AND user_flag = \'a\'');
  33. $stmt->execute(['user_id' => $userId, 'email' => $email]);
  34. $user = $stmt->fetch(\PDO::FETCH_ASSOC);
  35. if (!$user) {
  36. return ResponseLib::sendFail("Unauthorized: Invalid or inactive user", [], "E_VALIDATE")->withStatus(401);
  37. }
  38. $request = $request
  39. ->withAttribute('api_user', $email)
  40. ->withAttribute('api_user_id', $userId);
  41. return $next($request);
  42. } catch (\Exception $e) {
  43. return ResponseLib::sendFail("Unauthorized: " . $e->getMessage(), [], "E_VALIDATE")->withStatus(401);
  44. }
  45. }
  46. }