Files
Vault/lib/auth-check.ts
T
twotalesanimation 81ad7e4ea9 Initial commit
2026-06-11 10:46:09 +02:00

33 lines
922 B
TypeScript

// lib/auth-check.ts
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth-options';
import { redirect } from 'next/navigation';
/**
* Require a logged-in user. If not logged in, redirect to /login.
* Returns the session object when present.
*
* Use this helper from server components / app-route handlers.
*/
export async function requireUser(redirectTo = '/login') {
const session = await getServerSession(authOptions);
if (!session?.user?.email) {
// server-side redirect (preferred for pages)
redirect(redirectTo);
}
return session;
}
/**
* Use this variant for API routes where you want JSON 401/403 instead of redirect.
*/
export async function requireUserApi() {
const session = await getServerSession(authOptions);
if (!session?.user?.email) {
const err: any = new Error('Unauthorized');
err.status = 401;
throw err;
}
return session;
}