This commit is contained in:
2020-02-01 16:47:12 +07:00
commit 4c619ad6e6
16739 changed files with 3329179 additions and 0 deletions

36
vendor/yiisoft/yii2/rbac/Assignment.php vendored Normal file
View File

@@ -0,0 +1,36 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rbac;
use Yii;
use yii\base\BaseObject;
/**
* Assignment represents an assignment of a role to a user.
*
* For more details and usage information on Assignment, see the [guide article on security authorization](guide:security-authorization).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com>
* @since 2.0
*/
class Assignment extends BaseObject
{
/**
* @var string|int user ID (see [[\yii\web\User::id]])
*/
public $userId;
/**
* @var string the role name
*/
public $roleName;
/**
* @var int UNIX timestamp representing the assignment creation time
*/
public $createdAt;
}

293
vendor/yiisoft/yii2/rbac/BaseManager.php vendored Normal file
View File

@@ -0,0 +1,293 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rbac;
use yii\base\Component;
use yii\base\InvalidArgumentException;
use yii\base\InvalidConfigException;
use yii\base\InvalidValueException;
/**
* BaseManager is a base class implementing [[ManagerInterface]] for RBAC management.
*
* For more details and usage information on DbManager, see the [guide article on security authorization](guide:security-authorization).
*
* @property Role[] $defaultRoleInstances Default roles. The array is indexed by the role names. This property
* is read-only.
* @property string[] $defaultRoles Default roles. Note that the type of this property differs in getter and
* setter. See [[getDefaultRoles()]] and [[setDefaultRoles()]] for details.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
abstract class BaseManager extends Component implements ManagerInterface
{
/**
* @var array a list of role names that are assigned to every user automatically without calling [[assign()]].
* Note that these roles are applied to users, regardless of their state of authentication.
*/
protected $defaultRoles = [];
/**
* Returns the named auth item.
* @param string $name the auth item name.
* @return Item the auth item corresponding to the specified name. Null is returned if no such item.
*/
abstract protected function getItem($name);
/**
* Returns the items of the specified type.
* @param int $type the auth item type (either [[Item::TYPE_ROLE]] or [[Item::TYPE_PERMISSION]]
* @return Item[] the auth items of the specified type.
*/
abstract protected function getItems($type);
/**
* Adds an auth item to the RBAC system.
* @param Item $item the item to add
* @return bool whether the auth item is successfully added to the system
* @throws \Exception if data validation or saving fails (such as the name of the role or permission is not unique)
*/
abstract protected function addItem($item);
/**
* Adds a rule to the RBAC system.
* @param Rule $rule the rule to add
* @return bool whether the rule is successfully added to the system
* @throws \Exception if data validation or saving fails (such as the name of the rule is not unique)
*/
abstract protected function addRule($rule);
/**
* Removes an auth item from the RBAC system.
* @param Item $item the item to remove
* @return bool whether the role or permission is successfully removed
* @throws \Exception if data validation or saving fails (such as the name of the role or permission is not unique)
*/
abstract protected function removeItem($item);
/**
* Removes a rule from the RBAC system.
* @param Rule $rule the rule to remove
* @return bool whether the rule is successfully removed
* @throws \Exception if data validation or saving fails (such as the name of the rule is not unique)
*/
abstract protected function removeRule($rule);
/**
* Updates an auth item in the RBAC system.
* @param string $name the name of the item being updated
* @param Item $item the updated item
* @return bool whether the auth item is successfully updated
* @throws \Exception if data validation or saving fails (such as the name of the role or permission is not unique)
*/
abstract protected function updateItem($name, $item);
/**
* Updates a rule to the RBAC system.
* @param string $name the name of the rule being updated
* @param Rule $rule the updated rule
* @return bool whether the rule is successfully updated
* @throws \Exception if data validation or saving fails (such as the name of the rule is not unique)
*/
abstract protected function updateRule($name, $rule);
/**
* {@inheritdoc}
*/
public function createRole($name)
{
$role = new Role();
$role->name = $name;
return $role;
}
/**
* {@inheritdoc}
*/
public function createPermission($name)
{
$permission = new Permission();
$permission->name = $name;
return $permission;
}
/**
* {@inheritdoc}
*/
public function add($object)
{
if ($object instanceof Item) {
if ($object->ruleName && $this->getRule($object->ruleName) === null) {
$rule = \Yii::createObject($object->ruleName);
$rule->name = $object->ruleName;
$this->addRule($rule);
}
return $this->addItem($object);
} elseif ($object instanceof Rule) {
return $this->addRule($object);
}
throw new InvalidArgumentException('Adding unsupported object type.');
}
/**
* {@inheritdoc}
*/
public function remove($object)
{
if ($object instanceof Item) {
return $this->removeItem($object);
} elseif ($object instanceof Rule) {
return $this->removeRule($object);
}
throw new InvalidArgumentException('Removing unsupported object type.');
}
/**
* {@inheritdoc}
*/
public function update($name, $object)
{
if ($object instanceof Item) {
if ($object->ruleName && $this->getRule($object->ruleName) === null) {
$rule = \Yii::createObject($object->ruleName);
$rule->name = $object->ruleName;
$this->addRule($rule);
}
return $this->updateItem($name, $object);
} elseif ($object instanceof Rule) {
return $this->updateRule($name, $object);
}
throw new InvalidArgumentException('Updating unsupported object type.');
}
/**
* {@inheritdoc}
*/
public function getRole($name)
{
$item = $this->getItem($name);
return $item instanceof Item && $item->type == Item::TYPE_ROLE ? $item : null;
}
/**
* {@inheritdoc}
*/
public function getPermission($name)
{
$item = $this->getItem($name);
return $item instanceof Item && $item->type == Item::TYPE_PERMISSION ? $item : null;
}
/**
* {@inheritdoc}
*/
public function getRoles()
{
return $this->getItems(Item::TYPE_ROLE);
}
/**
* Set default roles
* @param string[]|\Closure $roles either array of roles or a callable returning it
* @throws InvalidArgumentException when $roles is neither array nor Closure
* @throws InvalidValueException when Closure return is not an array
* @since 2.0.14
*/
public function setDefaultRoles($roles)
{
if (is_array($roles)) {
$this->defaultRoles = $roles;
} elseif ($roles instanceof \Closure) {
$roles = call_user_func($roles);
if (!is_array($roles)) {
throw new InvalidValueException('Default roles closure must return an array');
}
$this->defaultRoles = $roles;
} else {
throw new InvalidArgumentException('Default roles must be either an array or a callable');
}
}
/**
* Get default roles
* @return string[] default roles
* @since 2.0.14
*/
public function getDefaultRoles()
{
return $this->defaultRoles;
}
/**
* Returns defaultRoles as array of Role objects.
* @since 2.0.12
* @return Role[] default roles. The array is indexed by the role names
*/
public function getDefaultRoleInstances()
{
$result = [];
foreach ($this->defaultRoles as $roleName) {
$result[$roleName] = $this->createRole($roleName);
}
return $result;
}
/**
* {@inheritdoc}
*/
public function getPermissions()
{
return $this->getItems(Item::TYPE_PERMISSION);
}
/**
* Executes the rule associated with the specified auth item.
*
* If the item does not specify a rule, this method will return true. Otherwise, it will
* return the value of [[Rule::execute()]].
*
* @param string|int $user the user ID. This should be either an integer or a string representing
* the unique identifier of a user. See [[\yii\web\User::id]].
* @param Item $item the auth item that needs to execute its rule
* @param array $params parameters passed to [[CheckAccessInterface::checkAccess()]] and will be passed to the rule
* @return bool the return value of [[Rule::execute()]]. If the auth item does not specify a rule, true will be returned.
* @throws InvalidConfigException if the auth item has an invalid rule.
*/
protected function executeRule($user, $item, $params)
{
if ($item->ruleName === null) {
return true;
}
$rule = $this->getRule($item->ruleName);
if ($rule instanceof Rule) {
return $rule->execute($user, $item, $params);
}
throw new InvalidConfigException("Rule not found: {$item->ruleName}");
}
/**
* Checks whether array of $assignments is empty and [[defaultRoles]] property is empty as well.
*
* @param Assignment[] $assignments array of user's assignments
* @return bool whether array of $assignments is empty and [[defaultRoles]] property is empty as well
* @since 2.0.11
*/
protected function hasNoAssignments(array $assignments)
{
return empty($assignments) && empty($this->defaultRoles);
}
}

