- Introduce `AuthWrapper` component for streamlined session-based layouts and authentication handling. - Add new utilities (`tokenUtils.ts`) for JWT decoding, token expiration checks, and refresh operations via Keycloak. - Refactor `serverCall` and `authOptions` to use centralized token refresh logic, removing redundant implementations. - Implement `ClientSessionProvider` for consistent session management across the client application. - Simplify `RootLayout` by delegating authentication enforcement to `AuthWrapper`.
33 lines
1.1 KiB
TypeScript
33 lines
1.1 KiB
TypeScript
import {getServerSession} from "next-auth";
|
|
import {authOptions} from "@/lib/api/auth/authOptions";
|
|
|
|
export async function serverCall(
|
|
path: string,
|
|
method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH",
|
|
body?: unknown
|
|
): Promise<Response> {
|
|
const url = `${process.env.INTERNAL_BACKEND_URL ?? "http://localhost:8080"}${path}`;
|
|
const session = await getServerSession(authOptions);
|
|
|
|
const headers: Record<string, string> = {
|
|
"Content-Type": "application/json",
|
|
};
|
|
|
|
if (session?.accessToken) {
|
|
// Use the access token from the session directly
|
|
// Token refresh is handled by the JWT callback in authOptions.ts
|
|
headers["Authorization"] = `Bearer ${session.accessToken}`;
|
|
// console.log("[auth] Using access token from session for API call");
|
|
} else {
|
|
console.warn("[auth] No access token available in session for API call");
|
|
}
|
|
|
|
console.log("[api] Calling backend API - [" + method + "]", path, body ?? "");
|
|
|
|
return fetch(url, {
|
|
method,
|
|
headers,
|
|
body: body ? JSON.stringify(body) : undefined,
|
|
});
|
|
}
|