JwtAuthMiddleware.php 2.2 KB

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