umami/components/forms/ChangePasswordForm.js

86 lines
2.3 KiB
JavaScript
Raw Normal View History

2020-08-09 08:48:43 +02:00
import React, { useState } from 'react';
import { Formik, Form, Field } from 'formik';
import { post } from 'lib/web';
import Button from 'components/common/Button';
import FormLayout, {
FormButtons,
FormError,
FormMessage,
FormRow,
} from 'components/layout/FormLayout';
const initialValues = {
2020-08-09 11:03:37 +02:00
current_password: '',
new_password: '',
confirm_password: '',
2020-08-09 08:48:43 +02:00
};
2020-08-09 11:03:37 +02:00
const validate = ({ current_password, new_password, confirm_password }) => {
2020-08-09 08:48:43 +02:00
const errors = {};
2020-08-09 11:03:37 +02:00
if (!current_password) {
errors.current_password = 'Required';
2020-08-09 08:48:43 +02:00
}
2020-08-09 11:03:37 +02:00
if (!new_password) {
errors.new_password = 'Required';
2020-08-09 08:48:43 +02:00
}
2020-08-09 11:03:37 +02:00
if (!confirm_password) {
errors.confirm_password = 'Required';
} else if (new_password !== confirm_password) {
errors.confirm_password = `Passwords don't match`;
2020-08-09 08:48:43 +02:00
}
return errors;
};
export default function ChangePasswordForm({ values, onSave, onClose }) {
const [message, setMessage] = useState();
const handleSubmit = async values => {
2020-08-09 11:03:37 +02:00
const response = await post(`/api/account/password`, values);
2020-08-09 08:48:43 +02:00
2020-08-09 11:03:37 +02:00
if (typeof response !== 'string') {
2020-08-09 08:48:43 +02:00
onSave();
} else {
2020-08-09 11:03:37 +02:00
setMessage(response || 'Something went wrong');
2020-08-09 08:48:43 +02:00
}
};
return (
<FormLayout>
<Formik
initialValues={{ ...initialValues, ...values }}
validate={validate}
onSubmit={handleSubmit}
>
{() => (
<Form>
<FormRow>
2020-08-09 11:03:37 +02:00
<label htmlFor="current_password">Current password</label>
<Field name="current_password" type="password" />
<FormError name="current_password" />
2020-08-09 08:48:43 +02:00
</FormRow>
<FormRow>
2020-08-09 11:03:37 +02:00
<label htmlFor="new_password">New password</label>
<Field name="new_password" type="password" />
<FormError name="new_password" />
2020-08-09 08:48:43 +02:00
</FormRow>
<FormRow>
2020-08-09 11:03:37 +02:00
<label htmlFor="confirm_password">Confirm password</label>
<Field name="confirm_password" type="password" />
<FormError name="confirm_password" />
2020-08-09 08:48:43 +02:00
</FormRow>
<FormButtons>
<Button type="submit" variant="action">
Save
</Button>
<Button onClick={onClose}>Cancel</Button>
</FormButtons>
<FormMessage>{message}</FormMessage>
</Form>
)}
</Formik>
</FormLayout>
);
}