import { getCsrfToken } from "next-auth/client"; import prisma from "../../../lib/prisma"; import Head from "next/head"; import React from "react"; import debounce from "lodash.debounce"; import dayjs from "dayjs"; import { ResetPasswordRequest } from "@prisma/client"; import { useMemo } from "react"; import Link from "next/link"; import { GetServerSidePropsContext } from "next"; type Props = { id: string; resetPasswordRequest: ResetPasswordRequest; csrfToken: string; }; export default function Page({ resetPasswordRequest, csrfToken }: Props) { const [loading, setLoading] = React.useState(false); const [error, setError] = React.useState(null); const [success, setSuccess] = React.useState(false); const [password, setPassword] = React.useState(""); const handleChange = (e) => { setPassword(e.target.value); }; const submitChangePassword = async ({ password, requestId }) => { try { const res = await fetch("/api/auth/reset-password", { method: "POST", body: JSON.stringify({ requestId: requestId, password: password }), headers: { "Content-Type": "application/json", }, }); const json = await res.json(); if (!res.ok) { setError(json); } else { setSuccess(true); } return json; } catch (reason) { setError({ message: "An unexpected error occurred. Try again." }); } finally { setLoading(false); } }; const debouncedChangePassword = debounce(submitChangePassword, 250); const handleSubmit = async (e) => { e.preventDefault(); if (!password) { return; } if (loading) { return; } setLoading(true); setError(null); setSuccess(false); await debouncedChangePassword({ password, requestId: resetPasswordRequest.id }); }; const Success = () => { return ( <>

Success

Your password has been reset. You can now login with your newly created password.

); }; const Expired = () => { return ( <>

Whoops

That Request is Expired.

That request is expired. You can back and enter the email associated with your account and we will you another link to reset your password.

); }; const isRequestExpired = useMemo(() => { const now = dayjs(); return dayjs(resetPasswordRequest.expires).isBefore(now); }, [resetPasswordRequest]); return (
Reset Password
{isRequestExpired && } {!isRequestExpired && !success && ( <>

Reset Password

Enter the new password you'd like for your account.

{error &&

{error.message}

}
)} {!isRequestExpired && success && ( <> )}
); } export async function getServerSideProps(context: GetServerSidePropsContext) { const id = context.params.id; try { const resetPasswordRequest = await prisma.resetPasswordRequest.findUnique({ where: { id: id, }, select: { id: true, expires: true, }, }); return { props: { resetPasswordRequest: { ...resetPasswordRequest, expires: resetPasswordRequest.expires.toString(), }, id, csrfToken: await getCsrfToken({ req: context.req }), }, }; } catch (reason) { return { notFound: true, }; } }