25 lines
980 B
TypeScript
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;
|
|
}
|