Spaces:
Running
Running
File size: 2,590 Bytes
4e4104a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | import { NextRequest, NextResponse } from 'next/server';
import { requireAdminAuth, createUnauthorizedResponse, createForbiddenResponse } from './index';
export type AdminAuth = {
userId: string;
username: string;
sessionRole: 'admin';
};
/**
* Wrapper for admin API routes without dynamic params
* Handles authentication and error responses automatically
*
* Usage:
* export const GET = withAdminAuth(async (request, auth) => {
* // auth is guaranteed to be valid admin
* return NextResponse.json({ data });
* });
*/
export function withAdminAuth(
handler: (request: NextRequest, auth: AdminAuth) => Promise<Response>
): (request: NextRequest) => Promise<Response> {
return async (request: NextRequest): Promise<Response> => {
try {
const auth = await requireAdminAuth(request);
return handler(request, auth);
} catch (error) {
if (error instanceof Error) {
if (error.message === 'Unauthorized') {
return createUnauthorizedResponse();
}
if (error.message === 'Forbidden') {
return createForbiddenResponse();
}
}
console.error('[Admin Route Handler] Unexpected error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
};
}
/**
* Wrapper for admin API routes WITH dynamic params (e.g., [conversationId])
* Handles authentication and error responses automatically
*
* Usage:
* export const GET = withAdminAuthParams<{ conversationId: string }>(
* async (request, auth, { params }) => {
* const { conversationId } = await params;
* return NextResponse.json({ data });
* }
* );
*/
export function withAdminAuthParams<TParams>(
handler: (
request: NextRequest,
auth: AdminAuth,
context: { params: Promise<TParams> }
) => Promise<Response>
): (request: NextRequest, context: { params: Promise<TParams> }) => Promise<Response> {
return async (
request: NextRequest,
context: { params: Promise<TParams> }
): Promise<Response> => {
try {
const auth = await requireAdminAuth(request);
return handler(request, auth, context);
} catch (error) {
if (error instanceof Error) {
if (error.message === 'Unauthorized') {
return createUnauthorizedResponse();
}
if (error.message === 'Forbidden') {
return createForbiddenResponse();
}
}
console.error('[Admin Route Handler] Unexpected error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
};
}
|