Files
prowler/ui/lib/server-auth.ts
T
Alan Buscaglia 627d3b6199 fix(ui): return 401 for unauthenticated report routes
- Preserve redirects for server-rendered authentication flows
- Return explicit unauthorized responses from report route handlers
- Cover invalid sessions and callback fallback behavior
2026-07-29 11:35:14 +02:00

57 lines
1.4 KiB
TypeScript

import "server-only";
import { headers } from "next/headers";
import { redirect } from "next/navigation";
const CURRENT_PATH_HEADER = "x-prowler-current-path";
const DEFAULT_CALLBACK_PATH = "/";
export const redirectToSignIn = async (): Promise<never> => {
const requestHeaders = await headers();
const callbackUrl =
requestHeaders.get(CURRENT_PATH_HEADER) ?? DEFAULT_CALLBACK_PATH;
const searchParams = new URLSearchParams({ callbackUrl });
redirect(`/sign-in?${searchParams.toString()}`);
};
type SessionError = "RefreshAccessTokenError" | (string & {});
export const getAuthHeadersIfAvailable = (
accessToken: string | undefined,
options?: { contentType?: boolean },
sessionError?: SessionError,
) => {
if (!accessToken || sessionError === "RefreshAccessTokenError") {
return null;
}
const authHeaders: Record<string, string> = {
Accept: "application/vnd.api+json",
Authorization: `Bearer ${accessToken}`,
};
if (options?.contentType) {
authHeaders["Content-Type"] = "application/vnd.api+json";
}
return authHeaders;
};
export const getRequiredAuthHeaders = async (
accessToken: string | undefined,
options?: { contentType?: boolean },
sessionError?: SessionError,
) => {
const authHeaders = getAuthHeadersIfAvailable(
accessToken,
options,
sessionError,
);
if (!authHeaders) {
return redirectToSignIn();
}
return authHeaders;
};