View File

@@ -0,0 +1,29 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rbac;
/**
* For more details and usage information on CheckAccessInterface, see the [guide article on security authorization](guide:security-authorization).
*
* @author Sam Mousa <sam@mousa.nl>
* @since 2.0.9
*/
interface CheckAccessInterface
{
/**
* Checks if the user has the specified permission.
* @param string|int $userId the user ID. This should be either an integer or a string representing
* the unique identifier of a user. See [[\yii\web\User::id]].
* @param string $permissionName the name of the permission to be checked against
* @param array $params name-value pairs that will be passed to the rules associated
* with the roles and permissions assigned to the user.
* @return bool whether the user has the specified permission.
* @throws \yii\base\InvalidParamException if $permissionName does not refer to an existing permission
*/
public function checkAccess($userId, $permissionName, $params = []);
}

1054
vendor/yiisoft/yii2/rbac/DbManager.php vendored Normal file

File diff suppressed because it is too large Load Diff

51
vendor/yiisoft/yii2/rbac/Item.php vendored Normal file
View File

@@ -0,0 +1,51 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rbac;
use yii\base\BaseObject;
/**
* For more details and usage information on Item, see the [guide article on security authorization](guide:security-authorization).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Item extends BaseObject
{
const TYPE_ROLE = 1;
const TYPE_PERMISSION = 2;
/**
* @var int the type of the item. This should be either [[TYPE_ROLE]] or [[TYPE_PERMISSION]].
*/
public $type;
/**
* @var string the name of the item. This must be globally unique.
*/
public $name;
/**
* @var string the item description
*/
public $description;
/**
* @var string name of the rule associated with this item
*/
public $ruleName;
/**
* @var mixed the additional data associated with this item
*/
public $data;
/**
* @var int UNIX timestamp representing the item creation time
*/
public $createdAt;
/**
* @var int UNIX timestamp representing the item updating time
*/
public $updatedAt;
}

View File

@@ -0,0 +1,259 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rbac;
/**
* For more details and usage information on ManagerInterface, see the [guide article on security authorization](guide:security-authorization).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
interface ManagerInterface extends CheckAccessInterface
{
/**
* Creates a new Role object.
* Note that the newly created role is not added to the RBAC system yet.
* You must fill in the needed data and call [[add()]] to add it to the system.
* @param string $name the role name
* @return Role the new Role object
*/
public function createRole($name);
/**
* Creates a new Permission object.
* Note that the newly created permission is not added to the RBAC system yet.
* You must fill in the needed data and call [[add()]] to add it to the system.
* @param string $name the permission name
* @return Permission the new Permission object
*/
public function createPermission($name);
/**
* Adds a role, permission or rule to the RBAC system.
* @param Role|Permission|Rule $object
* @return bool whether the role, permission or rule is successfully added to the system
* @throws \Exception if data validation or saving fails (such as the name of the role or permission is not unique)
*/
public function add($object);
/**
* Removes a role, permission or rule from the RBAC system.
* @param Role|Permission|Rule $object
* @return bool whether the role, permission or rule is successfully removed
*/
public function remove($object);
/**
* Updates the specified role, permission or rule in the system.
* @param string $name the old name of the role, permission or rule
* @param Role|Permission|Rule $object
* @return bool whether the update is successful
* @throws \Exception if data validation or saving fails (such as the name of the role or permission is not unique)
*/
public function update($name, $object);
/**
* Returns the named role.
* @param string $name the role name.
* @return null|Role the role corresponding to the specified name. Null is returned if no such role.
*/
public function getRole($name);
/**
* Returns all roles in the system.
* @return Role[] all roles in the system. The array is indexed by the role names.
*/
public function getRoles();
/**
* Returns the roles that are assigned to the user via [[assign()]].
* Note that child roles that are not assigned directly to the user will not be returned.
* @param string|int $userId the user ID (see [[\yii\web\User::id]])
* @return Role[] all roles directly assigned to the user. The array is indexed by the role names.
*/
public function getRolesByUser($userId);
/**
* Returns child roles of the role specified. Depth isn't limited.
* @param string $roleName name of the role to file child roles for
* @return Role[] Child roles. The array is indexed by the role names.
* First element is an instance of the parent Role itself.
* @throws \yii\base\InvalidParamException if Role was not found that are getting by $roleName
* @since 2.0.10
*/
public function getChildRoles($roleName);
/**
* Returns the named permission.
* @param string $name the permission name.
* @return null|Permission the permission corresponding to the specified name. Null is returned if no such permission.
*/
public function getPermission($name);
/**
* Returns all permissions in the system.
* @return Permission[] all permissions in the system. The array is indexed by the permission names.
*/
public function getPermissions();
/**
* Returns all permissions that the specified role represents.
* @param string $roleName the role name
* @return Permission[] all permissions that the role represents. The array is indexed by the permission names.
*/
public function getPermissionsByRole($roleName);
/**
* Returns all permissions that the user has.
* @param string|int $userId the user ID (see [[\yii\web\User::id]])
* @return Permission[] all permissions that the user has. The array is indexed by the permission names.
*/
public function getPermissionsByUser($userId);
/**
* Returns the rule of the specified name.
* @param string $name the rule name
* @return null|Rule the rule object, or null if the specified name does not correspond to a rule.
*/
public function getRule($name);
/**
* Returns all rules available in the system.
* @return Rule[] the rules indexed by the rule names
*/
public function getRules();
/**
* Checks the possibility of adding a child to parent.
* @param Item $parent the parent item
* @param Item $child the child item to be added to the hierarchy
* @return bool possibility of adding
*
* @since 2.0.8
*/
public function canAddChild($parent, $child);
/**
* Adds an item as a child of another item.
* @param Item $parent
* @param Item $child
* @return bool whether the child successfully added
* @throws \yii\base\Exception if the parent-child relationship already exists or if a loop has been detected.
*/
public function addChild($parent, $child);
/**
* Removes a child from its parent.
* Note, the child item is not deleted. Only the parent-child relationship is removed.
* @param Item $parent
* @param Item $child
* @return bool whether the removal is successful
*/
public function removeChild($parent, $child);
/**
* Removed all children form their parent.
* Note, the children items are not deleted. Only the parent-child relationships are removed.
* @param Item $parent
* @return bool whether the removal is successful
*/
public function removeChildren($parent);
/**
* Returns a value indicating whether the child already exists for the parent.
* @param Item $parent
* @param Item $child
* @return bool whether `$child` is already a child of `$parent`
*/
public function hasChild($parent, $child);
/**
* Returns the child permissions and/or roles.
* @param string $name the parent name
* @return Item[] the child permissions and/or roles
*/
public function getChildren($name);
/**
* Assigns a role to a user.
*
* @param Role|Permission $role
* @param string|int $userId the user ID (see [[\yii\web\User::id]])
* @return Assignment the role assignment information.
* @throws \Exception if the role has already been assigned to the user
*/
public function assign($role, $userId);
/**
* Revokes a role from a user.
* @param Role|Permission $role
* @param string|int $userId the user ID (see [[\yii\web\User::id]])
* @return bool whether the revoking is successful
*/
public function revoke($role, $userId);
/**
* Revokes all roles from a user.
* @param mixed $userId the user ID (see [[\yii\web\User::id]])
* @return bool whether the revoking is successful
*/
public function revokeAll($userId);
/**
* Returns the assignment information regarding a role and a user.
* @param string $roleName the role name
* @param string|int $userId the user ID (see [[\yii\web\User::id]])
* @return null|Assignment the assignment information. Null is returned if
* the role is not assigned to the user.
*/
public function getAssignment($roleName, $userId);
/**
* Returns all role assignment information for the specified user.
* @param string|int $userId the user ID (see [[\yii\web\User::id]])
* @return Assignment[] the assignments indexed by role names. An empty array will be
* returned if there is no role assigned to the user.
*/
public function getAssignments($userId);
/**
* Returns all user IDs assigned to the role specified.
* @param string $roleName
* @return array array of user ID strings
* @since 2.0.7
*/
public function getUserIdsByRole($roleName);
/**
* Removes all authorization data, including roles, permissions, rules, and assignments.
*/
public function removeAll();
/**
* Removes all permissions.
* All parent child relations will be adjusted accordingly.
*/
public function removeAllPermissions();
/**
* Removes all roles.
* All parent child relations will be adjusted accordingly.
*/
public function removeAllRoles();
/**
* Removes all rules.
* All roles and permissions which have rules will be adjusted accordingly.
*/
public function removeAllRules();
/**
* Removes all role assignments.
*/
public function removeAllAssignments();
}

