import React, { useEffect, useState } from 'react'; import { observer } from 'mobx-react-lite'; import { useStore } from 'App/mstore'; import { Form, Input, Loader, Icon, Message } from 'UI'; import { Button } from 'antd'; import { validatePassword } from 'App/validate'; import { PASSWORD_POLICY } from 'App/constants'; import { useTranslation } from 'react-i18next'; import withCaptcha, { WithCaptchaProps } from 'App/withRecaptcha'; const ERROR_DONT_MATCH = (t) => t("Passwords don't match."); interface Props { params: any; } function CreatePassword(props: Props & WithCaptchaProps) { const { t } = useTranslation(); const { params } = props; const { userStore } = useStore(); const { loading } = userStore; const { resetPassword } = userStore; const [error, setError] = useState(null); const [validationError, setValidationError] = useState(null); const [updated, setUpdated] = useState(false); const [passwordRepeat, setPasswordRepeat] = useState(''); const [password, setPassword] = useState(''); const pass = params.get('pass'); const invitation = params.get('invitation'); const { submitWithCaptcha, isVerifyingCaptcha, resetCaptcha } = props; const handleSubmit = (token?: string) => { if (!validatePassword(password)) { return; } resetPassword({ invitation, pass, password, 'g-recaptcha-response': token }) .then(() => { setUpdated(true); }) .catch((err) => { setError(err.message); // Reset captcha for the next attempt resetCaptcha(); }); }; const onSubmit = () => { // Validate before attempting captcha verification if (!validatePassword(password) || password !== passwordRepeat) { setValidationError( password !== passwordRepeat ? ERROR_DONT_MATCH(t) : PASSWORD_POLICY(t) ); return; } // Reset any previous errors setError(null); setValidationError(null); submitWithCaptcha({ pass, invitation, password }) .then((data) => { handleSubmit(data['g-recaptcha-response']); }) .catch((error) => { console.error('Captcha verification failed:', error); // The component will handle showing appropriate messages }); }; const write = (e: any) => { const { name, value } = e.target; if (name === 'password') setPassword(value); if (name === 'passwordRepeat') setPasswordRepeat(value); }; useEffect(() => { if (passwordRepeat.length > 0 && passwordRepeat !== password) { setValidationError(ERROR_DONT_MATCH(t)); } else if (passwordRepeat.length > 0 && !validatePassword(password)) { setValidationError(PASSWORD_POLICY(t)); } else { setValidationError(null); } }, [passwordRepeat, password, t]); return (
{!error && ( <>
{t('Your password has been updated successfully.')}
{validationError && {validationError}} {updated ? null : ( )} )} {error && (
{error}
)}
); } export default withCaptcha(observer(CreatePassword));