Adding username validation for subscriptions

This commit is contained in:
Eric van der Vlist 2023-03-01 18:13:13 +01:00
parent e36f8cf927
commit 90fe60c10c
1 changed files with 42 additions and 23 deletions

View File

@ -9,6 +9,7 @@ import { put } from '~/lib/put';
import { del } from '~/lib/del';
import { isFunction } from 'lodash';
import { userId } from '~/lib/user-id';
import { userExists } from '~/lib/user-exists';
interface Props {
values?: () => any;
@ -47,6 +48,7 @@ const User: Component<Props> = (props) => {
roles: [],
};
await put(couchUserId, userDoc, isNew(), '_users');
if (isNew()) {
navigate(`/user/${id}`);
}
@ -86,33 +88,46 @@ const User: Component<Props> = (props) => {
return errors;
}
if (isNew()) {
const authString = `${username}:${password}`;
const headers = new Headers();
headers.set('Authorization', 'Basic ' + btoa(authString));
const response = await fetch(
`${database}/_users/org.couchdb.user:${values.username}`,
{
method: 'HEAD',
mode: 'cors',
headers,
const subscriptions = values.subscriptions ?? [];
for (let i = 0; i < subscriptions.length; i++) {
let subscription = subscriptions[i];
if (
!!subscription.username &&
!(await userExists(subscription.username))
) {
if (!errors.subscriptions) {
errors.subscriptions = [];
}
);
if (response.status === 200) {
errors.username = 'The user is already existing';
errors.subscriptions[i] = { username: "User doesn't exist" };
}
}
if (isNew()) {
if (await userExists(values.username)) {
errors.username = 'The user is already existing';
}
}
console.log({ caller: 'Users / validationHandler', values, errors });
return errors;
};
const { form, data, setData, setInitialValues, reset, addField, unsetField } =
createForm({
onSubmit: submitHandler,
extend: reporter(),
validate: validationHandler,
initialValues: getValues(),
});
const {
form,
data,
setData,
setInitialValues,
reset,
addField,
unsetField,
isDirty,
isValid,
} = createForm({
onSubmit: submitHandler,
extend: reporter(),
validate: validationHandler,
initialValues: getValues(),
});
const createUserHandler = async () => {
console.log({
@ -226,14 +241,18 @@ const User: Component<Props> = (props) => {
</table>
<Switch>
<Match when={!isNew()}>
<Button.Root type='submit'>Save</Button.Root>
<Button.Root type='submit' disabled={!isDirty() || !isValid()}>
Save
</Button.Root>
<Button.Root onclick={deleteHandler}>Delete</Button.Root>
</Match>
<Match when={isNew()}>
<Button.Root type='submit'>Create</Button.Root>
<Button.Root type='submit' isDisabled={!isValid()}>
Create
</Button.Root>
</Match>
</Switch>
<Button.Root onclick={cancelHandler}>Cancel</Button.Root>
<Button.Root onclick={cancelHandler}>Back</Button.Root>
</form>
</>
);