22
vendor/yiisoft/yii2/rbac/Permission.php vendored Normal file
View File

@@ -0,0 +1,22 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rbac;
/**
* For more details and usage information on Permission, see the [guide article on security authorization](guide:security-authorization).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Permission extends Item
{
/**
* {@inheritdoc}
*/
public $type = self::TYPE_PERMISSION;
}

888
vendor/yiisoft/yii2/rbac/PhpManager.php vendored Normal file
View File

@@ -0,0 +1,888 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rbac;
use Yii;
use yii\base\InvalidArgumentException;
use yii\base\InvalidCallException;
use yii\helpers\VarDumper;
/**
* PhpManager represents an authorization manager that stores authorization
* information in terms of a PHP script file.
*
* The authorization data will be saved to and loaded from three files
* specified by [[itemFile]], [[assignmentFile]] and [[ruleFile]].
*
* PhpManager is mainly suitable for authorization data that is not too big
* (for example, the authorization data for a personal blog system).
* Use [[DbManager]] for more complex authorization data.
*
* Note that PhpManager is not compatible with facebooks [HHVM](http://hhvm.com/) because
* it relies on writing php files and including them afterwards which is not supported by HHVM.
*
* For more details and usage information on PhpManager, see the [guide article on security authorization](guide:security-authorization).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com>
* @author Christophe Boulain <christophe.boulain@gmail.com>
* @author Alexander Makarov <sam@rmcreative.ru>
* @since 2.0
*/
class PhpManager extends BaseManager
{
/**
* @var string the path of the PHP script that contains the authorization items.
* This can be either a file path or a [path alias](guide:concept-aliases) to the file.
* Make sure this file is writable by the Web server process if the authorization needs to be changed online.
* @see loadFromFile()
* @see saveToFile()
*/
public $itemFile = '@app/rbac/items.php';
/**
* @var string the path of the PHP script that contains the authorization assignments.
* This can be either a file path or a [path alias](guide:concept-aliases) to the file.
* Make sure this file is writable by the Web server process if the authorization needs to be changed online.
* @see loadFromFile()
* @see saveToFile()
*/
public $assignmentFile = '@app/rbac/assignments.php';
/**
* @var string the path of the PHP script that contains the authorization rules.
* This can be either a file path or a [path alias](guide:concept-aliases) to the file.
* Make sure this file is writable by the Web server process if the authorization needs to be changed online.
* @see loadFromFile()
* @see saveToFile()
*/
public $ruleFile = '@app/rbac/rules.php';
/**
* @var Item[]
*/
protected $items = []; // itemName => item
/**
* @var array
*/
protected $children = []; // itemName, childName => child
/**
* @var array
*/
protected $assignments = []; // userId, itemName => assignment
/**
* @var Rule[]
*/
protected $rules = []; // ruleName => rule
/**
* Initializes the application component.
* This method overrides parent implementation by loading the authorization data
* from PHP script.
*/
public function init()
{
parent::init();
$this->itemFile = Yii::getAlias($this->itemFile);
$this->assignmentFile = Yii::getAlias($this->assignmentFile);
$this->ruleFile = Yii::getAlias($this->ruleFile);
$this->load();
}
/**
* {@inheritdoc}
*/
public function checkAccess($userId, $permissionName, $params = [])
{
$assignments = $this->getAssignments($userId);
if ($this->hasNoAssignments($assignments)) {
return false;
}
return $this->checkAccessRecursive($userId, $permissionName, $params, $assignments);
}
/**
* {@inheritdoc}
*/
public function getAssignments($userId)
{
return isset($this->assignments[$userId]) ? $this->assignments[$userId] : [];
}
/**
* Performs access check for the specified user.
* This method is internally called by [[checkAccess()]].
*
* @param string|int $user the user ID. This should can be either an integer or a string representing
* the unique identifier of a user. See [[\yii\web\User::id]].
* @param string $itemName the name of the operation that need access check
* @param array $params name-value pairs that would be passed to rules associated
* with the tasks and roles assigned to the user. A param with name 'user' is added to this array,
* which holds the value of `$userId`.
* @param Assignment[] $assignments the assignments to the specified user
* @return bool whether the operations can be performed by the user.
*/
protected function checkAccessRecursive($user, $itemName, $params, $assignments)
{
if (!isset($this->items[$itemName])) {
return false;
}
/* @var $item Item */
$item = $this->items[$itemName];
Yii::debug($item instanceof Role ? "Checking role: $itemName" : "Checking permission : $itemName", __METHOD__);
if (!$this->executeRule($user, $item, $params)) {
return false;
}
if (isset($assignments[$itemName]) || in_array($itemName, $this->defaultRoles)) {
return true;
}
foreach ($this->children as $parentName => $children) {
if (isset($children[$itemName]) && $this->checkAccessRecursive($user, $parentName, $params, $assignments)) {
return true;
}
}
return false;
}
/**
* {@inheritdoc}
* @since 2.0.8
*/
public function canAddChild($parent, $child)
{
return !$this->detectLoop($parent, $child);
}
/**
* {@inheritdoc}
*/
public function addChild($parent, $child)
{
if (!isset($this->items[$parent->name], $this->items[$child->name])) {
throw new InvalidArgumentException("Either '{$parent->name}' or '{$child->name}' does not exist.");
}
if ($parent->name === $child->name) {
throw new InvalidArgumentException("Cannot add '{$parent->name} ' as a child of itself.");
}
if ($parent instanceof Permission && $child instanceof Role) {
throw new InvalidArgumentException('Cannot add a role as a child of a permission.');
}
if ($this->detectLoop($parent, $child)) {
throw new InvalidCallException("Cannot add '{$child->name}' as a child of '{$parent->name}'. A loop has been detected.");
}
if (isset($this->children[$parent->name][$child->name])) {
throw new InvalidCallException("The item '{$parent->name}' already has a child '{$child->name}'.");
}
$this->children[$parent->name][$child->name] = $this->items[$child->name];
$this->saveItems();
return true;
}
/**
* Checks whether there is a loop in the authorization item hierarchy.
*
* @param Item $parent parent item
* @param Item $child the child item that is to be added to the hierarchy
* @return bool whether a loop exists
*/
protected function detectLoop($parent, $child)
{
if ($child->name === $parent->name) {
return true;
}
if (!isset($this->children[$child->name], $this->items[$parent->name])) {
return false;
}
foreach ($this->children[$child->name] as $grandchild) {
/* @var $grandchild Item */
if ($this->detectLoop($parent, $grandchild)) {
return true;
}
}
return false;
}
/**
* {@inheritdoc}
*/
public function removeChild($parent, $child)
{
if (isset($this->children[$parent->name][$child->name])) {
unset($this->children[$parent->name][$child->name]);
$this->saveItems();
return true;
}
return false;
}
/**
* {@inheritdoc}
*/
public function removeChildren($parent)
{
if (isset($this->children[$parent->name])) {
unset($this->children[$parent->name]);
$this->saveItems();
return true;
}
return false;
}
/**
* {@inheritdoc}
*/
public function hasChild($parent, $child)
{
return isset($this->children[$parent->name][$child->name]);
}
/**
* {@inheritdoc}
*/
public function assign($role, $userId)
{
if (!isset($this->items[$role->name])) {
throw new InvalidArgumentException("Unknown role '{$role->name}'.");
} elseif (isset($this->assignments[$userId][$role->name])) {
throw new InvalidArgumentException("Authorization item '{$role->name}' has already been assigned to user '$userId'.");
}
$this->assignments[$userId][$role->name] = new Assignment([
'userId' => $userId,
'roleName' => $role->name,
'createdAt' => time(),
]);
$this->saveAssignments();
return $this->assignments[$userId][$role->name];
}
/**
* {@inheritdoc}
*/
public function revoke($role, $userId)
{
if (isset($this->assignments[$userId][$role->name])) {
unset($this->assignments[$userId][$role->name]);
$this->saveAssignments();
return true;
}
return false;
}
/**
* {@inheritdoc}
*/
public function revokeAll($userId)
{
if (isset($this->assignments[$userId]) && is_array($this->assignments[$userId])) {
foreach ($this->assignments[$userId] as $itemName => $value) {
unset($this->assignments[$userId][$itemName]);
}
$this->saveAssignments();
return true;
}
return false;
}
/**
* {@inheritdoc}
*/
public function getAssignment($roleName, $userId)
{
return isset($this->assignments[$userId][$roleName]) ? $this->assignments[$userId][$roleName] : null;
}
/**
* {@inheritdoc}
*/
public function getItems($type)
{
$items = [];
foreach ($this->items as $name => $item) {
/* @var $item Item */
if ($item->type == $type) {
$items[$name] = $item;
}
}
return $items;
}
/**
* {@inheritdoc}
*/
public function removeItem($item)
{
if (isset($this->items[$item->name])) {
foreach ($this->children as &$children) {
unset($children[$item->name]);
}
foreach ($this->assignments as &$assignments) {
unset($assignments[$item->name]);
}
unset($this->items[$item->name]);
$this->saveItems();
$this->saveAssignments();
return true;
}
return false;
}
/**
* {@inheritdoc}
*/
public function getItem($name)
{
return isset($this->items[$name]) ? $this->items[$name] : null;
}
/**
* {@inheritdoc}
*/
public function updateRule($name, $rule)
{
if ($rule->name !== $name) {
unset($this->rules[$name]);
}
$this->rules[$rule->name] = $rule;
$this->saveRules();
return true;
}
/**
* {@inheritdoc}
*/
public function getRule($name)
{
return isset($this->rules[$name]) ? $this->rules[$name] : null;
}
/**
* {@inheritdoc}
*/
public function getRules()
{
return $this->rules;
}
/**
* {@inheritdoc}
* The roles returned by this method include the roles assigned via [[$defaultRoles]].
*/
public function getRolesByUser($userId)
{
$roles = $this->getDefaultRoleInstances();
foreach ($this->getAssignments($userId) as $name => $assignment) {
$role = $this->items[$assignment->roleName];
if ($role->type === Item::TYPE_ROLE) {
$roles[$name] = $role;
}
}
return $roles;
}
/**
* {@inheritdoc}
*/
public function getChildRoles($roleName)
{
$role = $this->getRole($roleName);
if ($role === null) {
throw new InvalidArgumentException("Role \"$roleName\" not found.");
}
$result = [];
$this->getChildrenRecursive($roleName, $result);
$roles = [$roleName => $role];
$roles += array_filter($this->getRoles(), function (Role $roleItem) use ($result) {
return array_key_exists($roleItem->name, $result);
});
return $roles;
}
/**
* {@inheritdoc}
*/
public function getPermissionsByRole($roleName)
{
$result = [];
$this->getChildrenRecursive($roleName, $result);
if (empty($result)) {
return [];
}
$permissions = [];
foreach (array_keys($result) as $itemName) {
if (isset($this->items[$itemName]) && $this->items[$itemName] instanceof Permission) {
$permissions[$itemName] = $this->items[$itemName];
}
}
return $permissions;
}
/**
* Recursively finds all children and grand children of the specified item.
*
* @param string $name the name of the item whose children are to be looked for.
* @param array $result the children and grand children (in array keys)
*/
protected function getChildrenRecursive($name, &$result)
{
if (isset($this->children[$name])) {
foreach ($this->children[$name] as $child) {
$result[$child->name] = true;
$this->getChildrenRecursive($child->name, $result);
}
}
}
/**
* {@inheritdoc}
*/
public function getPermissionsByUser($userId)
{
$directPermission = $this->getDirectPermissionsByUser($userId);
$inheritedPermission = $this->getInheritedPermissionsByUser($userId);
return array_merge($directPermission, $inheritedPermission);
}
/**
* Returns all permissions that are directly assigned to user.
* @param string|int $userId the user ID (see [[\yii\web\User::id]])
* @return Permission[] all direct permissions that the user has. The array is indexed by the permission names.
* @since 2.0.7
*/
protected function getDirectPermissionsByUser($userId)
{
$permissions = [];
foreach ($this->getAssignments($userId) as $name => $assignment) {
$permission = $this->items[$assignment->roleName];
if ($permission->type === Item::TYPE_PERMISSION) {
$permissions[$name] = $permission;
}
}
return $permissions;
}
/**
* Returns all permissions that the user inherits from the roles assigned to him.
* @param string|int $userId the user ID (see [[\yii\web\User::id]])
* @return Permission[] all inherited permissions that the user has. The array is indexed by the permission names.
* @since 2.0.7
*/
protected function getInheritedPermissionsByUser($userId)
{
$assignments = $this->getAssignments($userId);
$result = [];
foreach (array_keys($assignments) as $roleName) {
$this->getChildrenRecursive($roleName, $result);
}
if (empty($result)) {
return [];
}
$permissions = [];
foreach (array_keys($result) as $itemName) {
if (isset($this->items[$itemName]) && $this->items[$itemName] instanceof Permission) {
$permissions[$itemName] = $this->items[$itemName];
}
}
return $permissions;
}
/**
* {@inheritdoc}
*/
public function getChildren($name)
{
return isset($this->children[$name]) ? $this->children[$name] : [];
}
/**
* {@inheritdoc}
*/
public function removeAll()
{
$this->children = [];
$this->items = [];
$this->assignments = [];
$this->rules = [];
$this->save();
}
/**
* {@inheritdoc}
*/
public function removeAllPermissions()
{
$this->removeAllItems(Item::TYPE_PERMISSION);
}
/**
* {@inheritdoc}
*/
public function removeAllRoles()
{
$this->removeAllItems(Item::TYPE_ROLE);
}
/**
* Removes all auth items of the specified type.
* @param int $type the auth item type (either Item::TYPE_PERMISSION or Item::TYPE_ROLE)
*/
protected function removeAllItems($type)
{
$names = [];
foreach ($this->items as $name => $item) {
if ($item->type == $type) {
unset($this->items[$name]);
$names[$name] = true;
}
}
if (empty($names)) {
return;
}
foreach ($this->assignments as $i => $assignments) {
foreach ($assignments as $n => $assignment) {
if (isset($names[$assignment->roleName])) {
unset($this->assignments[$i][$n]);
}
}
}
foreach ($this->children as $name => $children) {
if (isset($names[$name])) {
unset($this->children[$name]);
} else {
foreach ($children as $childName => $item) {
if (isset($names[$childName])) {
unset($children[$childName]);
}
}
$this->children[$name] = $children;
}
}
$this->saveItems();
}
/**
* {@inheritdoc}
*/
public function removeAllRules()
{
foreach ($this->items as $item) {
$item->ruleName = null;
}
$this->rules = [];
$this->saveRules();
}
/**
* {@inheritdoc}
*/
public function removeAllAssignments()
{
$this->assignments = [];
$this->saveAssignments();
}
/**
* {@inheritdoc}
*/
protected function removeRule($rule)
{
if (isset($this->rules[$rule->name])) {
unset($this->rules[$rule->name]);
foreach ($this->items as $item) {
if ($item->ruleName === $rule->name) {
$item->ruleName = null;
}
}
$this->saveRules();
return true;
}
return false;
}
/**
* {@inheritdoc}
*/
protected function addRule($rule)
{
$this->rules[$rule->name] = $rule;
$this->saveRules();
return true;
}
/**
* {@inheritdoc}
*/
protected function updateItem($name, $item)
{
if ($name !== $item->name) {
if (isset($this->items[$item->name])) {
throw new InvalidArgumentException("Unable to change the item name. The name '{$item->name}' is already used by another item.");
}
// Remove old item in case of renaming
unset($this->items[$name]);
if (isset($this->children[$name])) {
$this->children[$item->name] = $this->children[$name];
unset($this->children[$name]);
}
foreach ($this->children as &$children) {
if (isset($children[$name])) {
$children[$item->name] = $children[$name];
unset($children[$name]);
}
}
foreach ($this->assignments as &$assignments) {
if (isset($assignments[$name])) {
$assignments[$item->name] = $assignments[$name];
$assignments[$item->name]->roleName = $item->name;
unset($assignments[$name]);
}
}
$this->saveAssignments();
}
$this->items[$item->name] = $item;
$this->saveItems();
return true;
}
/**
* {@inheritdoc}
*/
protected function addItem($item)
{
$time = time();
if ($item->createdAt === null) {
$item->createdAt = $time;
}
if ($item->updatedAt === null) {
$item->updatedAt = $time;
}
$this->items[$item->name] = $item;
$this->saveItems();
return true;
}
/**
* Loads authorization data from persistent storage.
*/
protected function load()
{
$this->children = [];
$this->rules = [];
$this->assignments = [];
$this->items = [];
$items = $this->loadFromFile($this->itemFile);
$itemsMtime = @filemtime($this->itemFile);
$assignments = $this->loadFromFile($this->assignmentFile);
$assignmentsMtime = @filemtime($this->assignmentFile);
$rules = $this->loadFromFile($this->ruleFile);
foreach ($items as $name => $item) {
$class = $item['type'] == Item::TYPE_PERMISSION ? Permission::className() : Role::className();
$this->items[$name] = new $class([
'name' => $name,
'description' => isset($item['description']) ? $item['description'] : null,
'ruleName' => isset($item['ruleName']) ? $item['ruleName'] : null,
'data' => isset($item['data']) ? $item['data'] : null,
'createdAt' => $itemsMtime,
'updatedAt' => $itemsMtime,
]);
}
foreach ($items as $name => $item) {
if (isset($item['children'])) {
foreach ($item['children'] as $childName) {
if (isset($this->items[$childName])) {
$this->children[$name][$childName] = $this->items[$childName];
}
}
}
}
foreach ($assignments as $userId => $roles) {
foreach ($roles as $role) {
$this->assignments[$userId][$role] = new Assignment([
'userId' => $userId,
'roleName' => $role,
'createdAt' => $assignmentsMtime,
]);
}
}
foreach ($rules as $name => $ruleData) {
$this->rules[$name] = unserialize($ruleData);
}
}
/**
* Saves authorization data into persistent storage.
*/
protected function save()
{
$this->saveItems();
$this->saveAssignments();
$this->saveRules();
}
/**
* Loads the authorization data from a PHP script file.
*
* @param string $file the file path.
* @return array the authorization data
* @see saveToFile()
*/
protected function loadFromFile($file)
{
if (is_file($file)) {
return require $file;
}
return [];
}
/**
* Saves the authorization data to a PHP script file.
*
* @param array $data the authorization data
* @param string $file the file path.
* @see loadFromFile()
*/
protected function saveToFile($data, $file)
{
file_put_contents($file, "<?php\nreturn " . VarDumper::export($data) . ";\n", LOCK_EX);
$this->invalidateScriptCache($file);
}
/**
* Invalidates precompiled script cache (such as OPCache or APC) for the given file.
* @param string $file the file path.
* @since 2.0.9
*/
protected function invalidateScriptCache($file)
{
if (function_exists('opcache_invalidate')) {
opcache_invalidate($file, true);
}
if (function_exists('apc_delete_file')) {
@apc_delete_file($file);
}
}
/**
* Saves items data into persistent storage.
*/
protected function saveItems()
{
$items = [];
foreach ($this->items as $name => $item) {
/* @var $item Item */
$items[$name] = array_filter(
[
'type' => $item->type,
'description' => $item->description,
'ruleName' => $item->ruleName,
'data' => $item->data,
]
);
if (isset($this->children[$name])) {
foreach ($this->children[$name] as $child) {
/* @var $child Item */
$items[$name]['children'][] = $child->name;
}
}
}
$this->saveToFile($items, $this->itemFile);
}
/**
* Saves assignments data into persistent storage.
*/
protected function saveAssignments()
{
$assignmentData = [];
foreach ($this->assignments as $userId => $assignments) {
foreach ($assignments as $name => $assignment) {
/* @var $assignment Assignment */
$assignmentData[$userId][] = $assignment->roleName;
}
}
$this->saveToFile($assignmentData, $this->assignmentFile);
}
/**
* Saves rules data into persistent storage.
*/
protected function saveRules()
{
$rules = [];
foreach ($this->rules as $name => $rule) {
$rules[$name] = serialize($rule);
}
$this->saveToFile($rules, $this->ruleFile);
}
/**
* {@inheritdoc}
* @since 2.0.7
*/
public function getUserIdsByRole($roleName)
{
$result = [];
foreach ($this->assignments as $userID => $assignments) {
foreach ($assignments as $userAssignment) {
if ($userAssignment->roleName === $roleName && $userAssignment->userId == $userID) {
$result[] = (string) $userID;
}
}
}
return $result;
}
}

