Currently, I am developing a system for Role Based permissions that involves working with arrays. Here is an example of the array structure I have:
let Roles = {
[
{ model: 'user', property: 'find', permission: 'allow' },
{ model: 'user', property: 'create', permission: 'allow' },
{ model: 'user', property: 'update', permission: 'deny' },
{ model: 'user', property: 'delete', permission: 'deny' }
],
[
{ model: 'registration', property: 'find', permission: 'allow' },
{ model: 'registration', property: 'create', permission: 'deny' },
{ model: 'registration', property: 'update', permission: 'deny' },
{ model: 'registration', property: 'delete', permission: 'deny' }
]
[
{ model: 'schedule', property: 'find', permission: 'allow' },
{ model: 'schedule', property: 'create', permission: 'allow' },
{ model: 'schedule', property: 'update', permission :'allow'},
{ model: 'schedule', property: 'delete', permission: 'deny' }
]
}
The desired output I am trying to achieve is as follows:
let userPermissions = [{
'menu_name': 'user',
'canFetchData': true,
'canCreateData': true,
'canUpdateData': false,
'canDeleteData': false,
}]
let registrationPermissions = [{
'menu_name': 'registration',
'canFetchData': true,
'canCreateData': false,
'canUpdateData': false,
'canDeleteData': false,
}]
let schedulePermissions = [{
'menu_name': 'schedule',
'canFetchData': true,
'canCreateData': true,
'canUpdateData': true,
'canDeleteData': false,
}]
To generate these results, the conditions are simple: if the permission is 'allow', then set it to true; otherwise, set it to false.
In my attempt to achieve this, I encountered issues where values were getting overridden in the second array. To address this, I implemented conditional statements within a function that filters and applies permissions based on the data provided:
private canFetchData;
private canCreateData;
private canUpdateData;
private canDeleteData;
filterAndApplyPermission(data) {
for (let i = 0; i < data.length; i++) {
if (data[i].property === 'find' && data[i].permission === 'ALLOW') {
this.canFetchData = true;
} else if (data[i].property === 'create' && data[i].permission === 'ALLOW') {
this.canCreateData = true;
} else if (data[i].property === 'update' && data[i].permission === 'ALLOW') {
this.canUpdateData = true;
} else if (data[i].property === 'delete' && data[i].permission === 'ALLOW') {
this.canDeleteData = true;
}
}
const grouped_permission = {
'menu': data[0].model,
'canFetchData': this.canFetchData,
'canCreateData': this.canCreateData,
'canUpdateData': this.canUpdateData,
'canDeleteData': this.canDeleteData,
};
return grouped_permission;
}