templates2.Content.Next/lib/server/guard.ts
w4c-templates 3caefb8833
Some checks are pending
CI / quality (push) Waiting to run
chore(template): publish Content.Next
2026-10-11 23:29:57 +03:00

25 lines
980 B
TypeScript

import 'server-only';
import { NextResponse } from 'next/server';
import { getCurrentUser, type SessionUser } from './auth';
import { canAuthor } from '@/lib/rbac';
export type Guarded = { user: SessionUser; error?: undefined } | { user?: undefined; error: NextResponse };
const forbidden = () => NextResponse.json({ error: 'Forbidden' }, { status: 403 });
/** API guard: a signed-in author (admin | editor) may read the content admin API. */
export async function apiStaff(): Promise<Guarded> {
const user = await getCurrentUser();
if (!user) return { error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) };
if (!canAuthor(user.role)) return { error: forbidden() };
return { user };
}
/** API guard for mutations (create/update/publish/delete) — admin | editor. */
export async function apiWrite(): Promise<Guarded> {
const g = await apiStaff();
if (g.error) return g;
if (!canAuthor(g.user.role)) return { error: forbidden() };
return g;
}