|
| 1 | +'use client' |
| 2 | + |
| 3 | +import { useEffect, useState } from 'react' |
| 4 | +import { useRouter } from 'next/navigation' |
| 5 | +import { z } from 'zod' |
| 6 | +import { useForm } from 'react-hook-form' |
| 7 | +import { zodResolver } from '@hookform/resolvers/zod' |
| 8 | +import { Loader2 } from 'lucide-react' |
| 9 | + |
| 10 | +import { Button } from '@/components/ui/button' |
| 11 | +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' |
| 12 | +import { |
| 13 | + Form, |
| 14 | + FormControl, |
| 15 | + FormField, |
| 16 | + FormItem, |
| 17 | + FormLabel, |
| 18 | + FormMessage, |
| 19 | +} from '@/components/ui/form' |
| 20 | +import { Input } from '@/components/ui/input' |
| 21 | +import authClient from '@/lib/auth-client' |
| 22 | + |
| 23 | +// --- Configuration Constants --- |
| 24 | +const COOLDOWN_SECONDS = 60 |
| 25 | +const COOLDOWN_STORAGE_KEY = 'verification_cooldown_timestamp' |
| 26 | +const EMAIL_STORAGE_KEY = 'email_for_verification' |
| 27 | + |
| 28 | +// --- Zod Schema for the Form --- |
| 29 | +const formSchema = z.object({ |
| 30 | + otp: z.string().length(6, { message: 'Your code must be 6 digits.' }), |
| 31 | +}) |
| 32 | + |
| 33 | +export default function EmailVerificationPage() { |
| 34 | + const [loading, setLoading] = useState(false) // For the main OTP submission |
| 35 | + const [isSending, setIsSending] = useState(false) // For the "Resend" button |
| 36 | + const [cooldown, setCooldown] = useState(0) |
| 37 | + const [email, setEmail] = useState('') |
| 38 | + const router = useRouter() |
| 39 | + |
| 40 | + const form = useForm<z.infer<typeof formSchema>>({ |
| 41 | + resolver: zodResolver(formSchema), |
| 42 | + defaultValues: { otp: '' }, |
| 43 | + }) |
| 44 | + |
| 45 | + useEffect(() => { |
| 46 | + const storedEmail = sessionStorage.getItem(EMAIL_STORAGE_KEY) |
| 47 | + if (storedEmail) { |
| 48 | + setEmail(storedEmail) |
| 49 | + } else { |
| 50 | + router.push('/auth/login') |
| 51 | + } |
| 52 | + }, []) |
| 53 | + |
| 54 | + // --- Cooldown Logic --- |
| 55 | + useEffect(() => { |
| 56 | + // On initial page load, check if a cooldown is already active in localStorage |
| 57 | + const cooldownEndTime = parseInt(localStorage.getItem(COOLDOWN_STORAGE_KEY) || '0') |
| 58 | + if (cooldownEndTime > Date.now()) { |
| 59 | + const remainingSeconds = Math.ceil((cooldownEndTime - Date.now()) / 1000) |
| 60 | + setCooldown(remainingSeconds) |
| 61 | + } |
| 62 | + |
| 63 | + // Set up an interval to tick down the cooldown every second |
| 64 | + const timer = setInterval(() => { |
| 65 | + setCooldown((prev) => (prev > 0 ? prev - 1 : 0)) |
| 66 | + }, 1000) |
| 67 | + |
| 68 | + // Clean up the interval when the component unmounts |
| 69 | + return () => clearInterval(timer) |
| 70 | + }, []) |
| 71 | + |
| 72 | + // --- Handlers --- |
| 73 | + const handleResend = async () => { |
| 74 | + if (cooldown > 0 || isSending) return |
| 75 | + setIsSending(true) |
| 76 | + |
| 77 | + // The backend knows who the user is from their secure session cookie. |
| 78 | + // We do NOT need to send the email address from the client. |
| 79 | + const { error } = await authClient.emailOtp.sendVerificationOtp({ |
| 80 | + email: email, |
| 81 | + type: 'email-verification', |
| 82 | + }) |
| 83 | + |
| 84 | + if (!error) { |
| 85 | + // On success, set the cooldown timestamp in localStorage for persistence |
| 86 | + const cooldownEndTime = Date.now() + COOLDOWN_SECONDS * 1000 |
| 87 | + localStorage.setItem(COOLDOWN_STORAGE_KEY, cooldownEndTime.toString()) |
| 88 | + setCooldown(COOLDOWN_SECONDS) |
| 89 | + } |
| 90 | + setIsSending(false) |
| 91 | + } |
| 92 | + |
| 93 | + const onSubmit = async (values: z.infer<typeof formSchema>) => { |
| 94 | + setLoading(true) |
| 95 | + await authClient.emailOtp.verifyEmail( |
| 96 | + { email: email, otp: values.otp }, |
| 97 | + { |
| 98 | + onSuccess: async () => { |
| 99 | + localStorage.removeItem(COOLDOWN_STORAGE_KEY) |
| 100 | + sessionStorage.removeItem(EMAIL_STORAGE_KEY) |
| 101 | + |
| 102 | + router.push('/feeds') |
| 103 | + }, |
| 104 | + onError: (error) => { |
| 105 | + form.setError('otp', { type: 'server', message: error.error.message }) |
| 106 | + setLoading(false) |
| 107 | + }, |
| 108 | + } |
| 109 | + ) |
| 110 | + } |
| 111 | + |
| 112 | + return ( |
| 113 | + <div className="flex h-screen w-screen items-center justify-center bg-muted"> |
| 114 | + <Card className="w-full max-w-md"> |
| 115 | + <CardHeader className="text-center"> |
| 116 | + <CardTitle className="text-2xl">Check Your Email</CardTitle> |
| 117 | + <CardDescription> |
| 118 | + {email ? `We've sent a code to ${email}.` : 'Please wait...'} |
| 119 | + </CardDescription> |
| 120 | + </CardHeader> |
| 121 | + <CardContent> |
| 122 | + <Form {...form}> |
| 123 | + <form onSubmit={form.handleSubmit(onSubmit)} className="grid gap-4"> |
| 124 | + <FormField |
| 125 | + control={form.control} |
| 126 | + name="otp" |
| 127 | + render={({ field }) => ( |
| 128 | + <FormItem> |
| 129 | + <FormLabel className="sr-only">Verification Code</FormLabel> |
| 130 | + <FormControl> |
| 131 | + <Input |
| 132 | + placeholder="6-digit code" |
| 133 | + className="text-center text-lg tracking-widest" |
| 134 | + {...field} |
| 135 | + /> |
| 136 | + </FormControl> |
| 137 | + <FormMessage /> |
| 138 | + </FormItem> |
| 139 | + )} |
| 140 | + /> |
| 141 | + <Button type="submit" className="w-full" disabled={loading}> |
| 142 | + {loading ? <Loader2 className="animate-spin" /> : 'Verify Account'} |
| 143 | + </Button> |
| 144 | + </form> |
| 145 | + </Form> |
| 146 | + |
| 147 | + <div className="mt-4 text-center text-sm text-muted-foreground"> |
| 148 | + <span>Didn't receive the code?</span> |
| 149 | + <Button |
| 150 | + variant="link" |
| 151 | + className="px-1 font-semibold" |
| 152 | + disabled={cooldown > 0 || isSending} |
| 153 | + onClick={handleResend} |
| 154 | + > |
| 155 | + {isSending && <Loader2 className="mr-2 h-4 w-4 animate-spin" />} |
| 156 | + {cooldown > 0 ? `Resend in ${cooldown}s` : 'Click to resend'} |
| 157 | + </Button> |
| 158 | + </div> |
| 159 | + </CardContent> |
| 160 | + </Card> |
| 161 | + </div> |
| 162 | + ) |
| 163 | +} |
0 commit comments