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:
@@ -28,6 +28,8 @@ const ERROR_MESSAGES: Record<string, string> = {
|
||||
OAuthAccountNotLinked: 'Sign-in failed. Please try a different method or contact support.',
|
||||
OAuthCallbackError: 'OAuth sign-in failed. Please try again.',
|
||||
OAuthEmailNotVerified: 'Your OAuth account email is not verified. Please verify it with your provider and try again.',
|
||||
InvalidVerificationToken: 'The verification link is invalid or has expired.',
|
||||
VerificationFailed: 'Email verification failed. Please try again.',
|
||||
Default: 'Something went wrong. Please try again.',
|
||||
};
|
||||
|
||||
@@ -45,12 +47,16 @@ function LoginFormInner({ googleEnabled, githubEnabled }: LoginFormInnerProps) {
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [showSuccess, setShowSuccess] = useState(false);
|
||||
const [showVerifiedSuccess, setShowVerifiedSuccess] = useState(false);
|
||||
const callbackUrl = getSafeCallbackUrl(searchParams.get('callbackUrl'));
|
||||
|
||||
useEffect(() => {
|
||||
if (searchParams.get('registered') === 'true') {
|
||||
setShowSuccess(true);
|
||||
}
|
||||
if (searchParams.get('verified') === 'true') {
|
||||
setShowVerifiedSuccess(true);
|
||||
}
|
||||
const errorCode = searchParams.get('error');
|
||||
if (errorCode) {
|
||||
setError(ERROR_MESSAGES[errorCode] ?? ERROR_MESSAGES.Default);
|
||||
@@ -103,7 +109,13 @@ function LoginFormInner({ googleEnabled, githubEnabled }: LoginFormInnerProps) {
|
||||
<CardContent>
|
||||
{showSuccess && (
|
||||
<div className="p-3 rounded-md bg-green-500/10 text-green-600 text-sm mb-4">
|
||||
Account created successfully! Please sign in.
|
||||
Account created successfully! Please check your email to verify your address before signing in.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{showVerifiedSuccess && (
|
||||
<div className="p-3 rounded-md bg-green-500/10 text-green-600 text-sm mb-4">
|
||||
Email verified successfully! You can now sign in.
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
||||
@@ -87,7 +87,11 @@ export default function RegisterPageClient({ requireInviteCode, googleEnabled, g
|
||||
return;
|
||||
}
|
||||
|
||||
router.push('/login?registered=true');
|
||||
if (data.data?.emailVerificationRequired) {
|
||||
router.push(`/verify-email?email=${encodeURIComponent(formData.email)}`);
|
||||
} else {
|
||||
router.push('/login?registered=true');
|
||||
}
|
||||
} catch {
|
||||
setError('Something went wrong. Please try again.');
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import Link from 'next/link';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { Suspense } from 'react';
|
||||
import { Video, Mail, Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Input } from '@/components/ui/input';
|
||||
|
||||
function VerifyEmailContent() {
|
||||
const searchParams = useSearchParams();
|
||||
const emailParam = searchParams.get('email') || '';
|
||||
const [resendEmail, setResendEmail] = useState(emailParam);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [sent, setSent] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const handleResend = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
setError('');
|
||||
try {
|
||||
const res = await fetch('/api/auth/verify-email/resend', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email: resendEmail }),
|
||||
});
|
||||
if (res.ok) {
|
||||
setSent(true);
|
||||
} else {
|
||||
setError('Something went wrong. Please try again.');
|
||||
}
|
||||
} catch {
|
||||
setError('Something went wrong. Please try again.');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center p-4 bg-background">
|
||||
<div className="w-full max-w-md">
|
||||
<Link href="/" className="flex items-center justify-center gap-2 mb-8">
|
||||
<Video className="h-8 w-8 text-primary" />
|
||||
<span className="font-bold text-2xl">OpenFrame</span>
|
||||
</Link>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="text-center">
|
||||
<CardTitle className="flex items-center justify-center gap-2">
|
||||
<Mail className="h-5 w-5" />
|
||||
Check your email
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
We sent a verification link to{' '}
|
||||
{emailParam ? <strong>{emailParam}</strong> : 'your email address'}.
|
||||
Click the link to activate your account.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<p className="text-sm text-muted-foreground text-center">
|
||||
The link expires in 2 hours. Check your spam folder if you don't see it.
|
||||
</p>
|
||||
|
||||
{sent ? (
|
||||
<div className="p-3 rounded-md bg-green-500/10 text-green-600 text-sm text-center">
|
||||
Verification email resent! Check your inbox.
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<span className="w-full border-t" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-card px-2 text-muted-foreground">Didn't receive it?</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-3 rounded-md bg-destructive/10 text-destructive text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleResend} className="flex gap-2">
|
||||
<Input
|
||||
type="email"
|
||||
placeholder="[email protected]"
|
||||
value={resendEmail}
|
||||
onChange={(e) => setResendEmail(e.target.value)}
|
||||
required
|
||||
disabled={loading}
|
||||
className="text-sm"
|
||||
/>
|
||||
<Button type="submit" variant="outline" disabled={loading || !resendEmail}>
|
||||
{loading && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
|
||||
Resend
|
||||
</Button>
|
||||
</form>
|
||||
</>
|
||||
)}
|
||||
|
||||
<p className="text-center text-sm text-muted-foreground">
|
||||
Already verified?{' '}
|
||||
<Link href="/login" className="text-primary hover:underline">
|
||||
Sign in
|
||||
</Link>
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function VerifyEmailPage() {
|
||||
return (
|
||||
<Suspense>
|
||||
<VerifyEmailContent />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -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