import { Box, Field, FieldError, FieldGroup, FieldHint, FieldLabel, FieldRow, PasswordInput } from '@rocket.chat/fuselage'; import { PasswordVerifier, useValidatePassword } from '@rocket.chat/ui-client'; import { useEndpoint, useToastMessageDispatch } from '@rocket.chat/ui-contexts'; import type { AllHTMLAttributes } from 'react'; import { useId } from 'react'; import { Controller, useFormContext } from 'react-hook-form'; import { useTranslation } from 'react-i18next'; import { useAllowPasswordChange } from './useAllowPasswordChange'; type PasswordFieldValues = { password: string; confirmationPassword: string }; function getAriaDescribedbyForPassword( passwordVerifierId: string, passwordId: string, allowPasswordChange: boolean, passwordError: boolean, ) { const error = !allowPasswordChange || passwordError; return [passwordVerifierId, !allowPasswordChange && `${passwordId}-hint`, error && `${passwordId}-error`].filter(Boolean).join(' '); } const ChangePassword = (props: AllHTMLAttributes) => { const { t } = useTranslation(); const dispatchToastMessage = useToastMessageDispatch(); const passwordId = useId(); const confirmPasswordId = useId(); const passwordVerifierId = useId(); const { watch, formState: { errors }, handleSubmit, reset, control, } = useFormContext(); const password = watch('password'); const passwordIsValid = useValidatePassword(password); const { allowPasswordChange } = useAllowPasswordChange(); const updatePassword = useEndpoint('POST', '/v1/users.updateOwnBasicInfo'); const handleSave = async ({ password }: { password?: string }) => { try { await updatePassword({ data: { newPassword: password, }, }); dispatchToastMessage({ type: 'success', message: t('Password_changed_successfully') }); reset(); } catch (error) { dispatchToastMessage({ type: 'error', message: error }); } }; return ( {t('New_password')} (password?.length && !passwordIsValid ? t('Password_must_meet_the_complexity_requirements') : true), }} render={({ field }) => ( )} /> {!allowPasswordChange && {t('Password_Change_Disabled')}} {errors?.password && ( {errors.password.message} )} {allowPasswordChange && } {t('Confirm_password')} (password !== confirmationPassword ? t('Passwords_do_not_match') : true), }} render={({ field }) => ( )} /> {errors.confirmationPassword && ( {errors.confirmationPassword.message} )} ); }; export default ChangePassword;