umami/components/forms/UserPasswordForm.js

82 lines
2.2 KiB
JavaScript
Raw Normal View History

2022-12-26 21:34:23 +01:00
import { useRef } from 'react';
import { Form, FormInput, FormButtons, PasswordField, Button } from 'react-basics';
import { useApi } from 'next-basics';
2022-12-26 07:00:20 +01:00
import { useMutation } from '@tanstack/react-query';
import { getAuthToken } from 'lib/client';
2022-12-26 21:48:20 +01:00
import styles from './UserPasswordForm.module.css';
2022-12-26 21:34:23 +01:00
import useUser from 'hooks/useUser';
export default function UserPasswordForm({ onSave, userId }) {
const {
user: { id },
} = useUser();
2022-12-26 07:00:20 +01:00
2022-12-26 21:34:23 +01:00
const isCurrentUser = !userId || id === userId;
const url = isCurrentUser ? `/users/${id}/password` : `/users/${id}`;
2022-12-26 07:00:20 +01:00
const { post } = useApi(getAuthToken());
2022-12-26 21:34:23 +01:00
const { mutate, error, isLoading } = useMutation(data => post(url, data));
2022-12-26 07:00:20 +01:00
const ref = useRef(null);
const handleSubmit = async data => {
2022-12-26 21:34:23 +01:00
const payload = isCurrentUser
? data
: {
password: data.new_password,
};
mutate(payload, {
onSuccess: async () => {
onSave();
ref.current.reset();
2022-12-26 07:00:20 +01:00
},
2022-12-26 21:34:23 +01:00
});
2022-12-26 07:00:20 +01:00
};
const samePassword = value => {
if (value !== ref?.current?.getValues('new_password')) {
return "Passwords don't match";
}
return true;
};
return (
2022-12-26 21:34:23 +01:00
<Form ref={ref} className={styles.form} onSubmit={handleSubmit} error={error}>
{isCurrentUser && (
2022-12-26 07:00:20 +01:00
<FormInput
2022-12-26 21:34:23 +01:00
name="current_password"
label="Current password"
rules={{ required: 'Required' }}
2022-12-26 07:00:20 +01:00
>
<PasswordField autoComplete="off" />
</FormInput>
2022-12-26 21:34:23 +01:00
)}
<FormInput
name="new_password"
label="New password"
rules={{
required: 'Required',
minLength: { value: 8, message: 'Minimum length 8 characters' },
}}
>
<PasswordField autoComplete="off" />
</FormInput>
<FormInput
name="confirm_password"
label="Confirm password"
rules={{
required: 'Required',
minLength: { value: 8, message: 'Minimum length 8 characters' },
validate: samePassword,
}}
>
<PasswordField autoComplete="off" />
</FormInput>
<FormButtons flex>
<Button type="submit" disabled={isLoading}>
Save
</Button>
</FormButtons>
</Form>
2022-12-26 07:00:20 +01:00
);
}