22
vendor/yiisoft/yii2/rbac/Role.php vendored Normal file
View File

@@ -0,0 +1,22 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rbac;
/**
* For more details and usage information on Role, see the [guide article on security authorization](guide:security-authorization).
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Role extends Item
{
/**
* {@inheritdoc}
*/
public $type = self::TYPE_ROLE;
}

46
vendor/yiisoft/yii2/rbac/Rule.php vendored Normal file
View File

@@ -0,0 +1,46 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rbac;
use yii\base\BaseObject;
/**
* Rule represents a business constraint that may be associated with a role, permission or assignment.
*
* For more details and usage information on Rule, see the [guide article on security authorization](guide:security-authorization).
*
* @author Alexander Makarov <sam@rmcreative.ru>
* @since 2.0
*/
abstract class Rule extends BaseObject
{
/**
* @var string name of the rule
*/
public $name;
/**
* @var int UNIX timestamp representing the rule creation time
*/
public $createdAt;
/**
* @var int UNIX timestamp representing the rule updating time
*/
public $updatedAt;
/**
* Executes the rule.
*
* @param string|int $user the user ID. This should be either an integer or a string representing
* the unique identifier of a user. See [[\yii\web\User::id]].
* @param Item $item the role or permission that this rule is associated with
* @param array $params parameters passed to [[CheckAccessInterface::checkAccess()]].
* @return bool a value indicating whether the rule permits the auth item it is associated with.
*/
abstract public function execute($user, $item, $params);
}

