Skip to content

Commit

Permalink
feat: refactor permission handling by extracting getFieldPermissions …
Browse files Browse the repository at this point in the history
…function
  • Loading branch information
simlarsen committed Jan 7, 2025
1 parent a7ad9b7 commit 7b68c0b
Showing 1 changed file with 41 additions and 10 deletions.
51 changes: 41 additions & 10 deletions Common/UI/Components/Forms/ModelForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -188,16 +188,7 @@ const ModelForm: <TBaseModel extends BaseModel>(

userPermissions.push(Permission.Public);

const accessControl: Dictionary<ColumnAccessControl> =
model.getColumnAccessControlForAllColumns();

let fieldPermissions: Array<Permission> = [];

if (FormType.Create === props.formType) {
fieldPermissions = accessControl[fieldName]?.create || [];
} else {
fieldPermissions = accessControl[fieldName]?.update || [];
}
const fieldPermissions: Array<Permission> = getFieldPermissions(fieldName);

if (
fieldPermissions &&
Expand All @@ -212,6 +203,23 @@ const ModelForm: <TBaseModel extends BaseModel>(
return false;
};

const getFieldPermissions: (fieldName: string) => Array<Permission> = (
fieldName: string,
): Array<Permission> => {
const accessControl: Dictionary<ColumnAccessControl> =
model.getColumnAccessControlForAllColumns();

let fieldPermissions: Array<Permission> = [];

if (FormType.Create === props.formType) {
fieldPermissions = accessControl[fieldName]?.create || [];
} else {
fieldPermissions = accessControl[fieldName]?.update || [];
}

return fieldPermissions;
};

const setFormFields: PromiseVoidFunction = async (): Promise<void> => {
let fieldsToSet: Fields<TBaseModel> = [];

Expand Down Expand Up @@ -278,6 +286,29 @@ const ModelForm: <TBaseModel extends BaseModel>(

fieldsToSet = await fetchDropdownOptions(fieldsToSet);

// if there are no fields to set, then show permission erorr. This is useful when there are no fields to show.
if (fieldsToSet.length === 0 && props.fields.length > 0) {
const field: ModelField<TBaseModel> | undefined = props.fields[0];

if (field) {
const fieldName: string | undefined = Object.keys(field.field || {})[0];

if (fieldName) {
const fieldPermisisons: Array<Permission> =
getFieldPermissions(fieldName);

const columnMetadata: TableColumnMetadata =
model.getTableColumnMetadata(fieldName);

setError(
`You don't have enough permissions to ${
props.formType === FormType.Create ? "create" : "edit"
} ${columnMetadata.title} on ${model.singularName}. You need one of the following permissions: ${fieldPermisisons.join(", ")}`,
);
}
}
}

setFields(fieldsToSet);
};

Expand Down

0 comments on commit 7b68c0b

Please sign in to comment.