In many applications you have the need to set users privileges , and while there are many ways to do so, I prefer to using a single integer value to store a users privileges on any single entity.
This has many advantages,
- you only have a single value representing all privileges
- you can add and remove available privileges without altering the schema/entity model/storage logic
- checking for privileges are very simple
Now you might be wondering, how is it possible to store any number of privileges in a single integer?
One of the keys to doing this are the values that you assign each privilege, these must each be twice the previous value.
- Read = 1
- Write = 2
- Delete = 4
- … = 8
To understand why we do it like this we need to take a look at the individual integers binary representation
1 = 00000001 2 = 00000010 4 = 00000100 8 = 00001000
Anyone see the pattern?
And if you were to sum some of these, say Write (2) + Delete(4)
00000010 + 00000100 = 00000110
Again, you see the pattern?
Each privilege is being stored as a single bit in the integer, and each bit can be checked against even if you add multiple values together.
So, now that we have some of the theory covered, how do we utilize this?
If you have an integer you can easily check for any fraction using a simple statement
var allPrivileges = 6; var hasWrite = (allPrivileges == (allPrivileges | 2));
Dim allPrivileges As Integer = 6 Dim hasWrite As Boolean = allPrivileges = (allPrivileges Or 2)
Here we are using the bitwise operator | (or) to check that allPrivileges (6) binary or‘ed with 2 equals 6, meaning that 2 is a contained fraction of 6.
Now if you want to add a new privilege (or existing one) you just binary or the current integer with the new integer
var allPrivileges = 4; allPrivileges = allprivileges | 2; // allPrivileges equals 6 allPrivileges= allprivileges | 2; // allPrivileges still equals 6
Dim allPrivileges As Integer = 4 allPrivileges = (allPrivileges Or 2) ' allPrivileges equals 6 allPrivileges = (allPrivileges Or 2) ' allPrivileges still equals 6
Wasn’t that easy?
In an upcoming post I will show you a simple ExtJs control for visualizing and modifying a users privileges.