mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 17:46:06 +00:00
feat(auth): implement email verification process with resend functionality and update registration flow
This commit is contained in:
@@ -6,6 +6,7 @@ import { checkRateLimit, getClientIp, rateLimitHeaders, RATE_LIMIT_CONFIGS } fro
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
import { isInviteCodeRequired } from '@/lib/feature-flags';
|
||||
import { logError } from '@/lib/logger';
|
||||
import { createVerificationToken, isEmailVerificationEnabled, sendVerificationEmail } from '@/lib/email-verification';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
@@ -89,12 +90,16 @@ export async function POST(request: NextRequest) {
|
||||
// Hash password
|
||||
const hashedPassword = await bcrypt.hash(password, 12);
|
||||
|
||||
// If SMTP is not configured, auto-verify the email so users aren't locked out
|
||||
const emailVerificationRequired = isEmailVerificationEnabled();
|
||||
|
||||
// Create user
|
||||
const user = await db.user.create({
|
||||
data: {
|
||||
name: name.trim(),
|
||||
email: normalizedEmail,
|
||||
password: hashedPassword,
|
||||
emailVerified: emailVerificationRequired ? null : new Date(),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
@@ -116,8 +121,18 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
}
|
||||
|
||||
// Send verification email if SMTP is configured
|
||||
if (emailVerificationRequired) {
|
||||
const verificationToken = await createVerificationToken(normalizedEmail);
|
||||
await sendVerificationEmail(normalizedEmail, verificationToken);
|
||||
}
|
||||
|
||||
const message = emailVerificationRequired
|
||||
? 'Account created. Please check your email to verify your address before signing in.'
|
||||
: 'Account created successfully';
|
||||
|
||||
const response = successResponse(
|
||||
{ message: 'Account created successfully', user },
|
||||
{ message, user, emailVerificationRequired },
|
||||
201
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
import { db } from '@/lib/db';
|
||||
import { checkRateLimit, getClientIp } from '@/lib/rate-limit';
|
||||
import { apiErrors, successResponse, withCacheControl } from '@/lib/api-response';
|
||||
import { createVerificationToken, isEmailVerificationEnabled, sendVerificationEmail } from '@/lib/email-verification';
|
||||
import { logError } from '@/lib/logger';
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
if (!isEmailVerificationEnabled()) {
|
||||
return apiErrors.badRequest('Email verification is not enabled');
|
||||
}
|
||||
|
||||
// Rate-limit by IP to prevent abuse
|
||||
const clientIp = getClientIp(request);
|
||||
const rateLimitResult = await checkRateLimit(`resend-verification:${clientIp}`, 'resend-verification');
|
||||
if (!rateLimitResult.allowed) {
|
||||
return apiErrors.rateLimited('Too many requests. Please try again later.');
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { email } = body;
|
||||
|
||||
if (!email || typeof email !== 'string' || email.length > 254 || !email.includes('@')) {
|
||||
return apiErrors.badRequest('Valid email is required');
|
||||
}
|
||||
|
||||
const normalizedEmail = email.toLowerCase().trim();
|
||||
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(normalizedEmail)) {
|
||||
return apiErrors.badRequest('Valid email is required');
|
||||
}
|
||||
|
||||
// Look up user — return a generic success regardless of whether the email
|
||||
// exists to avoid user enumeration
|
||||
const user = await db.user.findUnique({
|
||||
where: { email: normalizedEmail },
|
||||
select: { id: true, emailVerified: true },
|
||||
});
|
||||
|
||||
if (user && !user.emailVerified) {
|
||||
const token = await createVerificationToken(normalizedEmail);
|
||||
await sendVerificationEmail(normalizedEmail, token);
|
||||
}
|
||||
|
||||
return withCacheControl(
|
||||
successResponse({ message: 'If that email has an unverified account, a new verification link has been sent.' }),
|
||||
'private, no-store'
|
||||
);
|
||||
} catch (err) {
|
||||
logError('Resend verification error:', err);
|
||||
return apiErrors.internalError('Failed to resend verification email');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { consumeVerificationToken } from '@/lib/email-verification';
|
||||
import { rateLimit } from '@/lib/rate-limit';
|
||||
import { logError } from '@/lib/logger';
|
||||
|
||||
// A raw 32-byte hex token is exactly 64 characters.
|
||||
const TOKEN_REGEX = /^[0-9a-f]{64}$/;
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
// Rate-limit by IP to prevent token enumeration attacks.
|
||||
const limited = await rateLimit(request, 'verify-email');
|
||||
if (limited) return limited;
|
||||
|
||||
const token = request.nextUrl.searchParams.get('token');
|
||||
|
||||
if (!token || !TOKEN_REGEX.test(token.trim())) {
|
||||
return NextResponse.redirect(new URL('/login?error=InvalidVerificationToken', request.url));
|
||||
}
|
||||
|
||||
const email = await consumeVerificationToken(token.trim());
|
||||
|
||||
if (!email) {
|
||||
return NextResponse.redirect(new URL('/login?error=InvalidVerificationToken', request.url));
|
||||
}
|
||||
|
||||
return NextResponse.redirect(new URL('/login?verified=true', request.url));
|
||||
} catch (err) {
|
||||
logError('Email verification error:', err);
|
||||
return NextResponse.redirect(new URL('/login?error=VerificationFailed', request.url));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user