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 { useNotificationContext } from "@app/components/context/Notifications/NotificationProvider"; import attemptChangePassword from "@app/components/utilities/attemptChangePassword"; import checkPassword from "@app/components/utilities/checks/checkPassword"; import { Button, FormControl, Input } from "@app/components/v2"; import { useUser } from "@app/context"; import { useGetCommonPasswords } from "@app/hooks/api"; type Errors = { length?: string, upperCase?: string, lowerCase?: string, number?: string, specialChar?: string, repeatedChar?: 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 { createNotification } = useNotificationContext(); const { user } = useUser(); const { data: commonPasswords } = useGetCommonPasswords(); 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 { if (!user?.email) return; if (!commonPasswords) return; const errorCheck = checkPassword({ password: newPassword, commonPasswords, setErrors }); if (errorCheck) return; setIsLoading(true); await attemptChangePassword({ email: user.email, 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; })}
)}
); }