I have a PHP MySQL application which has a modular design. There are about 5 modules total now, and I don’t really foresee there ever being more than 10.
I currently have 2 types of users – “User and Admin”. These user types have the same perms except the Admins can edit users, whereas regular users can’t.
I want to implement modular permssions, such that if you are an Admin you have permissions to make changes in ALL modules. If you are a regular User, there will be a way to set which modules that user has access to (ie a set of checkmarks).
My question is, what is the best way to store this in the database? I already have a Users table. I’ve come up with the following 3 solutions right off the top of my head, I’m wondering if there is a recommended way to do it or if there are other ways. I also need to keep in mind that when upgrading the application to the new version, I will have to set up perms for all users currently in the DB. I also have to be able to easily add a default perm for each user when a new module is integrated. I’m looking for something easy to maintain and implement, but flexible for adding a few more modules.
My brainstormed options so far:
- Store perms in the Users table in a column with a bit-mask type of string: 10001 indicates they have permissions for “Module A” and “Module E” only.
- Store perms in the Users table in a column with a delimited (comma or pipe) list of module names which the user has perms for: “ModuleA,ModuleE”.
- Create a separate table for user perms like so:
UserId | Module | Permission 1 | A | 1 1 | B | 0
What do you think?
It sounds like you are only tracking access as opposed to granular permissions which is fine.
I would highly recommend against this. Bit masks in databases are a maintenance nightmare. It is not even remotely obvious to another developer what the meaning of each of the bits represent.
This is a variant on your first solution only using a delimiter. Again, I would highly recommend against it as it is a maintenance headache.
This is the solution I would recommend. The big reason is that it is more extensible than the others and is easier to maintain. If you wanted to make a maintenance screen to control permissions, it would be trivial using this approach. You can easily add modules, change the order of the modules and later expand on what is maintained in the table (e.g. you might later add “Read Only” as a column as different than the ability to simply access the module). In addition, this approach makes it easier to pull information from the table. “Who has access to module X?” is an easy query to write with this, it is harder using a delimited list or bit mask.