2022-12-27 01:57:59 +01:00
|
|
|
import { useRef } from 'react';
|
|
|
|
import { Form, FormInput, FormButtons, PasswordField, Button } from 'react-basics';
|
2022-12-28 05:20:44 +01:00
|
|
|
import useApi from 'hooks/useApi';
|
2022-12-27 01:57:59 +01:00
|
|
|
import { useMutation } from '@tanstack/react-query';
|
2022-12-28 05:20:44 +01:00
|
|
|
import { getClientAuthToken } from 'lib/client';
|
2022-12-27 01:57:59 +01:00
|
|
|
import styles from './UserPasswordForm.module.css';
|
|
|
|
import useUser from 'hooks/useUser';
|
|
|
|
|
|
|
|
export default function UserPasswordForm({ onSave, userId }) {
|
|
|
|
const {
|
|
|
|
user: { id },
|
|
|
|
} = useUser();
|
|
|
|
|
|
|
|
const isCurrentUser = !userId || id === userId;
|
|
|
|
const url = isCurrentUser ? `/users/${id}/password` : `/users/${id}`;
|
2022-12-28 05:20:44 +01:00
|
|
|
const { post } = useApi(getClientAuthToken());
|
2022-12-27 01:57:59 +01:00
|
|
|
const { mutate, error, isLoading } = useMutation(data => post(url, data));
|
|
|
|
const ref = useRef(null);
|
|
|
|
|
|
|
|
const handleSubmit = async data => {
|
|
|
|
const payload = isCurrentUser
|
|
|
|
? data
|
|
|
|
: {
|
2022-12-27 02:36:48 +01:00
|
|
|
password: data.newPassword,
|
2022-12-27 01:57:59 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
mutate(payload, {
|
|
|
|
onSuccess: async () => {
|
|
|
|
onSave();
|
|
|
|
ref.current.reset();
|
|
|
|
},
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
|
|
|
const samePassword = value => {
|
2022-12-27 02:36:48 +01:00
|
|
|
if (value !== ref?.current?.getValues('newPassword')) {
|
2022-12-27 01:57:59 +01:00
|
|
|
return "Passwords don't match";
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
};
|
|
|
|
|
|
|
|
return (
|
|
|
|
<Form ref={ref} className={styles.form} onSubmit={handleSubmit} error={error}>
|
|
|
|
{isCurrentUser && (
|
2022-12-27 02:36:48 +01:00
|
|
|
<FormInput name="currentPassword" label="Current password" rules={{ required: 'Required' }}>
|
2022-12-27 01:57:59 +01:00
|
|
|
<PasswordField autoComplete="off" />
|
|
|
|
</FormInput>
|
|
|
|
)}
|
|
|
|
<FormInput
|
2022-12-27 02:36:48 +01:00
|
|
|
name="newPassword"
|
2022-12-27 01:57:59 +01:00
|
|
|
label="New password"
|
|
|
|
rules={{
|
|
|
|
required: 'Required',
|
|
|
|
minLength: { value: 8, message: 'Minimum length 8 characters' },
|
|
|
|
}}
|
|
|
|
>
|
|
|
|
<PasswordField autoComplete="off" />
|
|
|
|
</FormInput>
|
|
|
|
<FormInput
|
2022-12-27 02:36:48 +01:00
|
|
|
name="confirmPassword"
|
2022-12-27 01:57:59 +01:00
|
|
|
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>
|
|
|
|
);
|
|
|
|
}
|