44 lines
1.5 KiB
TypeScript
44 lines
1.5 KiB
TypeScript
// Backend calls from server components, with the visitor's session.
|
|||
|
|
import "server-only";
|
||
|
|
|
||
|
|
import { cookies } from "next/headers";
|
||
|
|
import { redirect } from "next/navigation";
|
||
|
|
|
||
|
|
import type { Me } from "./types";
|
||
|
|
|
||
|
|
export const BACKEND_URL = (process.env.BACKEND_URL ?? "http://localhost:8081").replace(/\/$/, "");
|
||
|
|
export const SESSION_COOKIE = "sf_session";
|
||
|
|
|
||
|
|
export class BackendError extends Error {
|
||
|
|
constructor(
|
||
|
|
public status: number,
|
||
|
|
message: string,
|
||
|
|
) {
|
||
|
|
super(message);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
/** GET from the backend as the logged-in visitor; `null` on 401/404. */
|
||
|
|
export async function backendGet<T>(path: string): Promise<T | null> {
|
||
|
|
const token = (await cookies()).get(SESSION_COOKIE)?.value;
|
||
|
|
const headers: HeadersInit = token ? { authorization: `Bearer ${token}` } : {};
|
||
|
|
const res = await fetch(`${BACKEND_URL}${path}`, { headers, cache: "no-store" });
|
||
|
|
if (res.status === 401 || res.status === 404) return null;
|
||
|
|
if (!res.ok) throw new BackendError(res.status, `${path}: HTTP ${res.status}`);
|
||
|
|
return (await res.json()) as T;
|
||
|
|
}
|
||
|
|
|
||
|
|
/** The logged-in user, or `null`. */
|
||
|
|
export async function getMe(): Promise<Me | null> {
|
||
|
|
const token = (await cookies()).get(SESSION_COOKIE)?.value;
|
||
|
|
if (!token) return null;
|
||
|
|
return backendGet<Me>("/v1/me");
|
||
|
|
}
|
||
|
|
|
||
|
|
/** The logged-in user; sends visitors to the login page. */
|
||
|
|
export async function requireMe(from: string): Promise<Me> {
|
||
|
|
const me = await getMe();
|
||
|
|
if (!me) redirect(`/belepes?vissza=${encodeURIComponent(from)}`);
|
||
|
|
return me;
|
||
|
|
}
|