fix(security): enforce order status state machine in admin endpoint
Add VALID_TRANSITIONS map and validate each status change before updating the database. Prevents skipping payment (e.g. PENDING→FULFILLED) or reopening closed orders.
This commit is contained in:
@@ -2,6 +2,14 @@ import { NextRequest, NextResponse } from 'next/server'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { getCurrentUser } from '@/lib/auth'
|
||||
|
||||
const VALID_TRANSITIONS: Record<string, string[]> = {
|
||||
PENDING: ['PAID', 'CANCELLED'],
|
||||
PAID: ['FULFILLED', 'REFUNDED', 'CANCELLED'],
|
||||
FULFILLED: ['REFUNDED'],
|
||||
CANCELLED: [],
|
||||
REFUNDED: [],
|
||||
}
|
||||
|
||||
async function requireAdmin() {
|
||||
const user = await getCurrentUser()
|
||||
if (!user || (user.role !== 'ADMIN' && user.role !== 'OWNER')) return null
|
||||
@@ -50,6 +58,17 @@ export async function PUT(
|
||||
return NextResponse.json({ error: 'Invalid status' }, { status: 400 })
|
||||
}
|
||||
|
||||
const currentOrder = await prisma.order.findUnique({ where: { id: params.id }, select: { status: true } })
|
||||
if (!currentOrder) return NextResponse.json({ error: 'Order not found' }, { status: 404 })
|
||||
|
||||
const allowed = VALID_TRANSITIONS[currentOrder.status] ?? []
|
||||
if (!allowed.includes(status)) {
|
||||
return NextResponse.json(
|
||||
{ error: `Cannot transition order from ${currentOrder.status} to ${status}` },
|
||||
{ status: 422 }
|
||||
)
|
||||
}
|
||||
|
||||
const order = await prisma.order.update({
|
||||
where: { id: params.id },
|
||||
data: { status: status as 'PENDING' | 'PAID' | 'CANCELLED' | 'REFUNDED' | 'FULFILLED' },
|
||||
|
||||
Reference in New Issue
Block a user