I'd like to create a system where there are maybe 4-5 types of user groups that can access certain things. The higher the permissions, the more they can do. That's simple to make for me, but the hard part for me is to create the system where the higher ranks can do anything lower ranks can, but lower ranks cannot do what higher ranks can.
I was thinking something like this:
if (user.group === "mod" || user.group === "admin"){
// do stuff
if (user.group === "admin"){
// do stuff
}
}
It seems like there's an easier way to do it though.
Why not try a switch statement?
switch(user.group) {
case 'admin':
// admin permissions
case 'mod':
// admin permission (waterfall effect)
// mod permission
case 'user':
// admin permission (waterfall effect)
// mod permission (waterfall effect)
// user permissions
default:
// default permissions;
break;
}
I don't see why this couldn't work.
Basically, by not adding break to each switch, an admin case will also trigger a mod case and a user case and default with a mod case also triggering a user case etc. etc.
You can introduce set of permissions, like PERMISSION_TO_DO_THING1, and so on. Next thing - roles, like ROLE_ADMIN, ROLE_SPECIAL_GUY, etc. Each role is a set of permissions. Just take care that higher role contains all the necessary permissions which lower role can do. That is logical thing and it is up to your app and the implementation. Anyway, in the end you need some method like userHasPermission(user, permission) and if its true - he can do things.
if (userHasPermission(user, PERMISSION_TO_ADD_USER)) {
// do things
}
if (userHasPermission(user, PERMISSION_TO_DELETE_USER)) {
// do things
}