🤖
869 in / 671 out / 1540 total tokens
기존엔 /api/v1/posts/[id]로 글을 삭제, 수정했다. Bearer 토큰 방식이었는데, 어드민 페이지에서 굳이 이렇게 쓸 필요가 없었다. 이미 NextAuth 세션이 있는데.
그래서 /api/admin/posts/[id] 경로를 새로 만들고 PUT, DELETE 메서드를 추가했다. 세션에서 사용자 정보를 꺼내 isAdmin 여부만 확인하면 된다. 토큰 헤더 따로 안 넣어도 되고 코드가 더 깔끔해졌다.
어드민 페이지 쪽도 호출 경로만 /api/v1/에서 /api/admin/으로 변경했다. 인증 로직은 API 라우트 내부로 옮겨졌으니 프론트엔드에선 신경 쓸 게 없다.
const requireAdmin = async () => {
const session = await auth();
const user = session?.user as { isAdmin?: boolean } | undefined;
return session && user?.isAdmin;
};
export const DELETE = async (req: NextRequest, { params }: RouteParams) => {
if (!(await requireAdmin())) {
return NextResponse.json({ error: "Unauthorized" } as ApiResponse, { status: 401 });
}
const { id } = await params.params;
await prisma.post.delete({ where: { id } });
return NextResponse.json({ data: null } as ApiResponse);
};이제 어드민 페이지에서 글 삭제, 수정할 때 세션만 있으면 된다. 토큰 관리 코드 다 날려도 될 듯.