import React, { SyntheticEvent, useState } from "react"; import { ErrorCode } from "@lib/auth"; import Modal from "@components/Modal"; const errorMessages: { [key: string]: string } = { [ErrorCode.IncorrectPassword]: "Current password is incorrect", [ErrorCode.NewPasswordMatchesOld]: "New password matches your old password. Please choose a different password.", }; const ChangePasswordSection = () => { const [oldPassword, setOldPassword] = useState(""); const [newPassword, setNewPassword] = useState(""); const [successModalOpen, setSuccessModalOpen] = useState(false); const [errorMessage, setErrorMessage] = useState(null); const [isSubmitting, setIsSubmitting] = useState(false); const closeSuccessModal = () => { setSuccessModalOpen(false); }; async function changePasswordHandler(e: SyntheticEvent) { e.preventDefault(); if (isSubmitting) { return; } setIsSubmitting(true); setErrorMessage(null); try { const response = await fetch("/api/auth/changepw", { method: "PATCH", body: JSON.stringify({ oldPassword, newPassword }), headers: { "Content-Type": "application/json", }, }); if (response.status === 200) { setOldPassword(""); setNewPassword(""); setSuccessModalOpen(true); return; } const body = await response.json(); setErrorMessage(errorMessages[body.error] || "Something went wrong. Please try again"); } catch (err) { console.error("Error changing password", err); setErrorMessage("Something went wrong. Please try again"); } finally { setIsSubmitting(false); } } return ( <>

Change Password

setOldPassword(e.currentTarget.value)} name="current_password" id="current_password" required className="shadow-sm focus:ring-black focus:border-black block w-full sm:text-sm border-gray-300 rounded-sm" placeholder="Your old password" />
setNewPassword(e.currentTarget.value)} className="shadow-sm focus:ring-black focus:border-black block w-full sm:text-sm border-gray-300 rounded-sm" placeholder="Your super secure new password" />
{errorMessage &&

{errorMessage}

}

); }; export default ChangePasswordSection;