import { useState } from "react"; import { Controller, useForm } from "react-hook-form"; import { useTranslation } from "react-i18next"; import { faXmark } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { yupResolver } from "@hookform/resolvers/yup"; import * as yup from "yup"; import { createNotification } from "@app/components/notifications"; import attemptChangePassword from "@app/components/utilities/attemptChangePassword"; import checkPassword from "@app/components/utilities/checks/password/checkPassword"; import { Button, FormControl, Input } from "@app/components/v2"; import { useUser } from "@app/context"; type Errors = { tooShort?: string; tooLong?: string; noLetterChar?: string; noNumOrSpecialChar?: string; repeatedChar?: string; escapeChar?: string; lowEntropy?: string; breached?: string; }; const schema = yup .object({ oldPassword: yup.string().required("Old password is required"), newPassword: yup.string().required("New password is required") }) .required(); export type FormData = yup.InferType; export const ChangePasswordSection = () => { const { t } = useTranslation(); const { user } = useUser(); const { reset, control, handleSubmit } = useForm({ defaultValues: { oldPassword: "", newPassword: "" }, resolver: yupResolver(schema) }); const [errors, setErrors] = useState({}); const [isLoading, setIsLoading] = useState(false); const onFormSubmit = async ({ oldPassword, newPassword }: FormData) => { try { const errorCheck = await checkPassword({ password: newPassword, setErrors }); if (errorCheck) return; setIsLoading(true); await attemptChangePassword({ email: user.username, currentPassword: oldPassword, newPassword }); setIsLoading(false); createNotification({ text: "Successfully changed password", type: "success" }); reset(); window.location.href = "/login"; } catch (err) { console.error(err); setIsLoading(false); createNotification({ text: "Failed to change password", type: "error" }); } }; return (

Change password

( )} control={control} name="oldPassword" />
( )} control={control} name="newPassword" />
{Object.keys(errors).length > 0 && (
{t("section.password.validate-base")}
{Object.keys(errors).map((key) => { if (errors[key as keyof Errors]) { return (

{errors[key as keyof Errors]}

); } return null; })}
)}
); };