import debounce from "lodash/debounce"; import { GetServerSidePropsContext } from "next"; import { getCsrfToken } from "next-auth/client"; import Link from "next/link"; import React, { SyntheticEvent } from "react"; import { getSession } from "@lib/auth"; import { useLocale } from "@lib/hooks/useLocale"; import { HeadSeo } from "@components/seo/head-seo"; export default function ForgotPassword({ csrfToken }: { csrfToken: string }) { const { t, i18n } = useLocale(); const [loading, setLoading] = React.useState(false); const [error, setError] = React.useState<{ message: string } | null>(null); const [success, setSuccess] = React.useState(false); const [email, setEmail] = React.useState(""); const handleChange = (e: SyntheticEvent) => { const target = e.target as typeof e.target & { value: string }; setEmail(target.value); }; const submitForgotPasswordRequest = async ({ email }: { email: string }) => { try { const res = await fetch("/api/auth/forgot-password", { method: "POST", body: JSON.stringify({ email: email, language: i18n.language }), headers: { "Content-Type": "application/json", }, }); const json = await res.json(); if (!res.ok) { setError(json); } else { setSuccess(true); } return json; } catch (reason) { setError({ message: t("unexpected_error_try_again") }); } finally { setLoading(false); } }; const debouncedHandleSubmitPasswordRequest = debounce(submitForgotPasswordRequest, 250); const handleSubmit = async (e: SyntheticEvent) => { e.preventDefault(); if (!email) { return; } if (loading) { return; } setLoading(true); setError(null); setSuccess(false); await debouncedHandleSubmitPasswordRequest({ email }); }; const Success = () => { return (

{t("done")}

{t("check_email_reset_password")}

{error &&

{error.message}

}
); }; return (
{success && } {!success && ( <>

{t("forgot_password")}

{t("reset_instructions")}

{error &&

{error.message}

}
)}
); } ForgotPassword.getInitialProps = async (context: GetServerSidePropsContext) => { const { req, res } = context; const session = await getSession({ req }); if (session) { res.writeHead(302, { Location: "/" }); res.end(); return; } return { csrfToken: await getCsrfToken(context), }; };