43 lines
2.1 KiB
TypeScript
43 lines
2.1 KiB
TypeScript
import { authorizeMobileSlip, consumeMobileSlipLink, recordMobileSlipError } from "@/lib/commission/mobile-slip";
|
|
import { MAX_SLIP_BYTES, verifyAndCreateTicket } from "@/lib/commission/slip-upload";
|
|
import { boundedBody, errorResponse, HttpError, requireSameOrigin, withUploadSlot } from "@/lib/security/http";
|
|
import { limitRequest } from "@/lib/security/rate-limit";
|
|
|
|
function bearerToken(request: Request) {
|
|
const value = request.headers.get("authorization") ?? "";
|
|
if (!value.startsWith("Bearer ")) throw new HttpError(401, "upload-link-required");
|
|
return value.slice(7);
|
|
}
|
|
|
|
export async function GET(request: Request) {
|
|
try {
|
|
const { checkout, ticketId } = await authorizeMobileSlip(bearerToken(request));
|
|
return Response.json({ amountBaht: checkout.amountBaht, complete: Boolean(ticketId) },
|
|
{ headers: { "Cache-Control": "no-store" } });
|
|
} catch (cause) { return errorResponse(cause); }
|
|
}
|
|
|
|
export async function POST(request: Request) {
|
|
let handoff: Awaited<ReturnType<typeof authorizeMobileSlip>> | undefined;
|
|
try {
|
|
requireSameOrigin(request);
|
|
handoff = await authorizeMobileSlip(bearerToken(request));
|
|
await limitRequest("commission-mobile-slip-token", handoff.digest, 10);
|
|
if (handoff.ticketId) return Response.json({ complete: true }, { headers: { "Cache-Control": "no-store" } });
|
|
if (!request.headers.get("content-type")?.startsWith("multipart/form-data;"))
|
|
throw new HttpError(415, "expected-multipart");
|
|
const { checkout, digest } = handoff;
|
|
const result = await withUploadSlot(async () => {
|
|
const form = await boundedBody(request, MAX_SLIP_BYTES + 64 * 1024).formData();
|
|
return verifyAndCreateTicket(checkout, form.get("file"));
|
|
});
|
|
await consumeMobileSlipLink(checkout.id, digest).catch(() => undefined);
|
|
return Response.json({ complete: true }, {
|
|
status: result.created ? 201 : 200, headers: { "Cache-Control": "no-store" },
|
|
});
|
|
} catch (cause) {
|
|
if (handoff) await recordMobileSlipError(handoff.digest, handoff.checkout.userId, cause).catch(() => undefined);
|
|
return errorResponse(cause);
|
|
}
|
|
}
|