tags:

views:

100

answers:

2

I once saw an article about how to use a specific type of numbering system to manage roles. A user would be assigned a specific role number and depending on a calculation, the number could stand for multiple roles.

Can anybody share this technique with me or share a link? Thanks!

+3  A: 

i think you have heard of "bit-flags". i don't know a good english turorial for that (i'm german) - but i think google will give you some nice links.

oezi
I guess this answers what OP was looking for.
Salman A
@oezi Thanks for your help. Apparently, I was asking about "bit-masks", as @Palantir has described.
letseatfood
+16  A: 

It is a bitmask. It works like this: you assign to each role a progressive number, then when you want to assign one role to a user, you pick the number of that role. If you want to add another role, you just add that role number to the original one. You can add as many roles as you wish. The trick is just how you choose your numbers: they are the powers of 2.

Here is an example:

Role: Editor.     Value: 2^0 = 1
Role: Manager.    Value: 2^1 = 2
Role: Supervisor. Value: 2^2 = 4
Role: Admin.      Value: 2^3 = 8
...

To give a user the role of Editor, you save 1 to the database, To give a user the roles of Editor, Manager and Admin you save 1 + 2 + 8 = 11

You can see why this works, if you see it as an array of 1 or 0 values.

|__|__|__|__|__|__|
    16  8  4  2  1 

Each role is a 1 in the corresponding slot. So our 11 case is:

|__|__|_1|_0|_1|_1|
    16  8  4  2  1 

If you have a bitmask, and you want to know whether the user has a certain role, you use this operation:

(bitmask & role_value) >= 1

For example:

(11 & 8) >= 1? yes, so the user has the admin role
(11 & 4) >= 1? no, so the user has not the supervisor role

It is called a bitmask, because what you are doing is to "check whether in a particular position there is a 1", that is, "apply a mask which will mask (set to 0) all the places, except the one you are searching for):

11 --> |__|__|_1|_0|_1|_1|
           16  8  4  2  1 
 8 --> |__|__|_1|_0|_0|_0|  (mask)
           16  8  4  2  1 
AND -> |__|__|_1|_0|_0|_0|  Result: Yes

Hope it helped :)

Palantir
@Palantir - Thanks! This is exactly what I was looking for. It is so easy to manage users this way!!
letseatfood
Really nice answer!
MartyIX