View File

@@ -0,0 +1,169 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
use yii\base\InvalidConfigException;
use yii\rbac\DbManager;
/**
* Initializes RBAC tables.
*
* @author Alexander Kochetov <creocoder@gmail.com>
* @since 2.0
*/
class m140506_102106_rbac_init extends \yii\db\Migration
{
/**
* @throws yii\base\InvalidConfigException
* @return DbManager
*/
protected function getAuthManager()
{
$authManager = Yii::$app->getAuthManager();
if (!$authManager instanceof DbManager) {
throw new InvalidConfigException('You should configure "authManager" component to use database before executing this migration.');
}
return $authManager;
}
/**
* @return bool
*/
protected function isMSSQL()
{
return $this->db->driverName === 'mssql' || $this->db->driverName === 'sqlsrv' || $this->db->driverName === 'dblib';
}
protected function isOracle()
{
return $this->db->driverName === 'oci';
}
/**
* {@inheritdoc}
*/
public function up()
{
$authManager = $this->getAuthManager();
$this->db = $authManager->db;
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
// http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
}
$this->createTable($authManager->ruleTable, [
'name' => $this->string(64)->notNull(),
'data' => $this->binary(),
'created_at' => $this->integer(),
'updated_at' => $this->integer(),
'PRIMARY KEY ([[name]])',
], $tableOptions);
$this->createTable($authManager->itemTable, [
'name' => $this->string(64)->notNull(),
'type' => $this->smallInteger()->notNull(),
'description' => $this->text(),
'rule_name' => $this->string(64),
'data' => $this->binary(),
'created_at' => $this->integer(),
'updated_at' => $this->integer(),
'PRIMARY KEY ([[name]])',
'FOREIGN KEY ([[rule_name]]) REFERENCES ' . $authManager->ruleTable . ' ([[name]])' .
$this->buildFkClause('ON DELETE SET NULL', 'ON UPDATE CASCADE'),
], $tableOptions);
$this->createIndex('idx-auth_item-type', $authManager->itemTable, 'type');
$this->createTable($authManager->itemChildTable, [
'parent' => $this->string(64)->notNull(),
'child' => $this->string(64)->notNull(),
'PRIMARY KEY ([[parent]], [[child]])',
'FOREIGN KEY ([[parent]]) REFERENCES ' . $authManager->itemTable . ' ([[name]])' .
$this->buildFkClause('ON DELETE CASCADE', 'ON UPDATE CASCADE'),
'FOREIGN KEY ([[child]]) REFERENCES ' . $authManager->itemTable . ' ([[name]])' .
$this->buildFkClause('ON DELETE CASCADE', 'ON UPDATE CASCADE'),
], $tableOptions);
$this->createTable($authManager->assignmentTable, [
'item_name' => $this->string(64)->notNull(),
'user_id' => $this->string(64)->notNull(),
'created_at' => $this->integer(),
'PRIMARY KEY ([[item_name]], [[user_id]])',
'FOREIGN KEY ([[item_name]]) REFERENCES ' . $authManager->itemTable . ' ([[name]])' .
$this->buildFkClause('ON DELETE CASCADE', 'ON UPDATE CASCADE'),
], $tableOptions);
if ($this->isMSSQL()) {
$this->execute("CREATE TRIGGER dbo.trigger_auth_item_child
ON dbo.{$authManager->itemTable}
INSTEAD OF DELETE, UPDATE
AS
DECLARE @old_name VARCHAR (64) = (SELECT name FROM deleted)
DECLARE @new_name VARCHAR (64) = (SELECT name FROM inserted)
BEGIN
IF COLUMNS_UPDATED() > 0
BEGIN
IF @old_name <> @new_name
BEGIN
ALTER TABLE {$authManager->itemChildTable} NOCHECK CONSTRAINT FK__auth_item__child;
UPDATE {$authManager->itemChildTable} SET child = @new_name WHERE child = @old_name;
END
UPDATE {$authManager->itemTable}
SET name = (SELECT name FROM inserted),
type = (SELECT type FROM inserted),
description = (SELECT description FROM inserted),
rule_name = (SELECT rule_name FROM inserted),
data = (SELECT data FROM inserted),
created_at = (SELECT created_at FROM inserted),
updated_at = (SELECT updated_at FROM inserted)
WHERE name IN (SELECT name FROM deleted)
IF @old_name <> @new_name
BEGIN
ALTER TABLE {$authManager->itemChildTable} CHECK CONSTRAINT FK__auth_item__child;
END
END
ELSE
BEGIN
DELETE FROM dbo.{$authManager->itemChildTable} WHERE parent IN (SELECT name FROM deleted) OR child IN (SELECT name FROM deleted);
DELETE FROM dbo.{$authManager->itemTable} WHERE name IN (SELECT name FROM deleted);
END
END;");
}
}
/**
* {@inheritdoc}
*/
public function down()
{
$authManager = $this->getAuthManager();
$this->db = $authManager->db;
if ($this->isMSSQL()) {
$this->execute('DROP TRIGGER dbo.trigger_auth_item_child;');
}
$this->dropTable($authManager->assignmentTable);
$this->dropTable($authManager->itemChildTable);
$this->dropTable($authManager->itemTable);
$this->dropTable($authManager->ruleTable);
}
protected function buildFkClause($delete = '', $update = '')
{
if ($this->isMSSQL()) {
return '';
}
if ($this->isOracle()) {
return ' ' . $delete;
}
return implode(' ', ['', $delete, $update]);
}
}

