feat: Add email verification and password reset

This commit is contained in:
Dries Augustyns
2025-12-20 20:06:25 +01:00
parent 7e25c148cc
commit 1a5607f278
31 changed files with 1026 additions and 122 deletions
+18
View File
@@ -57,6 +57,15 @@ export class network {
const res = (await response.json()) as ApiResponse;
if (response.status >= 400) {
// Check if this is an email verification required error
if (res.error?.code === 'EMAIL_VERIFICATION_REQUIRED') {
// Redirect to verification page
if (typeof window !== 'undefined' && !window.location.href.includes('/auth/verify-email')) {
window.location.href = '/auth/verify-email';
}
throw new Error(res.error.message ?? 'Please verify your email address to continue');
}
// Extract error message from standardized error response or fall back to direct message property
const errorMessage = res.error?.message ?? res.message ?? 'Something went wrong!';
throw new Error(errorMessage);
@@ -91,6 +100,15 @@ export class network {
const res = (await response.json()) as ApiResponse;
if (response.status >= 400) {
// Check if this is an email verification required error
if (res.error?.code === 'EMAIL_VERIFICATION_REQUIRED') {
// Redirect to verification page
if (typeof window !== 'undefined') {
window.location.href = '/auth/verify-email';
}
throw new Error(res.error.message ?? 'Please verify your email address to continue');
}
// Extract error message from standardized error response or fall back to direct message property
const errorMessage = res.error?.message ?? res.message ?? 'Something went wrong!';
throw new Error(errorMessage);
+5 -5
View File
@@ -19,7 +19,7 @@ dayjs.extend(relativeTime);
dayjs.extend(advancedFormat);
// Routes that don't require authentication
const PUBLIC_ROUTES = ['/auth/login', '/auth/signup', '/auth/reset', '/unsubscribe', '/subscribe', '/manage'];
const PUBLIC_ROUTES = ['/auth/login', '/auth/signup', '/auth/reset-password', '/auth/verify-email', '/unsubscribe', '/subscribe', '/manage'];
// Routes that don't require a project
const NO_PROJECT_ROUTES = ['/projects/create'];
@@ -35,8 +35,8 @@ function App({Component, pageProps}: AppProps) {
function AuthGuard({children}: {children: React.ReactNode}) {
const {data: user, isLoading} = useUser();
const router = useRouter();
const isPublicRoute = PUBLIC_ROUTES.some(route =>
router.pathname === route || router.pathname.startsWith(`${route}/`)
const isPublicRoute = PUBLIC_ROUTES.some(
route => router.pathname === route || router.pathname.startsWith(`${route}/`),
);
useEffect(() => {
@@ -111,8 +111,8 @@ export default function WithProviders(props: AppProps) {
function Root(props: AppProps) {
const router = useRouter();
const isPublicRoute = PUBLIC_ROUTES.some(route =>
router.pathname === route || router.pathname.startsWith(`${route}/`)
const isPublicRoute = PUBLIC_ROUTES.some(
route => router.pathname === route || router.pathname.startsWith(`${route}/`),
);
return (
+2 -2
View File
@@ -86,9 +86,9 @@ export default function Login() {
setResetStatus('loading');
setResetError(null);
try {
const response = await network.fetch<{success: boolean}, typeof AuthenticationSchemas.resetPassword>(
const response = await network.fetch<{success: boolean}, typeof AuthenticationSchemas.requestPasswordReset>(
'POST',
'/users/reset-password',
'/auth/request-password-reset',
{
email: resetEmail,
},
+213
View File
@@ -0,0 +1,213 @@
import {zodResolver} from '@hookform/resolvers/zod';
import {AuthenticationSchemas} from '@plunk/shared';
import {Button, Card, CardContent, Form, FormControl, FormField, FormItem, FormLabel, FormMessage, Input} from '@plunk/ui';
import {AnimatePresence, motion} from 'framer-motion';
import {NextSeo} from 'next-seo';
import Link from 'next/link';
import {useRouter} from 'next/router';
import React, {useEffect, useState} from 'react';
import {useForm} from 'react-hook-form';
import type {z} from 'zod';
import {network} from '../../lib/network';
export default function ResetPassword() {
const router = useRouter();
const {token} = router.query;
const [status, setStatus] = useState<'idle' | 'success' | 'error'>('idle');
const [errorMessage, setErrorMessage] = useState<string>('');
const form = useForm<z.infer<typeof AuthenticationSchemas.resetPassword>>({
resolver: zodResolver(AuthenticationSchemas.resetPassword),
defaultValues: {
token: '',
newPassword: '',
},
});
// Update form token when router is ready
useEffect(() => {
if (token && typeof token === 'string') {
form.setValue('token', token);
}
}, [token, form]);
async function onSubmit(values: z.infer<typeof AuthenticationSchemas.resetPassword>) {
try {
const response = await network.fetch<{success: boolean}, typeof AuthenticationSchemas.resetPassword>(
'POST',
'/auth/reset-password',
values,
);
if (response.success) {
setStatus('success');
setTimeout(() => {
void router.push('/auth/login');
}, 2000);
} else {
setStatus('error');
setErrorMessage('Failed to reset password. The link may be invalid or expired.');
}
} catch (error) {
setStatus('error');
setErrorMessage(error instanceof Error ? error.message : 'Something went wrong');
}
}
if (!token) {
return (
<>
<NextSeo title="Reset Password" />
<div className="min-h-screen flex items-center justify-center bg-neutral-50 py-12">
<div className="flex flex-col gap-6 max-w-md w-full px-4">
<Card>
<CardContent className="p-8">
<div className="flex flex-col items-center gap-4 text-center">
<div className="h-16 w-16 rounded-full bg-red-100 flex items-center justify-center">
<svg className="h-8 w-8 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</div>
<h1 className="text-2xl font-bold tracking-tight text-red-600">Invalid reset link</h1>
<p className="text-neutral-600">
This password reset link is invalid. Please request a new one from the login page.
</p>
<Link href="/auth/login">
<Button className="w-full mt-4">Back to login</Button>
</Link>
</div>
</CardContent>
</Card>
</div>
</div>
</>
);
}
return (
<>
<NextSeo title="Reset Password" />
<div className="min-h-screen flex items-center justify-center bg-neutral-50 py-12">
<div className="flex flex-col gap-6 max-w-md w-full px-4">
<Card>
<CardContent className="p-0">
<AnimatePresence mode="wait">
{status === 'success' ? (
<motion.div
key="success"
initial={{opacity: 0, scale: 0.95}}
animate={{opacity: 1, scale: 1}}
exit={{opacity: 0}}
className="p-8"
>
<div className="flex flex-col items-center gap-4 text-center">
<div className="h-16 w-16 rounded-full bg-green-100 flex items-center justify-center">
<svg className="h-8 w-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
</div>
<h1 className="text-2xl font-bold tracking-tight text-green-600">Password reset!</h1>
<p className="text-neutral-600">
Your password has been successfully reset. Redirecting to login...
</p>
</div>
</motion.div>
) : (
<motion.div
key="form"
initial={{opacity: 1}}
exit={{opacity: 0}}
className="p-8"
>
<Form {...form}>
<form
onSubmit={e => {
e.preventDefault();
void form.handleSubmit(onSubmit)(e);
}}
>
<div className="flex flex-col gap-6">
<div className="flex flex-col gap-2">
<h1 className="text-3xl font-bold tracking-tight">Reset your password</h1>
<p className="text-neutral-600">Enter your new password below</p>
</div>
<div className="grid gap-2">
<FormField
control={form.control}
name="newPassword"
render={({field}) => (
<FormItem>
<FormLabel>New Password</FormLabel>
<FormControl>
<Input placeholder="Enter new password" type="password" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</div>
<AnimatePresence>
{status === 'error' && (
<motion.p
initial={{opacity: 0, y: -10}}
animate={{opacity: 1, y: 0}}
exit={{opacity: 0, y: -10}}
className="text-sm font-medium text-red-500"
>
{errorMessage}
</motion.p>
)}
</AnimatePresence>
<Button type="submit" className="w-full" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? (
<>
<svg
className="h-4 w-4 animate-spin"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
className="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
strokeWidth="4"
/>
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
/>
</svg>
</>
) : (
'Reset password'
)}
</Button>
<div className="text-center text-sm text-neutral-500">
Remember your password?{' '}
<Link href="/auth/login" className="underline underline-offset-4 hover:text-neutral-900">
Back to login
</Link>
</div>
</div>
</form>
</Form>
</motion.div>
)}
</AnimatePresence>
</CardContent>
</Card>
</div>
</div>
</>
);
}
+236
View File
@@ -0,0 +1,236 @@
import {AuthenticationSchemas} from '@plunk/shared';
import {Button, Card, CardContent} from '@plunk/ui';
import {AnimatePresence, motion} from 'framer-motion';
import {NextSeo} from 'next-seo';
import Link from 'next/link';
import {useRouter} from 'next/router';
import React, {useEffect, useRef, useState} from 'react';
import {network} from '../../lib/network';
export default function VerifyEmail() {
const router = useRouter();
const {token} = router.query;
const [status, setStatus] = useState<'verifying' | 'success' | 'error' | 'pending'>('pending');
const [errorMessage, setErrorMessage] = useState<string>('');
const [isResending, setIsResending] = useState(false);
const [resendMessage, setResendMessage] = useState<string>('');
const processedToken = useRef<string | undefined>(undefined);
useEffect(() => {
// Wait for router to be ready before processing
if (!router.isReady) {
return;
}
const normalizedToken = typeof token === 'string' ? token : undefined;
if (processedToken.current === normalizedToken) {
return;
}
processedToken.current = normalizedToken;
// If no token, show the pending verification state
if (!token || typeof token !== 'string') {
setStatus('pending');
return;
}
setStatus('verifying');
async function verifyEmail() {
try {
const response = await network.fetch<{success: boolean}, typeof AuthenticationSchemas.verifyEmail>(
'POST',
'/auth/verify-email',
{token: token as string},
);
if (response.success) {
setStatus('success');
setTimeout(() => {
void router.push('/');
}, 2000);
} else {
setStatus('error');
setErrorMessage('Invalid or expired verification link');
}
} catch (error) {
setStatus('error');
setErrorMessage(error instanceof Error ? error.message : 'Something went wrong');
}
}
void verifyEmail();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [router.isReady, token]);
async function handleResend() {
setIsResending(true);
setResendMessage('');
try {
const response = await network.fetch<{success: boolean}>('POST', '/auth/request-verification');
if (response.success) {
setResendMessage('Verification email sent! Please check your inbox.');
} else {
setResendMessage('Failed to send verification email. Please try again.');
}
} catch {
setResendMessage('Failed to send verification email. Please try again.');
} finally {
setIsResending(false);
}
}
return (
<>
<NextSeo title="Verify Email" />
<div className="min-h-screen flex items-center justify-center bg-neutral-50 py-12">
<div className="flex flex-col gap-6 max-w-md w-full px-4">
<Card>
<CardContent className="p-8">
<div className="flex flex-col gap-6 text-center">
<AnimatePresence mode="wait">
{status === 'pending' && (
<motion.div
key="pending"
initial={{opacity: 0, scale: 0.95}}
animate={{opacity: 1, scale: 1}}
exit={{opacity: 0}}
className="flex flex-col items-center gap-4"
>
<div className="h-16 w-16 rounded-full bg-blue-100 flex items-center justify-center">
<svg className="h-8 w-8 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"
/>
</svg>
</div>
<h1 className="text-2xl font-bold tracking-tight">Verify your email</h1>
<p className="text-neutral-600">
Please check your inbox for a verification link. Click the link in the email to verify your
account.
</p>
<div className="flex flex-col gap-3 w-full mt-4">
<Button onClick={handleResend} disabled={isResending} className="w-full">
{isResending ? 'Sending...' : 'Resend verification email'}
</Button>
{resendMessage && (
<p
className={`text-sm ${resendMessage.includes('sent') ? 'text-green-600' : 'text-red-500'}`}
>
{resendMessage}
</p>
)}
<Link href="/auth/login">
<Button variant="outline" className="w-full">
Back to login
</Button>
</Link>
</div>
</motion.div>
)}
{status === 'verifying' && (
<motion.div
key="verifying"
initial={{opacity: 0}}
animate={{opacity: 1}}
exit={{opacity: 0}}
className="flex flex-col items-center gap-4"
>
<div className="h-16 w-16 rounded-full bg-neutral-100 flex items-center justify-center">
<svg
className="h-8 w-8 animate-spin text-neutral-600"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path
className="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
/>
</svg>
</div>
<h1 className="text-2xl font-bold tracking-tight">Verifying your email...</h1>
<p className="text-neutral-600">Please wait while we verify your email address.</p>
</motion.div>
)}
{status === 'success' && (
<motion.div
key="success"
initial={{opacity: 0, scale: 0.95}}
animate={{opacity: 1, scale: 1}}
exit={{opacity: 0}}
className="flex flex-col items-center gap-4"
>
<div className="h-16 w-16 rounded-full bg-green-100 flex items-center justify-center">
<svg className="h-8 w-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
</div>
<h1 className="text-2xl font-bold tracking-tight text-green-600">Email verified!</h1>
<p className="text-neutral-600">
Your email has been successfully verified. Redirecting to dashboard...
</p>
</motion.div>
)}
{status === 'error' && (
<motion.div
key="error"
initial={{opacity: 0, scale: 0.95}}
animate={{opacity: 1, scale: 1}}
exit={{opacity: 0}}
className="flex flex-col items-center gap-4"
>
<div className="h-16 w-16 rounded-full bg-red-100 flex items-center justify-center">
<svg className="h-8 w-8 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</div>
<h1 className="text-2xl font-bold tracking-tight text-red-600">Verification failed</h1>
<p className="text-neutral-600">{errorMessage}</p>
<div className="flex flex-col gap-3 w-full mt-4">
<Button onClick={handleResend} disabled={isResending} className="w-full">
{isResending ? 'Sending...' : 'Resend verification email'}
</Button>
{resendMessage && (
<p
className={`text-sm ${resendMessage.includes('sent') ? 'text-green-600' : 'text-red-500'}`}
>
{resendMessage}
</p>
)}
<Link href="/auth/login">
<Button variant="outline" className="w-full">
Back to login
</Button>
</Link>
</div>
</motion.div>
)}
</AnimatePresence>
</div>
</CardContent>
</Card>
</div>
</div>
</>
);
}
+53 -1
View File
@@ -7,11 +7,12 @@ import {
CardContent,
CardDescription,
CardHeader,
CardTitle
CardTitle,
} from '@plunk/ui';
import {AlertCircle, Mail, Send, TrendingUp, Users} from 'lucide-react';
import {NextSeo} from 'next-seo';
import Link from 'next/link';
import {useState} from 'react';
import {ApiKeyDisplay} from '../components/ApiKeyDisplay';
import {DashboardLayout} from '../components/DashboardLayout';
import {QuickStart} from '../components/QuickStart';
@@ -21,6 +22,8 @@ import {useDashboardStats} from '../lib/hooks/useDashboardStats';
import {useProjectSetupState} from '../lib/hooks/useProjectSetupState';
import {useProjectSecurity} from '../lib/hooks/useProjectSecurity';
import {useConfig} from '../lib/hooks/useConfig';
import {useUser} from '../lib/hooks/useUser';
import {network} from '../lib/network';
export default function Index() {
const {activeProject} = useActiveProject();
@@ -28,6 +31,9 @@ export default function Index() {
const {setupState, isLoading: isLoadingSetupState} = useProjectSetupState(activeProject?.id);
const {securityMetrics} = useProjectSecurity(activeProject?.id);
const {data: config} = useConfig();
const {data: user} = useUser();
const [isResending, setIsResending] = useState(false);
const [resendMessage, setResendMessage] = useState<string>('');
const stats = [
{
@@ -52,6 +58,24 @@ export default function Index() {
},
];
async function handleResendVerification() {
setIsResending(true);
setResendMessage('');
try {
const response = await network.fetch<{success: boolean}>('POST', '/auth/request-verification');
if (response.success) {
setResendMessage('Verification email sent! Please check your inbox.');
} else {
setResendMessage('Failed to send verification email. Please try again.');
}
} catch {
setResendMessage('Failed to send verification email. Please try again.');
} finally {
setIsResending(false);
}
}
return (
<>
<NextSeo title="Dashboard" />
@@ -71,6 +95,34 @@ export default function Index() {
</Alert>
)}
{/* Email Verification Banner */}
{user && user.type === 'PASSWORD' && !user.emailVerified && (
<Alert variant="warning">
<AlertCircle className="h-4 w-4" />
<AlertTitle>Verify your email address</AlertTitle>
<AlertDescription className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
<span className="text-sm">
Please verify your email address to unlock all features. Check your inbox for the verification link.
</span>
<div className="flex flex-col gap-2">
<Button
size="sm"
className="w-full sm:w-auto"
onClick={handleResendVerification}
disabled={isResending}
>
{isResending ? 'Sending...' : 'Resend verification email'}
</Button>
{resendMessage && (
<p className={`text-xs ${resendMessage.includes('sent') ? 'text-green-600' : 'text-red-500'}`}>
{resendMessage}
</p>
)}
</div>
</AlertDescription>
</Alert>
)}
{/* Security Warning Banner */}
{activeProject && !activeProject.disabled && securityMetrics && (
<SecurityWarningBanner status={securityMetrics.status} />