File size: 2,779 Bytes
eaab0a9 | 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 | import { NextRequest, NextResponse } from 'next/server';
import { withDb } from '@/lib/api-handler';
import { db } from '@/lib/db';
import { z } from 'zod';
import { getClientIp } from '@/lib/validation';
import { rateLimit } from '@/lib/rate-limit';
const forgotPasswordSchema = z.object({
email: z.string().email('Please enter a valid email address'),
});
async function handler(request: NextRequest) {
try {
// ── Rate Limit: 3 per 15 minutes ─────────────────────────────────
const ip = getClientIp(request);
const { allowed, retryAfterMs } = await rateLimit(`forgot-pw:${ip}`, 3, 15 * 60_000);
if (!allowed) {
return NextResponse.json(
{ error: 'Too many reset attempts. Please try again later.' },
{
status: 429,
headers: { 'Retry-After': String(Math.ceil(retryAfterMs / 1000)) },
}
);
}
// ── Parse & Validate Body ─────────────────────────────────────────
const body = await request.json();
const parsed = forgotPasswordSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json(
{ error: parsed.error.issues[0].message },
{ status: 400 }
);
}
const { email } = parsed.data;
// ── Check if user exists ──────────────────────────────────────────
const user = await db.user.findUnique({ where: { email } });
if (user) {
// Generate a random 6-digit code
const code = String(Math.floor(100000 + Math.random() * 900000));
const expiresAt = new Date(Date.now() + 15 * 60 * 1000); // 15 minutes
// Invalidate any existing tokens for this email
await db.resetToken.updateMany({
where: { email, usedAt: null },
data: { usedAt: new Date() },
});
// Create new reset token
await db.resetToken.create({
data: {
email,
token: code,
expiresAt,
},
});
return NextResponse.json({
message: 'If an account exists with this email, a reset code has been generated.',
code, // Demo: return code so user can use it
});
}
// Return same message regardless to prevent email enumeration
return NextResponse.json({
message: 'If an account exists with this email, a reset code has been generated.',
});
} catch (error) {
console.error('[FORGOT_PASSWORD_ERROR]', error);
return NextResponse.json(
{ error: 'Internal server error' },
{ status: 500 }
);
}
}
export const POST = withDb(handler); |