Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Manage roles with math?

Tags:

php

roles

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!

like image 409
Mike Moore Avatar asked May 11 '10 06:05

Mike Moore


2 Answers

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 :)

like image 123
Palantir Avatar answered Sep 19 '22 08:09

Palantir


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.

like image 26
oezi Avatar answered Sep 19 '22 08:09

oezi