I am working on a MERN stack app that is a CRM with a couple of modules. Now when the user sends x request to the server to do a supposed action (such as delete something), the server first checks if the user has access by checking the MongoDB database users' collection's permissions property for an array of "permissions" that looks something like this:
[
{ name: "Leads", level: 1 },
{ name: "Conversations", level: 1 },
{ name: "Salesbot", level: 0 },
{ name: "Reporting", level: 1 },
{ name: "Contacts", level: 4 },
]
This states the level of permission this user has for each module. There are 5 possible levels conveying different amounts of access, these are:
- None
- Accepted only
- Read
- Write
- All
Each level automatically grants access to the levels that would be before it. So if the user has write permission, he would logically, also have read permission as well.
I wrote a function that I call every time to check if the user has X relevant permission before doing something on the server.
The function is as follows:
const checkPermission = (permissions, checkFor) => {
for (let i = 0; i < permissions.length; i++) {
const permission = permissions[i];
if (
permission.name === checkFor.name &&
permission.level >= checkFor.level
) {
return true;
}
}
return false;
};
and then I call it this way:
checkPermission(
[
{ name: "Leads", level: 1 },
{ name: "Conversations", level: 1 },
{ name: "Salesbot", level: 0 },
{ name: "Reporting", level: 1 },
{ name: "Contacts", level: 4 },
],
{ name: "Contacts", level: 3 }
);
So this function call checks to see if the user has write access in the contacts module, and if they do, then it returns true, if they don't, then false.
I welcome any sort of improvements to the code, but most importantly, I would welcome improvements to the logic of permissions if there are any. I came up with this permissions levels system on my own without much research, so there could be many things in this that I would be neglecting unknowingly that you guys can point out. Perhaps an entirely new way of handling permissions or whatever, I welcome any sort of improvements.