Prevent admin from resetting their own role.

This commit is contained in:
Mike Cao 2024-02-16 10:22:18 -08:00
parent 2e871af05b
commit f25cd93012
10 changed files with 66 additions and 31 deletions

View file

@ -1,88 +0,0 @@
import {
Dropdown,
Item,
Form,
FormRow,
FormButtons,
FormInput,
TextField,
SubmitButton,
PasswordField,
useToasts,
} from 'react-basics';
import { useApi, useMessages } from 'components/hooks';
import { ROLES } from 'lib/constants';
import { useRef } from 'react';
export function UserEditForm({ userId, data }: { userId: string; data: object }) {
const { formatMessage, labels, messages } = useMessages();
const { post, useMutation } = useApi();
const { mutate, error } = useMutation({
mutationFn: ({
username,
password,
role,
}: {
username: string;
password: string;
role: string;
}) => post(`/users/${userId}`, { username, password, role }),
});
const ref = useRef(null);
const { showToast } = useToasts();
const handleSubmit = async (data: any) => {
mutate(data, {
onSuccess: async () => {
showToast({ message: formatMessage(messages.saved), variant: 'success' });
ref.current.reset(data);
},
});
};
const renderValue = (value: string) => {
if (value === ROLES.user) {
return formatMessage(labels.user);
}
if (value === ROLES.admin) {
return formatMessage(labels.administrator);
}
if (value === ROLES.viewOnly) {
return formatMessage(labels.viewOnly);
}
};
return (
<Form ref={ref} onSubmit={handleSubmit} error={error} values={data} style={{ width: 300 }}>
<FormRow label={formatMessage(labels.username)}>
<FormInput name="username">
<TextField />
</FormInput>
</FormRow>
<FormRow label={formatMessage(labels.password)}>
<FormInput
name="password"
rules={{
minLength: { value: 8, message: formatMessage(messages.minPasswordLength, { n: 8 }) },
}}
>
<PasswordField autoComplete="new-password" />
</FormInput>
</FormRow>
<FormRow label={formatMessage(labels.role)}>
<FormInput name="role" rules={{ required: formatMessage(labels.required) }}>
<Dropdown renderValue={renderValue}>
<Item key={ROLES.viewOnly}>{formatMessage(labels.viewOnly)}</Item>
<Item key={ROLES.user}>{formatMessage(labels.user)}</Item>
<Item key={ROLES.admin}>{formatMessage(labels.administrator)}</Item>
</Dropdown>
</FormInput>
</FormRow>
<FormButtons>
<SubmitButton variant="primary">{formatMessage(labels.save)}</SubmitButton>
</FormButtons>
</Form>
);
}
export default UserEditForm;