Skip to content

Instantly share code, notes, and snippets.

@juban
Last active January 4, 2016 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juban/8618419 to your computer and use it in GitHub Desktop.
Save juban/8618419 to your computer and use it in GitHub Desktop.
This class inherit from and is an enhancement for CDbAuthManager class from Yii Framework 1.1 which lower the number of database queries.
<?php
/**
* EFastDbAuthManager class file
*
* This class inherit from and is an enhancement for CDbAuthManager class which lower the number of database queries.
* The main difference with the original class is that the authorization data are loaded once for all in a very a similar way to CPhpAuthManager.
* In short terms, this is a kind of mix between CDbAuthManager and CPhpAuthManager classes to get the best of both worlds.
* The class can also be used to cache the authorization data to achieve an even faster loading.
*
* Yii 1.1.11 required
*
* @author juban
* @version 1.0.1
*/
/**
* EFastDbAuthManager represents an authorization manager that stores authorization information in database.
*
* The database connection is specified by {@link connectionID}. And the database schema
* should be as described in "framework/web/auth/*.sql". You may change the names of
* the three tables used to store the authorization data by setting {@link itemTable},
* {@link itemChildTable} and {@link assignmentTable}.
*
* @property array $authItems The authorization items of the specific type.
*/
class EFastDbAuthManager extends CDbAuthManager
{
private $_items = array(); // itemName => item
private $_children = array(); // itemName, childName => child
private $_assignments = array(); // userId, itemName => assignment
public $cacheID = 'cache';
public $cacheKeyPrefix = "Auth.EFastDbAuthManager.";
public $cachingDuration = 0;
/**
* Initializes the application component.
* This method overrides parent implementation by loading the authorization data
* from database.
*/
public function init()
{
parent::init();
$this->load();
}
/**
* Loads authorization data from database or from cache if activated.
*/
public function load()
{
$this->clearAll();
$items = false;
$children = false;
$cache = $this->getCache();
if ($cache) {
$items = $cache->get($this->cacheKeyPrefix . "AuthItems");
$children = $cache->get($this->cacheKeyPrefix . "AuthItemsChildren");
$assignments = $cache->get($this->cacheKeyPrefix . "AuthItemsAssignments");
}
if ($items === false || $children === false || $assignments == false) {
// Load auth items
$this->_items = parent::getAuthItems();
$this->loadChildren();
$this->loadAssignments();
if (!is_null($cache)) {
$dependency = new CGlobalStateCacheDependency('AuthManagerLastChange');
$cache->set($this->cacheKeyPrefix . "AuthItems", serialize($this->_items), $this->cachingDuration, $dependency);
$cache->set($this->cacheKeyPrefix . "AuthItemsChildren", serialize($this->_children), $this->cachingDuration, $dependency);
$cache->set($this->cacheKeyPrefix . "AuthItemsAssignments", serialize($this->_assignments), $this->cachingDuration, $dependency);
}
} else {
$this->_items = unserialize($items);
$this->_children = unserialize($children);
$this->_assignments = unserialize($assignments);
}
}
/*
* Load parent children relationships
*/
public function loadChildren()
{
$rows = $this->db->createCommand()
->select()
->from($this->itemChildTable)
->queryAll();
foreach ($rows as $row) {
if (isset($this->_items[$row['child']]))
$this->_children[$row['parent']][$row['child']] = $this->_items[$row['child']];
}
}
/*
* Load assignations data
*/
public function loadAssignments()
{
$rows = $this->db->createCommand()
->select()
->from($this->assignmentTable)
->queryAll();
foreach ($rows as $row) {
if (($data = @unserialize($row['data'])) === false)
$data = null;
$this->_assignments[$row['userid']][$row['itemname']] = new CAuthAssignment($this, $row['itemname'], $row['userid'], $row['bizrule'], $data);
}
}
/**
* Performs access check for the specified user.
* @param string $itemName the name of the operation that need access check
* @param mixed $userId the user ID. This can be either an integer or a string representing
* the unique identifier of a user. See {@link IWebUser::getId}.
* @param array $params name-value pairs that would be passed to biz rules associated
* with the tasks and roles assigned to the user.
* Since version 1.1.11 a param with name 'userId' is added to this array, which holds the value of <code>$userId</code>.
* @return boolean whether the operations can be performed by the user.
*/
public function checkAccess($itemName, $userId, $params = array())
{
if (!isset($this->_items[$itemName]))
return false;
$item = $this->_items[$itemName];
Yii::trace('Checking permission "' . $item->getName() . '"', 'system.web.auth.EFastDbAuthManager');
if (!isset($params['userId']))
$params['userId'] = $userId;
if ($this->executeBizRule($item->getBizRule(), $params, $item->getData())) {
if (in_array($itemName, $this->defaultRoles))
return true;
if (isset($this->_assignments[$userId][$itemName])) {
$assignment = $this->_assignments[$userId][$itemName];
if ($this->executeBizRule($assignment->getBizRule(), $params, $assignment->getData()))
return true;
}
foreach ($this->_children as $parentName => $children) {
if (isset($children[$itemName]) && $this->checkAccess($parentName, $userId, $params))
return true;
}
}
return false;
}
/**
* Removes all authorization data.
*/
public function clearAll()
{
$this->clearAuthAssignments();
$this->_children = array();
$this->_items = array();
}
/**
* Removes all authorization assignments.
*/
public function clearAuthAssignments()
{
$this->_assignments = array();
}
/**
* Returns the caching component for this component.
* @return CCache|null the caching component.
*/
protected function getCache()
{
return $this->cachingDuration > 0 && $this->cacheID !== false ? Yii::app()->getComponent($this->cacheID) : null;
}
/**
* Returns a value indicating whether a child exists within a parent.
* @param string $itemName the parent item name
* @param string $childName the child item name
* @return boolean whether the child exists
*/
public function hasItemChild($itemName, $childName)
{
return isset($this->_children[$itemName][$childName]);
}
/**
* Returns the children of the specified item.
* @param mixed $names the parent item name. This can be either a string or an array.
* The latter represents a list of item names.
* @return array all child items of the parent
*/
public function getItemChildren($names)
{
if (is_string($names))
return isset($this->_children[$names]) ? $this->_children[$names] : array();
$children = array();
foreach ($names as $name) {
if (isset($this->_children[$name]))
$children = array_merge($children, $this->_children[$name]);
}
return $children;
}
/*
* Set the AuthManagerLastChange global state to invalidate cached authorization data
*/
private function invalidateCache()
{
Yii::app()->setGlobalState('AuthManagerLastChange', microtime());
$this->load();
}
/**
* Adds an item as a child of another item and invalidate cache.
* @param string $itemName the parent item name
* @param string $childName the child item name
* @return boolean whether the item is added successfully
* @throws CException if either parent or child doesn't exist or if a loop has been detected.
*/
public function addItemChild($itemName, $childName)
{
parent::addItemChild($itemName, $childName);
$this->invalidateCache();
}
/**
* Returns a value indicating whether the item has been assigned to the user.
* @param string $itemName the item name
* @param mixed $userId the user ID (see {@link IWebUser::getId})
* @return boolean whether the item has been assigned to the user.
*/
public function isAssigned($itemName, $userId)
{
return isset($this->_assignments[$userId][$itemName]);
}
/**
* Returns the item assignment information.
* @param string $itemName the item name
* @param mixed $userId the user ID (see {@link IWebUser::getId})
* @return CAuthAssignment the item assignment information. Null is returned if
* the item is not assigned to the user.
*/
public function getAuthAssignment($itemName, $userId)
{
return isset($this->_assignments[$userId][$itemName]) ? $this->_assignments[$userId][$itemName] : null;
}
/**
* Returns the item assignments for the specified user.
* @param mixed $userId the user ID (see {@link IWebUser::getId})
* @return array the item assignment information for the user. An empty array will be
* returned if there is no item assigned to the user.
*/
public function getAuthAssignments($userId)
{
return isset($this->_assignments[$userId]) ? $this->_assignments[$userId] : array();
}
/**
* Returns the authorization items of the specific type and user.
* @param integer $type the item type (0: operation, 1: task, 2: role). Defaults to null,
* meaning returning all items regardless of their type.
* @param mixed $userId the user ID. Defaults to null, meaning returning all items even if
* they are not assigned to a user.
* @return array the authorization items of the specific type.
*/
public function getAuthItems($type = null, $userId = null)
{
if ($type === null && $userId === null)
return $this->_items;
$items = array();
if ($userId === null) {
foreach ($this->_items as $name => $item) {
if ($item->getType() == $type)
$items[$name] = $item;
}
}
elseif (isset($this->_assignments[$userId])) {
foreach ($this->_assignments[$userId] as $assignment) {
$name = $assignment->getItemName();
if (isset($this->_items[$name]) && ($type === null || $this->_items[$name]->getType() == $type))
$items[$name] = $this->_items[$name];
}
}
return $items;
}
/**
* Returns the authorization item with the specified name.
* @param string $name the name of the item
* @return CAuthItem the authorization item. Null if the item cannot be found.
*/
public function getAuthItem($name)
{
return isset($this->_items[$name]) ? $this->_items[$name] : null;
}
/**
* Creates an authorization item and invalidate cache.
* An authorization item represents an action permission (e.g. creating a post).
* It has three types: operation, task and role.
* Authorization items form a hierarchy. Higher level items inheirt permissions representing
* by lower level items.
* @param string $name the item name. This must be a unique identifier.
* @param integer $type the item type (0: operation, 1: task, 2: role).
* @param string $description description of the item
* @param string $bizRule business rule associated with the item. This is a piece of
* PHP code that will be executed when {@link checkAccess} is called for the item.
* @param mixed $data additional data associated with the item.
* @return CAuthItem the authorization item
* @throws CException if an item with the same name already exists
*/
public function createAuthItem($name, $type, $description = '', $bizRule = null, $data = null)
{
$authItem = parent::createAuthItem($name, $type, $description, $bizRule, $data);
$this->invalidateCache();
return $authItem;
}
/**
* Removes a child from its parent and invalidate cache.
* Note, the child item is not deleted. Only the parent-child relationship is removed.
* @param string $itemName the parent item name
* @param string $childName the child item name
* @return boolean whether the removal is successful
*/
public function removeItemChild($itemName, $childName)
{
$result = parent::removeItemChild($itemName, $childName);
$this->invalidateCache();
return $result;
}
/**
* Assigns an authorization item to a user and invalidate cache.
* @param string $itemName the item name
* @param mixed $userId the user ID (see {@link IWebUser::getId})
* @param string $bizRule the business rule to be executed when {@link checkAccess} is called
* for this particular authorization item.
* @param mixed $data additional data associated with this assignment
* @return CAuthAssignment the authorization assignment information.
* @throws CException if the item does not exist or if the item has already been assigned to the user
*/
public function assign($itemName, $userId, $bizRule = null, $data = null)
{
if (!isset($this->_items[$itemName]))
throw new CException(Yii::t('yii', 'Unknown authorization item "{name}".', array('{name}' => $itemName)));
elseif (isset($this->_assignments[$userId][$itemName]))
throw new CException(Yii::t('yii', 'Authorization item "{item}" has already been assigned to user "{user}".', array('{item}' => $itemName, '{user}' => $userId)));
else {
$result = parent::assign($itemName, $userId, $bizRule, $data);
$this->invalidateCache();
return $result;
}
}
/**
* Revokes an authorization assignment from a user and invalidate cache.
* @param string $itemName the item name
* @param mixed $userId the user ID (see {@link IWebUser::getId})
* @return boolean whether removal is successful
*/
public function revoke($itemName, $userId)
{
$result = parent::revoke($itemName, $userId);
$this->invalidateCache();
return $result;
}
/**
* Saves the authorization data to persistent storage and invalidate cache.
*/
public function save()
{
parent::save();
$this->invalidateCache();
}
/**
* Saves the changes to an authorization assignment and invalidate cache.
* @param CAuthAssignment $assignment the assignment that has been changed.
*/
public function saveAuthAssignment($assignment)
{
parent::saveAuthAssignment($assignment);
$this->invalidateCache();
}
/**
* Saves an authorization item to persistent storage and invalidate cache.
* @param CAuthItem $item the item to be saved.
* @param string $oldName the old item name. If null, it means the item name is not changed.
*/
public function saveAuthItem($item, $oldName = null)
{
if ($oldName !== null && ($newName = $item->getName()) !== $oldName) { // name changed
if (isset($this->_items[$newName]))
throw new CException(Yii::t('yii', 'Unable to change the item name. The name "{name}" is already used by another item.', array('{name}' => $newName)));
if (isset($this->_items[$oldName]) && $this->_items[$oldName] === $item) {
unset($this->_items[$oldName]);
$this->_items[$newName] = $item;
if (isset($this->_children[$oldName])) {
$this->_children[$newName] = $this->_children[$oldName];
unset($this->_children[$oldName]);
}
foreach ($this->_children as &$children) {
if (isset($children[$oldName])) {
$children[$newName] = $children[$oldName];
unset($children[$oldName]);
}
}
foreach ($this->_assignments as &$assignments) {
if (isset($assignments[$oldName])) {
$assignments[$newName] = $assignments[$oldName];
unset($assignments[$oldName]);
}
}
}
}
parent::saveAuthItem($item, $oldName);
$this->invalidateCache();
}
/**
* Removes the specified authorization item and invalidate cache.
* @param string $name the name of the item to be removed
* @return boolean whether the item exists in the storage and has been removed
*/
public function removeAuthItem($name)
{
$result = parent::removeAuthItem($name);
$this->invalidateCache();
return $result;
}
/**
* Removes all authorization assignments and invalidate cache.
*/
public function clearAuthAssignment()
{
parent::clearAuthAssignments();
$this->invalidateCache();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment