Created
June 18, 2011 02:51
-
-
Save mindplay-dk/1032750 to your computer and use it in GitHub Desktop.
Security context checking in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class SecurityContext | |
{ | |
private $_readonly = false; | |
private $_context = array(); | |
public static $actions = array( | |
); | |
public function __construct($user) | |
{ | |
$this->_context['user'] = $user; | |
} | |
public function __get($name) | |
{ | |
if (!array_key_exists($name, $this->_context)) { | |
throw new Exception("undefined security context '{$name}'"); | |
} | |
return $this->_context[$name]; | |
} | |
public function __set($name, $value) | |
{ | |
if ($this->_readonly) { | |
throw new Exception("access violation: security context is read-only"); | |
} | |
if (!array_key_exists($name, $this->_context)) { | |
throw new Exception("cannot overwrite security context '{$name}'"); | |
} | |
$this->_context[$name] = $value; | |
} | |
public function __call($action, $params) | |
{ | |
$this->_readonly = true; | |
if (!isset(self::$actions[$action])) { | |
throw new Exception("undefined action '{$action}'"); | |
} | |
$subject = array_key_exists(0, $params) ? $params[0] : null; | |
return call_user_func( self::$actions[$action], $this, $subject ); | |
} | |
} | |
SecurityContext::$actions['isAdmin'] = function($context, $subject) { | |
return $context->user === 'Rasmus' ? true : false; | |
}; | |
SecurityContext::$actions['canCreate'] = function($context, $subject) { | |
if (!$context->isAdmin()) { | |
return false; | |
} | |
if ($subject === 'BlogPost') { | |
return true; | |
} | |
return false; | |
}; | |
header('Content-type: text/plain'); | |
$context = new SecurityContext('Rasmus'); | |
var_dump($context->isAdmin()); // true | |
var_dump($context->canCreate('BlogPost')); // true | |
var_dump($context->canCreate('SpamMail')); // false | |
$context = new SecurityContext('Someone'); | |
var_dump($context->isAdmin()); // false | |
var_dump($context->canCreate('BlogPost')); // false |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment