views:

143

answers:

1

So I have an application that has several modules (think of modules as different pages), each module has a set of permissions; view, add, edit, delete

I want each user role to have privileges for each module, for example

Role A Permissions

Module 1 -> view
Module 2 -> add, edit
Module 3 -> view, add, edit, delete
etc.

How can I design the database to support that and how would I go about implementing it using bitwise operators (or would there be a more efficient way for this particular case?)

I already have the user, user_role and role tables but I'm unsure on how to design the Module table.

+1  A: 

If you decide to use a bitmask, remember that the number of permissions you can keep track of is limited (you can track 31 permissions in a signed 4-byte integer database column). Each permission would then be assigned a value that is a power of two (1, 2, 4, 8, etc), and you could perform bitwise operations to check for permission matches.

From what you're looking to accomplish, I would suggest creating a role_has_module_privs table instead. This approach is much more scalable, and more efficient from a querying perspective. But if you have a finite number of combinations, bitmasks may be more efficient.

Kenaniah
I'm already familiar with `bitmask` I just need to know if there's a way to track permissions for each module. Like I said each module only has 4 different permissions and even if I decided to add more permissions later on I doubt I'll ever go over 31 permissions.Not quite sure how your approach will work, do you mean that `role_has_module_privs` will contain something like**id_module**, **id_role**,**permissions**
Serge
Very close. Schema would probably look like **id_module**, **id_role**, **id_permission**. Using your example, module 3 would have four records in this table. Your primary key would be a composite of **id_module** and **id_role**.
Kenaniah
Performance/maintainability wise what would be better, using bitmask (less rows in db but more lines of code on each page) so that each role will on have one row in `role_has_module_privs` or use your way (have more rows, an extra table but probably less code on each page)
Serge
In general, it's probably a wash. I would recommend one row per permission as that better adheres to the rules of database normalization.
Kenaniah
Accepted and up-voted, thanks for your help!
Serge