sel-chat-coach / src /lib /auth /admin-route-handler.ts
tblaisaacliao's picture
support admin login page
4e4104a
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 });
}
};
}