jwtSecret = $_ENV['JWT_SECRET'] ?? 'default-secret-fallback'; // Use um fallback seguro em dev } public function __invoke(ServerRequestInterface $request, callable $next) { $authHeader = $request->getHeaderLine('Authorization'); if (empty($authHeader) || !preg_match('/Bearer\s+(.*)/', $authHeader, $matches)) { return ResponseLib::sendFail("Unauthorized: Missing or invalid Authorization header", [], "E_VALIDATE")->withStatus(401); } $token = $matches[1]; try { $decoded = JWT::decode($token, new Key($this->jwtSecret, 'HS256')); $userId = $decoded->sub ?? null; $email = $decoded->email ?? null; if (empty($userId) || empty($email)) { return ResponseLib::sendFail("Unauthorized: Invalid JWT claims", [], "E_VALIDATE")->withStatus(401); } if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof \PDO) { $pdo = $GLOBALS['pdo']; } $stmt = $pdo->prepare('SELECT user_id FROM "user" WHERE user_id = :user_id AND user_email = :email AND user_flag = \'a\''); $stmt->execute(['user_id' => $userId, 'email' => $email]); $user = $stmt->fetch(\PDO::FETCH_ASSOC); if (!$user) { return ResponseLib::sendFail("Unauthorized: Invalid or inactive user", [], "E_VALIDATE")->withStatus(401); } $request = $request ->withAttribute('api_user', $email) ->withAttribute('api_user_id', $userId); return $next($request); } catch (\Exception $e) { return ResponseLib::sendFail("Unauthorized: " . $e->getMessage(), [], "E_VALIDATE")->withStatus(401); } } }