Skip to content

Instantly share code, notes, and snippets.

@Maqsim
Last active December 23, 2015 08:19
Show Gist options
  • Save Maqsim/6607100 to your computer and use it in GitHub Desktop.
Save Maqsim/6607100 to your computer and use it in GitHub Desktop.
Allow and deny permissions
<?php
/**
* Give or deny access for some user level
* Examples:
* "+(4)" --> [4]
* "+(user, 4)" --> [1, 4]
* "+(10) -(2, operators) +(all)" --> [1,2,3,4,7,10]
* "+(all)-(3)" --> [1,2,4,7,10]
* "-(all)" --> []
* "-(2,10)" --> [1,3,4,7]
*
* NOTICE: DON'T USE THIS MECHANISM FOR PUBLIC API METHODS
*
* @param string $access_sctring
*/
function access($access_string) {
$access_string = trim($access_string);
$aliases = array(
'all' => '1,2,3,4,7,10',
'operators' => '2,10',
'user' => '1',
'admins' => '3,4',
'seo' => '7'
);
// If "+(<some>)" then give permissions for only this list firstly.
// Otherwise give permissions for all levels -- add +(all) in head of $access_string
if (!$access_string OR $access_string[0] == '-') $access_string = "+(all)$access_string";
// Aliases multi-replacement. Ex.: admins -> 3,4
foreach($aliases as $alias => $levels)
$access_string = str_replace($alias, $levels, $access_string);
preg_match_all("/[\-|\+]\(.*?\)/", $access_string, $matches);
$allow = array();
$deny = array();
// Push and/or pop level from $allow and $deny arrays
// '+' -- push to $allow, pop from $deny
// '-' -- reverse '+'
foreach($matches[0] as $pattern) {
$arr = explode(',', substr($pattern, 2, strlen($pattern)-3));
if ($pattern[0] == '+') {
$allow = array_merge($allow, $arr);
$deny = array_diff($deny, $arr);
} else {
$deny = array_merge($deny, $arr);
$allow = array_diff($allow, $arr);
}
}
// Get final list of allow-access levels
$permissions = array_unique(array_filter(array_diff($allow, $deny)));
// If user->access_level is not in $permission then show "550 Permission Denied" error
$CI =& get_instance();
if(!@in_array($CI->authentication->user->access_level, $permissions)) {
header($_SERVER['SERVER_PROTOCOL']." 550 Permission Denied", true, 550);
header('Content-Type: application/json');
exit(json_encode(array('status' => false, 'error' => 'Permission Denied')));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment