umami/components/pages/settings/profile/PasswordEditForm.js

67 lines
2.1 KiB
JavaScript
Raw Normal View History

2023-01-21 02:12:53 +01:00
import { useRef } from 'react';
import { Form, FormRow, FormInput, FormButtons, PasswordField, Button } from 'react-basics';
import useApi from 'hooks/useApi';
2023-03-22 22:05:55 +01:00
import useMessages from 'hooks/useMessages';
2023-01-21 02:12:53 +01:00
2023-01-25 16:42:46 +01:00
export default function PasswordEditForm({ onSave, onClose }) {
2023-03-22 22:05:55 +01:00
const { formatMessage, labels, messages } = useMessages();
2023-01-21 02:12:53 +01:00
const { post, useMutation } = useApi();
2023-01-25 16:42:46 +01:00
const { mutate, error, isLoading } = useMutation(data => post('/me/password', data));
2023-01-21 02:12:53 +01:00
const ref = useRef(null);
const handleSubmit = async data => {
2023-01-25 16:42:46 +01:00
mutate(data, {
2023-01-21 02:12:53 +01:00
onSuccess: async () => {
onSave();
onClose();
2023-01-21 02:12:53 +01:00
},
});
};
const samePassword = value => {
if (value !== ref?.current?.getValues('newPassword')) {
2023-01-25 16:42:46 +01:00
return formatMessage(messages.noMatchPassword);
2023-01-21 02:12:53 +01:00
}
return true;
};
return (
<Form ref={ref} onSubmit={handleSubmit} error={error}>
2023-01-25 16:42:46 +01:00
<FormRow label={formatMessage(labels.currentPassword)}>
<FormInput name="currentPassword" rules={{ required: 'Required' }}>
<PasswordField autoComplete="current-password" />
</FormInput>
</FormRow>
<FormRow label={formatMessage(labels.newPassword)}>
2023-01-21 02:12:53 +01:00
<FormInput
name="newPassword"
rules={{
required: 'Required',
2023-01-25 16:42:46 +01:00
minLength: { value: 8, message: formatMessage(messages.minPasswordLength) },
2023-01-21 02:12:53 +01:00
}}
>
2023-01-25 16:42:46 +01:00
<PasswordField autoComplete="new-password" />
2023-01-21 02:12:53 +01:00
</FormInput>
</FormRow>
2023-01-25 16:42:46 +01:00
<FormRow label={formatMessage(labels.confirmPassword)}>
2023-01-21 02:12:53 +01:00
<FormInput
name="confirmPassword"
rules={{
2023-01-25 16:42:46 +01:00
required: formatMessage(labels.required),
minLength: { value: 8, message: formatMessage(messages.minPasswordLength) },
2023-01-21 02:12:53 +01:00
validate: samePassword,
}}
>
2023-01-25 16:42:46 +01:00
<PasswordField autoComplete="confirm-password" />
2023-01-21 02:12:53 +01:00
</FormInput>
</FormRow>
<FormButtons flex>
<Button type="submit" variant="primary" disabled={isLoading}>
2023-01-25 16:42:46 +01:00
{formatMessage(labels.save)}
2023-01-21 02:12:53 +01:00
</Button>
2023-01-25 16:42:46 +01:00
<Button onClick={onClose}>{formatMessage(labels.cancel)}</Button>
2023-01-21 02:12:53 +01:00
</FormButtons>
</Form>
);
}