View File

@@ -0,0 +1,56 @@
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
use yii\base\InvalidConfigException;
use yii\db\Migration;
use yii\rbac\DbManager;
/**
* Adds index on `user_id` column in `auth_assignment` table for performance reasons.
*
* @see https://github.com/yiisoft/yii2/pull/14765
*
* @author Ivan Buttinoni <ivan.buttinoni@cibi.it>
* @since 2.0.13
*/
class m170907_052038_rbac_add_index_on_auth_assignment_user_id extends Migration
{
public $column = 'user_id';
public $index = 'auth_assignment_user_id_idx';
/**
* @throws yii\base\InvalidConfigException
* @return DbManager
*/
protected function getAuthManager()
{
$authManager = Yii::$app->getAuthManager();
if (!$authManager instanceof DbManager) {
throw new InvalidConfigException('You should configure "authManager" component to use database before executing this migration.');
}
return $authManager;
}
/**
* {@inheritdoc}
*/
public function up()
{
$authManager = $this->getAuthManager();
$this->createIndex($this->index, $authManager->assignmentTable, $this->column);
}
/**
* {@inheritdoc}
*/
public function down()
{
$authManager = $this->getAuthManager();
$this->dropIndex($this->index, $authManager->assignmentTable);
}
}

View File

@@ -0,0 +1,101 @@
/**
* Database schema required by \yii\rbac\DbManager.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com>
* @link http://www.yiiframework.com/
* @copyright 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @since 2.0
*/
if object_id('[auth_assignment]', 'U') is not null
drop table [auth_assignment];
if object_id('[auth_item_child]', 'U') is not null
drop table [auth_item_child];
if object_id('[auth_item]', 'U') is not null
drop table [auth_item];
if object_id('[auth_rule]', 'U') is not null
drop table [auth_rule];
create table [auth_rule]
(
[name] varchar(64) not null,
[data] blob,
[created_at] integer,
[updated_at] integer,
primary key ([name])
);
create table [auth_item]
(
[name] varchar(64) not null,
[type] smallint not null,
[description] text,
[rule_name] varchar(64),
[data] blob,
[created_at] integer,
[updated_at] integer,
primary key ([name]),
foreign key ([rule_name]) references [auth_rule] ([name])
);
create index [idx-auth_item-type] on [auth_item] ([type]);
create table [auth_item_child]
(
[parent] varchar(64) not null,
[child] varchar(64) not null,
primary key ([parent],[child]),
foreign key ([parent]) references [auth_item] ([name]),
foreign key ([child]) references [auth_item] ([name])
);
create table [auth_assignment]
(
[item_name] varchar(64) not null,
[user_id] varchar(64) not null,
[created_at] integer,
primary key ([item_name], [user_id]),
foreign key ([item_name]) references [auth_item] ([name]) on delete cascade on update cascade
);
create index [auth_assignment_user_id_idx] on [auth_assignment] ([user_id]);
CREATE TRIGGER dbo.trigger_auth_item_child
ON dbo.[auth_item]
INSTEAD OF DELETE, UPDATE
AS
DECLARE @old_name VARCHAR (64) = (SELECT name FROM deleted)
DECLARE @new_name VARCHAR (64) = (SELECT name FROM inserted)
BEGIN
IF COLUMNS_UPDATED() > 0
BEGIN
IF @old_name <> @new_name
BEGIN
ALTER TABLE auth_item_child NOCHECK CONSTRAINT FK__auth_item__child;
UPDATE auth_item_child SET child = @new_name WHERE child = @old_name;
END
UPDATE auth_item
SET name = (SELECT name FROM inserted),
type = (SELECT type FROM inserted),
description = (SELECT description FROM inserted),
rule_name = (SELECT rule_name FROM inserted),
data = (SELECT data FROM inserted),
created_at = (SELECT created_at FROM inserted),
updated_at = (SELECT updated_at FROM inserted)
WHERE name IN (SELECT name FROM deleted)
IF @old_name <> @new_name
BEGIN
ALTER TABLE auth_item_child CHECK CONSTRAINT FK__auth_item__child;
END
END
ELSE
BEGIN
DELETE FROM dbo.[auth_item_child] WHERE parent IN (SELECT name FROM deleted) OR child IN (SELECT name FROM deleted);
DELETE FROM dbo.[auth_item] WHERE name IN (SELECT name FROM deleted);
END
END;

