Justin
Justin

Reputation: 2530

PHP BitWise Permissions & Roles, or Alternatives

I am doing my first app that contains permissions and roles with multiple users. My understanding is the best way to do this is using BitWise formatting. Is this true, or is there a better alternative?

This is my current Test Code, and I'm getting a rather bizzare effect. If someone could shed some light as to why this is happening the way it is, that would be greatly appreciated.

EXAMPLE:

$user = array('permissions' => 1); // This *should* return ONLY READ, (except it shows all)
$user = array('permissions' => 8); // Shows correct, FULL resources.

You can use this to test the code... http://writecodeonline.com/php/

define("PERM_R", 1);  # Read    
define("PERM_W", 2);  # Write   
define("PERM_E", 4);  # Edit    
define("PERM_D", 8);  # Delete  

define("ROLE_GUEST",  PERM_R);
define("ROLE_EDITOR", ROLE_GUEST | PERM_W | PERM_E);
define("ROLE_FULL",   ROLE_EDITOR | PERM_D);

function hasAccess($user, $action) {
    if( is_array($user) ) {
        return $user['permissions'] & $action;
    } else if ( is_int($user) ) {
        return $user & $action;
    }
}


$user = array('permissions' => 1);
echo "USER PERMISSIONS: ". $user['permissions'] ."<br /><br />";

# TEST PERMS
if(hasAccess($user, PERM_R)) {
    echo PERM_R;
    echo " - Yes you can see READ <br />";
}
if(hasAccess($user, PERM_R | PERM_W)) {
    echo PERM_R | PERM_W;
    echo " - Yes you can see READ & WRITE<br />";
}
if(hasAccess($user, PERM_R | PERM_W | PERM_E)) {
    echo PERM_R | PERM_W | PERM_E;
    echo " - Yes you can see READ & WRITE & EDIT<br />";
}
if(hasAccess($user, PERM_R | PERM_W | PERM_E | PERM_D)) {
    echo PERM_R | PERM_W | PERM_E | PERM_D;
    echo " - Yes you can see READ & WRITE & EDIT & DELETE<br />";
}

# TEST ROLES
if(hasAccess($user, ROLE_GUEST)) {
    echo ROLE_GUEST;
    echo " - Yes, You Are A GUEST <br />";
}
if(hasAccess($user, ROLE_EDITOR)) {
    echo ROLE_EDITOR;
    echo " - Yes, You Are A EDITOR <br />";
}
if(hasAccess($user, ROLE_FULL)) {
    echo ROLE_FULL;
    echo " - Yes, You Are A FULL <br />";
}

Upvotes: 3

Views: 3617

Answers (1)

Sammitch
Sammitch

Reputation: 32272

The issue is that you're simply returning the results of a bitwise & which, for all of your tests, is at least 1/true because all users have the R permission.

  1. Only feed one permission into hasAccess(), stop using |.
  2. Write a new function to determine the user level that does an integer comparison.

Upvotes: 2

Related Questions