mirror of
https://github.com/yusufipk/OpenFrame.git
synced 2026-09-11 09:36:08 +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));
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import { db } from '@/lib/db';
|
||||
import { ProjectMemberRole, WorkspaceMemberRole } from '@prisma/client';
|
||||
import { hasBillingAccess } from '@/lib/billing';
|
||||
import { isInviteCodeRequired } from '@/lib/feature-flags';
|
||||
import { isEmailVerificationEnabled } from '@/lib/email-verification';
|
||||
|
||||
// Dummy hash for timing-safe comparison when user doesn't exist
|
||||
// This prevents user enumeration via timing attacks
|
||||
@@ -47,6 +48,11 @@ export const { handlers, signIn, signOut, auth } = NextAuth({
|
||||
return null;
|
||||
}
|
||||
|
||||
// Block sign-in when email verification is required but not yet completed
|
||||
if (isEmailVerificationEnabled() && !user.emailVerified) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import { createHash, randomBytes } from 'crypto';
|
||||
import { db } from '@/lib/db';
|
||||
import nodemailer from 'nodemailer';
|
||||
import {
|
||||
brandedEmailTemplate,
|
||||
emailButton,
|
||||
emailHeading,
|
||||
emailRow,
|
||||
escapeHtml,
|
||||
EMAIL_COLORS,
|
||||
} from '@/lib/email-brand';
|
||||
import { logError } from '@/lib/logger';
|
||||
|
||||
// Reduce window to 2 hours — shorter exposure in access logs and backups.
|
||||
const TOKEN_EXPIRY_HOURS = 2;
|
||||
|
||||
/** Hash a raw token before persisting so the DB stores only the digest. */
|
||||
function hashToken(token: string): string {
|
||||
return createHash('sha256').update(token).digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true when SMTP is fully configured and email sending should be enforced.
|
||||
* When SMTP is not configured, email verification is bypassed so self-hosted deployments
|
||||
* without a mail server continue to function.
|
||||
*/
|
||||
export function isEmailVerificationEnabled(): boolean {
|
||||
return !!(process.env.SMTP_HOST && process.env.SMTP_USER && process.env.SMTP_PASSWORD);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a secure random verification token, persist only its SHA-256 digest,
|
||||
* and return the raw token (sent to the user via email).
|
||||
* Any existing tokens for this email are deleted first (at most one live token).
|
||||
*/
|
||||
export async function createVerificationToken(email: string): Promise<string> {
|
||||
const token = randomBytes(32).toString('hex');
|
||||
const tokenHash = hashToken(token);
|
||||
const expires = new Date(Date.now() + TOKEN_EXPIRY_HOURS * 60 * 60 * 1000);
|
||||
|
||||
// Delete existing tokens for this identifier before creating a new one
|
||||
await db.verificationToken.deleteMany({ where: { identifier: email } });
|
||||
|
||||
await db.verificationToken.create({
|
||||
data: { identifier: email, token: tokenHash, expires },
|
||||
});
|
||||
|
||||
// Return the raw (unhashed) token — only ever sent to the user, never stored.
|
||||
return token;
|
||||
}
|
||||
|
||||
/**
|
||||
* Consume a verification token: hash the raw token, look it up, mark the user
|
||||
* email as verified, and delete the DB record atomically.
|
||||
* Returns the user's email on success, or null on any failure (invalid, expired,
|
||||
* already verified, or deleted account).
|
||||
*/
|
||||
export async function consumeVerificationToken(token: string): Promise<string | null> {
|
||||
const tokenHash = hashToken(token);
|
||||
const record = await db.verificationToken.findUnique({ where: { token: tokenHash } });
|
||||
|
||||
if (!record) return null;
|
||||
if (record.expires < new Date()) {
|
||||
await db.verificationToken.delete({ where: { token: tokenHash } }).catch(() => null);
|
||||
return null;
|
||||
}
|
||||
|
||||
// Atomically mark email as verified and delete the token
|
||||
const [user] = await db.$transaction([
|
||||
db.user.updateMany({
|
||||
where: { email: record.identifier, emailVerified: null },
|
||||
data: { emailVerified: new Date() },
|
||||
}),
|
||||
db.verificationToken.delete({ where: { token: tokenHash } }),
|
||||
]);
|
||||
|
||||
// count === 0 means the user was already verified or has been deleted.
|
||||
// Return null so a replayed/stale token never produces a misleading success redirect.
|
||||
if (user.count === 0) return null;
|
||||
|
||||
return record.identifier;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Email sending
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function createTransport() {
|
||||
const host = process.env.SMTP_HOST;
|
||||
const port = Number(process.env.SMTP_PORT || '587');
|
||||
const user = process.env.SMTP_USER;
|
||||
const pass = process.env.SMTP_PASSWORD;
|
||||
if (!host || !user || !pass) return null;
|
||||
return nodemailer.createTransport({ host, port, secure: port === 465, auth: { user, pass } });
|
||||
}
|
||||
|
||||
export async function sendVerificationEmail(email: string, token: string): Promise<void> {
|
||||
const transporter = createTransport();
|
||||
if (!transporter) return;
|
||||
|
||||
const baseUrl = process.env.NEXTAUTH_URL;
|
||||
if (!baseUrl) {
|
||||
// A missing NEXTAUTH_URL means the verification link will be malformed and the
|
||||
// user will be permanently locked out with no visible failure. Treat as fatal.
|
||||
logError(
|
||||
'NEXTAUTH_URL is not set — cannot build a valid verification link.',
|
||||
new Error(
|
||||
'Set NEXTAUTH_URL to your deployment origin (e.g. https://app.example.com).'
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const verifyUrl = `${baseUrl}/api/auth/verify-email?token=${encodeURIComponent(token)}`;
|
||||
const from = process.env.SMTP_FROM || process.env.EMAIL_FROM || 'OpenFrame <[email protected]>';
|
||||
|
||||
const html = brandedEmailTemplate(
|
||||
`
|
||||
<tr>${emailHeading('✉', 'Verify your email address')}</tr>
|
||||
<tr><td style="padding:20px;">
|
||||
<table cellpadding="0" cellspacing="0" style="width:100%;margin-bottom:20px;">
|
||||
${emailRow('Account', escapeHtml(email), true)}
|
||||
${emailRow('Expires in', `${TOKEN_EXPIRY_HOURS} hours`)}
|
||||
</table>
|
||||
<p style="margin:0 0 20px;font-size:14px;color:${EMAIL_COLORS.textSecondary};line-height:1.6;">
|
||||
Click the button below to verify your email address and activate your OpenFrame account.
|
||||
If you did not create an account, you can safely ignore this email.
|
||||
</p>
|
||||
${emailButton('Verify Email Address →', verifyUrl)}
|
||||
</td></tr>
|
||||
`,
|
||||
{
|
||||
footerText: `This link expires in ${TOKEN_EXPIRY_HOURS} hours.`,
|
||||
}
|
||||
);
|
||||
|
||||
try {
|
||||
await transporter.sendMail({
|
||||
from,
|
||||
to: email,
|
||||
subject: 'Verify your OpenFrame email address',
|
||||
html,
|
||||
});
|
||||
} catch (err) {
|
||||
logError('Failed to send verification email:', err);
|
||||
}
|
||||
}
|
||||
@@ -70,6 +70,10 @@ export const RATE_LIMIT_CONFIGS: Record<string, RateLimitConfig> = {
|
||||
'video-download': { windowMs: 60 * 1000, maxRequests: 8 }, // 8 per minute
|
||||
'video-download-prepare': { windowMs: 60 * 1000, maxRequests: 5 }, // 5 per minute
|
||||
|
||||
// Email verification
|
||||
'verify-email': { windowMs: 15 * 60 * 1000, maxRequests: 20 }, // 20 per 15 min (clicked link)
|
||||
'resend-verification': { windowMs: 60 * 60 * 1000, maxRequests: 5 }, // 5 per hour
|
||||
|
||||
// Onboarding — one-time action, very strict
|
||||
'onboarding-complete': { windowMs: 60 * 60 * 1000, maxRequests: 5 }, // 5 per hour
|
||||
|
||||
|
||||
Reference in New Issue
Block a user