Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 19x 17x 17x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 5x 1x 1x 4x 4x 4x 4x 4x 3x 3x 3x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 13x 13x 13x 13x 13x 13x 13x 8x 8x 8x 8x 11x 11x 11x 8x 8x 8x 5x 5x 5x 5x 5x 14x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 14x 3x 3x 3x 3x 2x 3x 3x 3x 1x 1x | import { NextRequest, NextResponse } from "next/server";
import {
withAuth,
withErrorHandling,
successResponse,
createdResponse,
validationErrorResponse,
ApiSuccessResponse,
ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";
import { prisma } from "@/lib/prisma";
import { addSecurityHeaders } from "@/lib/security";
import {
checkRateLimit,
rateLimitPresets,
getRateLimitInfo } from "@/lib/security";
import { z } from "zod";
import { Prisma, Address } from "@prisma/client";
import { Session } from "next-auth";
// Address schema
const AddressSchema = z.object({
type: z.enum(["SHIPPING", "BILLING"]),
// Contact Information
name: z.string().min(1, "Name is required").max(100),
email: z.string().email().max(255).optional().nullable(),
phone: z.string().max(20).optional().nullable(),
// Address Fields
street: z.string().min(5).max(255),
city: z.string().min(2).max(100),
state: z.string().min(2).max(100),
zipCode: z.string().min(3).max(20),
country: z.string().min(2).max(100),
isDefault: z.boolean().optional() });
// Rate limit helper - returns error response if rate limited
function checkRateLimitForAddresses(
request: NextRequest,
action: "get" | "post"
): NextResponse<ApiErrorResponse> | null {
const ip =
request.headers.get("x-forwarded-for") ||
request.headers.get("x-real-ip") ||
"unknown";
const key = `api-user-addresses-${action}-${ip}`;
if (
!checkRateLimit(
key,
rateLimitPresets.standard.limit,
rateLimitPresets.standard.windowMs
)
) {
//
const rateLimitInfo = getRateLimitInfo(key, rateLimitPresets.standard.limit);
return addSecurityHeaders(
NextResponse.json<ApiErrorResponse>(
{
success: false,
error: {
code: "RATE_LIMIT_EXCEEDED",
message: "Rate limit exceeded" } },
{
status: 429,
headers: {
"X-RateLimit-Limit": rateLimitInfo.limit.toString(),
"X-RateLimit-Remaining": rateLimitInfo.remaining.toString(),
"X-RateLimit-Reset": rateLimitInfo.resetTime } }
)
);
}
return null;
}
// GET /api/user/addresses - Get user's addresses
async function handleGet(
request: NextRequest,
_context: RouteContext | undefined,
session: Session
): Promise<NextResponse<ApiSuccessResponse<Address[]> | ApiErrorResponse>> {
// Rate limiting
const rateLimitResponse = checkRateLimitForAddresses(request, "get");
if (rateLimitResponse) {
return rateLimitResponse;
}
const userId = session.user.id;
// Get query parameter for filtering by type
const { searchParams } = new URL(request.url);
const type = searchParams.get("type");
// Build where clause
const where: Prisma.AddressWhereInput = { userId };
if (type && (type === "SHIPPING" || type === "BILLING")) {
where.type = type;
}
// Fetch addresses
const addresses = await prisma.address.findMany({
where,
orderBy: [{ isDefault: "desc" }, { createdAt: "desc" }] });
return addSecurityHeaders(successResponse(addresses));
}
// POST /api/user/addresses - Create new address
async function handlePost(
request: NextRequest,
_context: RouteContext | undefined,
session: Session
): Promise<NextResponse<ApiSuccessResponse<Address> | ApiErrorResponse>> {
// Rate limiting
const rateLimitResponse = checkRateLimitForAddresses(request, "post");
if (rateLimitResponse) {
return rateLimitResponse;
}
const userId = session.user.id;
const body = await request.json();
// Validate input
const validationResult = AddressSchema.safeParse(body);
if (!validationResult.success) {
return addSecurityHeaders(
validationErrorResponse(
"Invalid address data",
validationResult.error.issues.map((issue) => ({
field: issue.path.join(".") || "_root",
message: issue.message,
code: issue.code }))
)
);
}
const validatedData = validationResult.data;
// If this is set as default, unset other defaults of the same type
let newAddress: Address;
if (validatedData.isDefault) {
newAddress = await prisma.$transaction(async (tx) => {
// Unset other defaults of the same type
await tx.address.updateMany({
where: {
userId,
type: validatedData.type,
isDefault: true },
data: { isDefault: false } });
// Create new address
return await tx.address.create({
data: {
...validatedData,
userId } });
});
} else {
newAddress = await prisma.address.create({
data: {
...validatedData,
userId } });
}
return addSecurityHeaders(createdResponse(newAddress));
}
export const GET = withErrorHandling(withAuth(handleGet));
export const POST = withErrorHandling(withAuth(handlePost));
|