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; $userEmail = $decoded->email ?? $decoded->username ?? null; if (empty($userId) || empty($userEmail)) { return ResponseLib::sendFail("Unauthorized: Invalid JWT claims", [], "E_VALIDATE")->withStatus(401); } $pdo = Database::pdo(); $stmt = $pdo->prepare("SELECT user_id, user_email FROM \"user\" WHERE user_id = :user_id AND user_email = :user_email AND user_deleted_at = 'infinity'"); $stmt->execute(['user_id' => $userId, 'user_email' => mb_strtolower(trim($userEmail))]); $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', $user['user_email']) ->withAttribute('api_user_id', $user['user_id']) ->withAttribute('user_email', $user['user_email']) ->withAttribute('user_id', $user['user_id']); return $next($request); } catch (\Exception $e) { return ResponseLib::sendFail("Unauthorized: " . $e->getMessage(), [], "E_VALIDATE")->withStatus(401); } } }