View File

@@ -0,0 +1,57 @@
/**
* Database schema required by \yii\rbac\DbManager.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com>
* @link http://www.yiiframework.com/
* @copyright 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @since 2.0
*/
drop table if exists `auth_assignment`;
drop table if exists `auth_item_child`;
drop table if exists `auth_item`;
drop table if exists `auth_rule`;
create table `auth_rule`
(
`name` varchar(64) not null,
`data` blob,
`created_at` integer,
`updated_at` integer,
primary key (`name`)
) engine InnoDB;
create table `auth_item`
(
`name` varchar(64) not null,
`type` smallint not null,
`description` text,
`rule_name` varchar(64),
`data` blob,
`created_at` integer,
`updated_at` integer,
primary key (`name`),
foreign key (`rule_name`) references `auth_rule` (`name`) on delete set null on update cascade,
key `type` (`type`)
) engine InnoDB;
create table `auth_item_child`
(
`parent` varchar(64) not null,
`child` varchar(64) not null,
primary key (`parent`, `child`),
foreign key (`parent`) references `auth_item` (`name`) on delete cascade on update cascade,
foreign key (`child`) references `auth_item` (`name`) on delete cascade on update cascade
) engine InnoDB;
create table `auth_assignment`
(
`item_name` varchar(64) not null,
`user_id` varchar(64) not null,
`created_at` integer,
primary key (`item_name`, `user_id`),
foreign key (`item_name`) references `auth_item` (`name`) on delete cascade on update cascade,
key `auth_assignment_user_id_idx` (`user_id`)
) engine InnoDB;

View File

@@ -0,0 +1,60 @@
/**
* Database schema required by \yii\rbac\DbManager.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com>
* @link http://www.yiiframework.com/
* @copyright 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @since 2.0
*/
drop table "auth_assignment";
drop table "auth_item_child";
drop table "auth_item";
drop table "auth_rule";
-- create new auth_rule table
create table "auth_rule"
(
"name" varchar(64) not null,
"data" BYTEA,
"created_at" integer,
"updated_at" integer,
primary key ("name")
);
-- create auth_item table
create table "auth_item"
(
"name" varchar(64) not null,
"type" smallint not null,
"description" varchar(1000),
"rule_name" varchar(64),
"data" BYTEA,
"updated_at" integer,
foreign key ("rule_name") references "auth_rule"("name") on delete set null,
primary key ("name")
);
-- adds oracle specific index to auth_item
CREATE INDEX auth_type_index ON "auth_item"("type");
create table "auth_item_child"
(
"parent" varchar(64) not null,
"child" varchar(64) not null,
primary key ("parent","child"),
foreign key ("parent") references "auth_item"("name") on delete cascade,
foreign key ("child") references "auth_item"("name") on delete cascade
);
create table "auth_assignment"
(
"item_name" varchar(64) not null,
"user_id" varchar(64) not null,
"created_at" integer,
primary key ("item_name","user_id"),
foreign key ("item_name") references "auth_item" ("name") on delete cascade
);
CREATE INDEX auth_assignment_user_id_idx ON "auth_assignment" ("user_id");

View File

@@ -0,0 +1,59 @@
/**
* Database schema required by \yii\rbac\DbManager.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com>
* @link http://www.yiiframework.com/
* @copyright 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @since 2.0
*/
drop table if exists "auth_assignment";
drop table if exists "auth_item_child";
drop table if exists "auth_item";
drop table if exists "auth_rule";
create table "auth_rule"
(
"name" varchar(64) not null,
"data" bytea,
"created_at" integer,
"updated_at" integer,
primary key ("name")
);
create table "auth_item"
(
"name" varchar(64) not null,
"type" smallint not null,
"description" text,
"rule_name" varchar(64),
"data" bytea,
"created_at" integer,
"updated_at" integer,
primary key ("name"),
foreign key ("rule_name") references "auth_rule" ("name") on delete set null on update cascade
);
create index auth_item_type_idx on "auth_item" ("type");
create table "auth_item_child"
(
"parent" varchar(64) not null,
"child" varchar(64) not null,
primary key ("parent","child"),
foreign key ("parent") references "auth_item" ("name") on delete cascade on update cascade,
foreign key ("child") references "auth_item" ("name") on delete cascade on update cascade
);
create table "auth_assignment"
(
"item_name" varchar(64) not null,
"user_id" varchar(64) not null,
"created_at" integer,
primary key ("item_name","user_id"),
foreign key ("item_name") references "auth_item" ("name") on delete cascade on update cascade
);
create index auth_assignment_user_id_idx on "auth_assignment" ("user_id");

View File

@@ -0,0 +1,59 @@
/**
* Database schema required by \yii\rbac\DbManager.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com>
* @link http://www.yiiframework.com/
* @copyright 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @since 2.0
*/
drop table if exists "auth_assignment";
drop table if exists "auth_item_child";
drop table if exists "auth_item";
drop table if exists "auth_rule";
create table "auth_rule"
(
"name" varchar(64) not null,
"data" blob,
"created_at" integer,
"updated_at" integer,
primary key ("name")
);
create table "auth_item"
(
"name" varchar(64) not null,
"type" smallint not null,
"description" text,
"rule_name" varchar(64),
"data" blob,
"created_at" integer,
"updated_at" integer,
primary key ("name"),
foreign key ("rule_name") references "auth_rule" ("name") on delete set null on update cascade
);
create index "auth_item_type_idx" on "auth_item" ("type");
create table "auth_item_child"
(
"parent" varchar(64) not null,
"child" varchar(64) not null,
primary key ("parent","child"),
foreign key ("parent") references "auth_item" ("name") on delete cascade on update cascade,
foreign key ("child") references "auth_item" ("name") on delete cascade on update cascade
);
create table "auth_assignment"
(
"item_name" varchar(64) not null,
"user_id" varchar(64) not null,
"created_at" integer,
primary key ("item_name","user_id"),
foreign key ("item_name") references "auth_item" ("name") on delete cascade on update cascade
);
create index "auth_assignment_user_id_idx" on "auth_assignment" ("user_id");