| 1 | "use client"; |
| 2 | |
| 3 | import { getViewURL, validateEmailAddress |
| 4 | import { |
| 5 | useAuth, |
| 6 | useFetchOptions, |
| 7 | useRequestPasswordReset, |
| 8 | } from "@better-auth-ui/react"; |
| 9 | |
| 10 | import { Card, CardContent |
| 11 | import { FieldDescription, FieldGroup |
| 12 | import { Spinner } |
| 13 | import { useAuthForm } |
| 14 | import { RESET_LINK_SENT_STORAGE_KEY } |
| 15 | |
| 16 | export function ForgotPassword() |
| 17 | const { |
| 18 | authClient, |
| 19 | baseURL, |
| 20 | basePaths, |
| 21 | localization, |
| 22 | navigate, |
| 23 | viewPaths, |
| 24 | Link, |
| 25 | } = useAuth(); |
| 26 | |
| 27 | const { fetchOptions, |
| 28 | |
| 29 | const { mutate: |
| 30 | authClient, |
| 31 | { |
| 32 | onError: () => |
| 33 | resetFetchOptions(); |
| 34 | }, |
| 35 | onSuccess: (_data, |
| 36 | sessionStorage.setItem(RESET_LINK_SENT_STORAGE_KEY |
| 37 | navigate({ to: |
| 38 | }, |
| 39 | }, |
| 40 | ); |
| 41 | |
| 42 | const form = |
| 43 | defaultValues: { email: "" |
| 44 | onSubmit: ({ value |
| 45 | requestPasswordReset({ |
| 46 | email: value.email |
| 47 | redirectTo: getViewURL( |
| 48 | baseURL, |
| 49 | basePaths.auth, |
| 50 | viewPaths.auth.resetPassword |
| 51 | ), |
| 52 | fetchOptions, |
| 53 | }), |
| 54 | }); |
| 55 | |
| 56 | return ( |
| 57 | <Card className=" |
| 58 | <CardHeader> |
| 59 | <CardTitle className=" |
| 60 | {localization.auth.forgotPassword |
| 61 | </CardTitle> |
| 62 | </CardHeader> |
| 63 | |
| 64 | <CardContent> |
| 65 | <form.AppForm> |
| 66 | <form.AuthFormRoot> |
| 67 | <FieldGroup> |
| 68 | <form.AppField |
| 69 | name="email" |
| 70 | validators={{ |
| 71 | onChange: ({ value |
| 72 | validateEmailAddress(value, { |
| 73 | invalidMessage: localization.auth |
| 74 | requiredMessage: localization.auth |
| 75 | }), |
| 76 | }} |
| 77 | > |
| 78 | {(field) => |
| 79 | <field.AuthFormTextField |
| 80 | label={localization.auth |
| 81 | type="email" |
| 82 | autoComplete="email" |
| 83 | placeholder={localization.auth |
| 84 | required |
| 85 | disabled={isPending} |
| 86 | /> |
| 87 | )} |
| 88 | </form.AppField> |
| 89 | |
| 90 | <div className="flex flex-col gap-3 |
| 91 | <form.AuthFormSubmitButton disabled={ |
| 92 | {isPending && <Spinner |
| 93 | {localization.auth.sendResetLink |
| 94 | </form.AuthFormSubmitButton> |
| 95 | </div> |
| 96 | </FieldGroup> |
| 97 | </form.AuthFormRoot> |
| 98 | </form.AppForm> |
| 99 | |
| 100 | <div className="flex flex-col gap-3 items-center w-full mt-4 |
| 101 | <FieldDescription className=" |
| 102 | {localization.auth.rememberYourPassword |
| 103 | <Link |
| 104 | href={`${basePaths |
| 105 | className="underline underline-offset-4" |
| 106 | > |
| 107 | {localization.auth.signIn |
| 108 | </Link> |
| 109 | </FieldDescription> |
| 110 | </div> |
| 111 | </CardContent> |
| 112 | </Card> |
| 113 | ); |
| 114 | } |