Thursday, November 20, 2008

Using biwise operator to implement user access

Here's a way to use biwise operator to implement user access of special section on a site.

1. Define Constants:
PER_ADD = 1 (000001)
PERM_EDIT = 2 (000010)
PERM_DELETE = 4 (000100)
PERM_VIEW = 8 (001000)

2. Define user access level code:
EDIT => 63 (111111)
READ => 8 (000100)
NOACCESS=>0(000000)

3. Each user is associate with one or more access level code base on the section.

4. The algorithm to perform user access check is like this:
if((userAccessCode & PERM_EDIT) == PERM_EDIT){
grand access
}else{
access denial
}


How this works?
Using above example, if the user access code for a special section is defined as 63 which the binary representation is 111111, and we want to check if the user has edit permission for the section, then we can use the & biwise operator to figure it out. Sine the PERM_EDIT is define as 2 (000010), so

1 1 1 1 1 1 (63)
& 0 0 0 0 1 0 (2)
--------------
0 0 0 0 1 0 (2)

which if((userAccessCode & PERM_EDIT) == PERM_EDIT){ } will return true, so user can modify this section.

Other example, if the user access code is 8 (000100),

0 0 0 1 0 0 (63)
& 0 0 0 0 1 0 (8)
--------------
0 0 0 0 0 0 (0)

which if((userAccessCode & PERM_EDIT) == PERM_EDIT){ } will return false, so user can not modify this section.


Here's a list of possible combinations:
0 & 0 = 0
8 & 8 = 8 (Read)
63 & 8 = 8 (Read)
63 & 2 = 2 (Write)
8 & 2 = 0 (No write)

1 comment:

Jerry said...
This comment has been removed by a blog administrator.