| 1 | "use client"; |
| 2 | |
| 3 | import { useAuth, useSendVerificationEmail } from "@better-auth-ui/react"; |
| 4 | import { useEffect, useState |
| 5 | import { toast } |
| 6 | |
| 7 | import { Button } |
| 8 | import { Card, CardContent |
| 9 | import { FieldDescription } |
| 10 | import { Spinner } |
| 11 | import { cn } |
| 12 | import { OpenEmailButton } |
| 13 | import { useIsHydrated } |
| 14 | |
| 15 | export type VerifyEmailProps |
| 16 | className?: string |
| 17 | }; |
| 18 | |
| 19 | /** Seconds the resend button stays disabled to prevent spamming the endpoint. */ |
| 20 | const RESEND_COOLDOWN_SECONDS = 60 |
| 21 | |
| 22 | /** Render a card prompting the user to verify their email, with a resend button that is rate-limited by a cooldown timer. */ |
| 23 | export function VerifyEmail({ |
| 24 | const { |
| 25 | authClient, |
| 26 | basePaths, |
| 27 | baseURL, |
| 28 | localization, |
| 29 | redirectTo, |
| 30 | viewPaths, |
| 31 | Link, |
| 32 | } = useAuth(); |
| 33 | |
| 34 | const isHydrated = |
| 35 | const email = |
| 36 | (isHydrated && sessionStorage |
| 37 | const [cooldown, |
| 38 | |
| 39 | useEffect(() => |
| 40 | if (cooldown <= |
| 41 | |
| 42 | const interval = |
| 43 | setCooldown((current) |
| 44 | }, 1000); |
| 45 | |
| 46 | return () => |
| 47 | }, [cooldown, |
| 48 | |
| 49 | const { mutate: |
| 50 | authClient, |
| 51 | { |
| 52 | onSuccess: () => |
| 53 | toast.success(localization |
| 54 | setCooldown(RESEND_COOLDOWN_SECONDS); |
| 55 | }, |
| 56 | }, |
| 57 | ); |
| 58 | |
| 59 | const isCoolingDown = |
| 60 | |
| 61 | return ( |
| 62 | <Card className={ |
| 63 | <CardHeader> |
| 64 | <CardTitle className=" |
| 65 | {localization.auth.verifyEmail |
| 66 | </CardTitle> |
| 67 | </CardHeader> |
| 68 | |
| 69 | <CardContent> |
| 70 | <div className="flex flex-col gap-4 |
| 71 | <FieldDescription> |
| 72 | {localization.auth.checkYourEmail |
| 73 | </FieldDescription> |
| 74 | |
| 75 | {email && ( |
| 76 | <div className="flex flex-col gap-3 |
| 77 | <OpenEmailButton email={ |
| 78 | |
| 79 | <Button |
| 80 | type="button" |
| 81 | variant="outline" |
| 82 | disabled={!email |
| 83 | onClick={() => |
| 84 | sendVerificationEmail({ |
| 85 | email, |
| 86 | callbackURL: `${baseURL}${ |
| 87 | }) |
| 88 | } |
| 89 | > |
| 90 | {isPending && <Spinner |
| 91 | |
| 92 | {isCoolingDown |
| 93 | ? localization.auth. |
| 94 | "{{seconds}}", |
| 95 | String(cooldown), |
| 96 | ) |
| 97 | : localization.auth. |
| 98 | </Button> |
| 99 | </div> |
| 100 | )} |
| 101 | </div> |
| 102 | |
| 103 | <div className="flex flex-col gap-3 items-center w-full mt-4 |
| 104 | <FieldDescription className=" |
| 105 | {localization.auth.alreadyVerifiedYourEmail |
| 106 | <Link |
| 107 | href={`${basePaths |
| 108 | className="underline underline-offset-4" |
| 109 | > |
| 110 | {localization.auth.signIn |
| 111 | </Link> |
| 112 | </FieldDescription> |
| 113 | </div> |
| 114 | </CardContent> |
| 115 | </Card> |
| 116 | ); |
| 117 | } |