mirror of
https://github.com/prowler-cloud/prowler.git
synced 2026-10-13 23:14:16 +00:00
- Preserve redirects for server-rendered authentication flows - Return explicit unauthorized responses from report route handlers - Cover invalid sessions and callback fallback behavior
57 lines
1.4 KiB
TypeScript
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;
|
|
};
|