This code violates the KISS principle by implementing overly complex permission checking logic with nested role hierarchies and permission matrices. A simpler approach would be:
const ROLE_PERMISSIONS = {
admin: () => true, // Admin can do everything
manager: (action, resource) => {
const allowed = {
read: ['post', 'comment', 'draft', 'user'],
write: ['post', 'comment', 'draft'],
delete: ['post', 'comment']
};
return allowed[action]?.includes(resource) ?? false;
},
editor: (action, resource) => {
const allowed = {
read: ['post', 'comment', 'draft'],
write: ['post', 'comment']
};
return allowed[action]?.includes(resource) ?? false;
},
user: (action, resource) => {
const allowed = {
read: ['post', 'comment'],
write: ['comment']
};
return allowed[action]?.includes(resource) ?? false;
}
};
function checkPermission(user, action, resource) {
return user?.roles?.some(role =>
ROLE_PERMISSIONS[role]?.(action, resource)
) ?? false;
}