36 lines
1.1 KiB
TypeScript
36 lines
1.1 KiB
TypeScript
|
|
import "server-only";
|
||
|
|
import { headers } from "next/headers";
|
||
|
|
import { redirect, notFound } from "next/navigation";
|
||
|
|
import { auth } from "./auth";
|
||
|
|
|
||
|
|
/** Returns the current session (or null) using request headers. */
|
||
|
|
export async function getServerSession() {
|
||
|
|
return auth.api.getSession({ headers: await headers() });
|
||
|
|
}
|
||
|
|
|
||
|
|
/** Require a logged-in user; redirect to sign-in otherwise. */
|
||
|
|
export async function requireAuth(redirectTo?: string) {
|
||
|
|
const session = await getServerSession();
|
||
|
|
if (!session) {
|
||
|
|
const target = redirectTo ? `?redirect=${encodeURIComponent(redirectTo)}` : "";
|
||
|
|
redirect(`/sign-in${target}`);
|
||
|
|
}
|
||
|
|
return session;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Require a platform admin. Returns 404 (not 403) for non-admins so the admin
|
||
|
|
* surface isn't disclosed to ordinary users.
|
||
|
|
*/
|
||
|
|
export async function requireAdmin() {
|
||
|
|
const session = await getServerSession();
|
||
|
|
if (!session || session.user.role !== "admin") notFound();
|
||
|
|
return session;
|
||
|
|
}
|
||
|
|
|
||
|
|
/** Convenience: the active organization id from the session (if any). */
|
||
|
|
export async function getActiveOrgId() {
|
||
|
|
const session = await getServerSession();
|
||
|
|
return session?.session.activeOrganizationId ?? null;
|
||
|
|
}
|