...

View Full Version : Permissions with bitwise operations



MoD
07-01-2007, 10:40 PM
Ok, users in my system can have ONE number in their permissions field.. Namely:

SUPER_ADMIN = 0;
ADMIN = 1;
MODERATOR = 2;
MENTOR = 3;
USER = 4;
GUEST = 5;

Easy ha? Well... Not exactly.. Heres the entire class


class user
{
// Rights constants
const SUPER_ADMIN = 0;
const ADMIN = 1;
const MODERATOR = 2;
const MENTOR = 3;
const USER = 4;
const GUEST = 5;

/**
* @access public
* Loads the user. Must be done in every script
* that needs user access!
*/
public function load()
{
}

/**
* Checks if the user is logged in...
* @access public
* @return bool
*/
public function logged_in()
{
if($_SESSION['auth'] === true && $_SESSION['user_id'] != '')
{
return true;
}
else
{
return false;
}
}

/**
* Checks if the user has a specific right
* @access public
* @param right - numerical
* @return true if the user has right, false otherwise
*/
public function is_right($value)
{
if($this->rights == $value)
{
return true;
}
else
{
return false;
}
}

/**
* Checks for specifics
* @access public
* @return bool
*/
public function is_sadmin()
{
if($this->rights == SUPER_ADMIN)
{
return true;
}
else
{
return false;
}
}

/**
* Checks for specifics
* @access public
* @return bool
*/
public function is_admin()
{
if($this->rights == ADMIN || $this->rights == SUPER_ADMIN)
{
return true;
}
else
{
return false;
}
}

/**
* Checks for specifics
* @access public
* @return bool
*/
public function is_mentor()
{
if($this->rights == MENTOR || $this->rights == ADMIN || $this->rights == SUPER_ADMIN)
{
return true;
}
else
{
return false;
}
}

/**
* Checks for specifics
* @access public
* @return bool
*/
public function is_user()
{
if($this->rights == USER || $this->rights == ADMIN || $this->rights == SUPER_ADMIN
|| $this->rights == MENTOR)
{
return true;
}
else
{
return false;
}
}
}


Dont bother about some unfinished functions. So, do you see the problem?

Logically, if the USER has access to X, then the admins and mods will have access to there too.. Right? Basically, the problem is, the lower you go in the functions that check the user rights ( is_user , is_mod) the more OR's there are... I dont like that.

Is there an easier method involving bitwise operations?

Thanks!

firepages
07-02-2007, 02:49 AM
with top down authentication you only need check if the status <= than the required minimum level


<?
public function is_user()
{
if($this->rights <= USER)
{
return true;
}
else
{
return false;
}
?>

Fumigator
07-02-2007, 04:04 AM
In case your access levels aren't as clean as top-down and thus you can't use the simple technique Firepages mentioned, then this thread may help you:

http://www.codingforums.com/showthread.php?t=117414

Xer0-
07-02-2007, 08:36 AM
what about using a switch statement




switch($permissions) {

case "1":
return whatever;
break;

case "2":
dostuff();
break;

case "3":
dostuff();
break;
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum