import React, { useEffect } from 'react'; import { FabButton } from '../base/fab-button'; import { FabModal } from '../base/fab-modal'; import { FormInput } from '../form/form-input'; import { useForm, UseFormRegister } from 'react-hook-form'; import { useTranslation } from 'react-i18next'; import Authentication from '../../api/authentication'; import { FieldValues } from 'react-hook-form/dist/types/fields'; import { PasswordInput } from './password-input'; import { FormState } from 'react-hook-form/dist/types/form'; import MemberAPI from '../../api/member'; import { User } from '../../models/user'; interface ChangePasswordProp { register: UseFormRegister, onError: (message: string) => void, currentFormPassword: string, formState: FormState, user: User, } /** * This component shows a button that trigger a modal dialog to verify the user's current password. * If the user's current password is correct, the modal dialog is closed and the button is replaced by a form to set the new password. */ export const ChangePassword = ({ register, onError, currentFormPassword, formState, user }: ChangePasswordProp) => { const { t } = useTranslation('shared'); const [isModalOpen, setIsModalOpen] = React.useState(false); const [isConfirmedPassword, setIsConfirmedPassword] = React.useState(false); const [isPrivileged, setIsPrivileged] = React.useState(false); const { handleSubmit, register: passwordRegister } = useForm<{ password: string }>(); useEffect(() => { MemberAPI.current().then(operator => { setIsPrivileged((operator.role === 'admin' || operator.role === 'manager') && user.id !== operator.id); }).catch(error => onError(error)); }, []); /** * Opens/closes the dialog asking to confirm the current password before changing it. */ const toggleConfirmationModal = () => { setIsModalOpen(!isModalOpen); }; /** * Callback triggered when the user clicks on the "change my password" button */ const handleChangePasswordRequested = () => { if (isPrivileged) { setIsConfirmedPassword(true); } else { toggleConfirmationModal(); } }; /** * Callback triggered when the user confirms his current password. */ const onSubmit = (event: React.FormEvent) => { if (event) { event.stopPropagation(); event.preventDefault(); } return handleSubmit((data: { password: string }) => { Authentication.verifyPassword(data.password).then(res => { if (res) { setIsConfirmedPassword(true); toggleConfirmationModal(); } else { onError(t('app.shared.change_password.wrong_password')); } }).catch(err => { onError(err); }); })(event); }; return (
{!isConfirmedPassword && handleChangePasswordRequested()}> {t('app.shared.change_password.change_my_password')} } {isConfirmedPassword &&
}
{t('app.shared.change_password.confirm')}
); };