On the other hand, just to argue with myself a little bit, the permissions object alternative does avoid accessing the database every time. That may or may not be important and worthwhile. Anyway, here's another way to do it:
PHP Code:
define('DO_STUFF',1);
class Permissions {
var $permissions = array();
function Permissions($permissionArray) {
$this->permissions = $permissionArray;
}
function isAllowed($permission) {
return array_key_exists($permission,$this->permissions);
}
}
class Authoriser {
function getPermissions($userAccount) {
$sql = "SELECT permission FROM Permissions p, Roles r, UserRoles ur, UserAccounts u ".
"WHERE p.role_id = r.id AND r.id = ur.role_id AND ur.account_id = u.id ".
"AND u.name = '$userAccount'";
$result = mysql_query($sql);
$permissionArray = array();
while ($row = mysql_fetch_array($result)) {
$permissionArray[$row[0]] = TRUE;
}
$_SESSION['permissions'] = new Permissions($permissionArray);
return $_SESSION['permissions'];
}
function isAllowed($permission) {
return $_SESSION['permissions']->isAllowed($permission);
}
}
And here's the test code:
PHP Code:
function testNonUserHasNothingAllowed() {
$permissions = Authoriser::getPermissions('nobody');
$this->assertFalse($permissions->isAllowed(DO_STUFF));
$this->assertFalse(Authoriser::isAllowed(DO_STUFF));
}
function testLegitimateUserHasActionAllowed() {
$permissions = Authoriser::getPermissions('fred');
$this->assertTrue($permissions->isAllowed(DO_STUFF));
$this->assertTrue(Authoriser::isAllowed(DO_STUFF));
}
Bookmarks