|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914 |
- <?php
-
-
- namespace yii\rbac;
-
- use Yii;
- use yii\caching\Cache;
- use yii\db\Connection;
- use yii\db\Query;
- use yii\db\Expression;
- use yii\base\InvalidCallException;
- use yii\base\InvalidParamException;
- use yii\di\Instance;
-
-
- class DbManager extends BaseManager
- {
-
-
- public $db = 'db';
-
-
- public $itemTable = '{{%auth_item}}';
-
-
- public $itemChildTable = '{{%auth_item_child}}';
-
-
- public $assignmentTable = '{{%auth_assignment}}';
-
-
- public $ruleTable = '{{%auth_rule}}';
-
-
- public $cache;
-
-
- public $cacheKey = 'rbac';
-
-
- protected $items;
-
-
- protected $rules;
-
-
- protected $parents;
-
-
-
- public function init()
- {
- parent::init();
- $this->db = Instance::ensure($this->db, Connection::className());
- if ($this->cache !== null) {
- $this->cache = Instance::ensure($this->cache, Cache::className());
- }
- }
-
-
-
- public function checkAccess($userId, $permissionName, $params = [])
- {
- $assignments = $this->getAssignments($userId);
- $this->loadFromCache();
- if ($this->items !== null) {
- return $this->checkAccessFromCache($userId, $permissionName, $params, $assignments);
- } else {
- return $this->checkAccessRecursive($userId, $permissionName, $params, $assignments);
- }
- }
-
-
-
- protected function checkAccessFromCache($user, $itemName, $params, $assignments)
- {
- if (!isset($this->items[$itemName])) {
- return false;
- }
-
- $item = $this->items[$itemName];
-
- Yii::trace($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;
- }
-
- if (!empty($this->parents[$itemName])) {
- foreach ($this->parents[$itemName] as $parent) {
- if ($this->checkAccessRecursive($user, $parent, $params, $assignments)) {
- return true;
- }
- }
- }
-
- return false;
- }
-
-
-
- protected function checkAccessRecursive($user, $itemName, $params, $assignments)
- {
- if (($item = $this->getItem($itemName)) === null) {
- return false;
- }
-
- Yii::trace($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;
- }
-
- $query = new Query;
- $parents = $query->select(['parent'])
- ->from($this->itemChildTable)
- ->where(['child' => $itemName])
- ->column($this->db);
- foreach ($parents as $parent) {
- if ($this->checkAccessRecursive($user, $parent, $params, $assignments)) {
- return true;
- }
- }
-
- return false;
- }
-
-
-
- protected function getItem($name)
- {
- if (!empty($this->items[$name])) {
- return $this->items[$name];
- }
-
- $row = (new Query)->from($this->itemTable)
- ->where(['name' => $name])
- ->one($this->db);
-
- if ($row === false) {
- return null;
- }
-
- if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
- $row['data'] = null;
- }
-
- return $this->populateItem($row);
- }
-
-
-
- protected function supportsCascadeUpdate()
- {
- return strncmp($this->db->getDriverName(), 'sqlite', 6) !== 0;
- }
-
-
-
- protected function addItem($item)
- {
- $time = time();
- if ($item->createdAt === null) {
- $item->createdAt = $time;
- }
- if ($item->updatedAt === null) {
- $item->updatedAt = $time;
- }
- $this->db->createCommand()
- ->insert($this->itemTable, [
- 'name' => $item->name,
- 'type' => $item->type,
- 'description' => $item->description,
- 'rule_name' => $item->ruleName,
- 'data' => $item->data === null ? null : serialize($item->data),
- 'created_at' => $item->createdAt,
- 'updated_at' => $item->updatedAt,
- ])->execute();
-
- $this->invalidateCache();
-
- return true;
- }
-
-
-
- protected function removeItem($item)
- {
- if (!$this->supportsCascadeUpdate()) {
- $this->db->createCommand()
- ->delete($this->itemChildTable, ['or', '[[parent]]=:name', '[[child]]=:name'], [':name' => $item->name])
- ->execute();
- $this->db->createCommand()
- ->delete($this->assignmentTable, ['item_name' => $item->name])
- ->execute();
- }
-
- $this->db->createCommand()
- ->delete($this->itemTable, ['name' => $item->name])
- ->execute();
-
- $this->invalidateCache();
-
- return true;
- }
-
-
-
- protected function updateItem($name, $item)
- {
- if ($item->name !== $name && !$this->supportsCascadeUpdate()) {
- $this->db->createCommand()
- ->update($this->itemChildTable, ['parent' => $item->name], ['parent' => $name])
- ->execute();
- $this->db->createCommand()
- ->update($this->itemChildTable, ['child' => $item->name], ['child' => $name])
- ->execute();
- $this->db->createCommand()
- ->update($this->assignmentTable, ['item_name' => $item->name], ['item_name' => $name])
- ->execute();
- }
-
- $item->updatedAt = time();
-
- $this->db->createCommand()
- ->update($this->itemTable, [
- 'name' => $item->name,
- 'description' => $item->description,
- 'rule_name' => $item->ruleName,
- 'data' => $item->data === null ? null : serialize($item->data),
- 'updated_at' => $item->updatedAt,
- ], [
- 'name' => $name,
- ])->execute();
-
- $this->invalidateCache();
-
- return true;
- }
-
-
-
- protected function addRule($rule)
- {
- $time = time();
- if ($rule->createdAt === null) {
- $rule->createdAt = $time;
- }
- if ($rule->updatedAt === null) {
- $rule->updatedAt = $time;
- }
- $this->db->createCommand()
- ->insert($this->ruleTable, [
- 'name' => $rule->name,
- 'data' => serialize($rule),
- 'created_at' => $rule->createdAt,
- 'updated_at' => $rule->updatedAt,
- ])->execute();
-
- $this->invalidateCache();
-
- return true;
- }
-
-
-
- protected function updateRule($name, $rule)
- {
- if ($rule->name !== $name && !$this->supportsCascadeUpdate()) {
- $this->db->createCommand()
- ->update($this->itemTable, ['rule_name' => $rule->name], ['rule_name' => $name])
- ->execute();
- }
-
- $rule->updatedAt = time();
-
- $this->db->createCommand()
- ->update($this->ruleTable, [
- 'name' => $rule->name,
- 'data' => serialize($rule),
- 'updated_at' => $rule->updatedAt,
- ], [
- 'name' => $name,
- ])->execute();
-
- $this->invalidateCache();
-
- return true;
- }
-
-
-
- protected function removeRule($rule)
- {
- if (!$this->supportsCascadeUpdate()) {
- $this->db->createCommand()
- ->update($this->itemTable, ['rule_name' => null], ['rule_name' => $rule->name])
- ->execute();
- }
-
- $this->db->createCommand()
- ->delete($this->ruleTable, ['name' => $rule->name])
- ->execute();
-
- $this->invalidateCache();
-
- return true;
- }
-
-
-
- protected function getItems($type)
- {
- $query = (new Query)
- ->from($this->itemTable)
- ->where(['type' => $type]);
-
- $items = [];
- foreach ($query->all($this->db) as $row) {
- $items[$row['name']] = $this->populateItem($row);
- }
-
- return $items;
- }
-
-
-
- protected function populateItem($row)
- {
- $class = $row['type'] == Item::TYPE_PERMISSION ? Permission::className() : Role::className();
-
- if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
- $data = null;
- }
-
- return new $class([
- 'name' => $row['name'],
- 'type' => $row['type'],
- 'description' => $row['description'],
- 'ruleName' => $row['rule_name'],
- 'data' => $data,
- 'createdAt' => $row['created_at'],
- 'updatedAt' => $row['updated_at'],
- ]);
- }
-
-
-
- public function getRolesByUser($userId)
- {
- if (empty($userId)) {
- return [];
- }
-
- $query = (new Query)->select('b.*')
- ->from(['a' => $this->assignmentTable, 'b' => $this->itemTable])
- ->where('{{a}}.[[item_name]]={{b}}.[[name]]')
- ->andWhere(['a.user_id' => (string) $userId]);
-
- $roles = [];
- foreach ($query->all($this->db) as $row) {
- $roles[$row['name']] = $this->populateItem($row);
- }
- return $roles;
- }
-
-
-
- public function getPermissionsByRole($roleName)
- {
- $childrenList = $this->getChildrenList();
- $result = [];
- $this->getChildrenRecursive($roleName, $childrenList, $result);
- if (empty($result)) {
- return [];
- }
- $query = (new Query)->from($this->itemTable)->where([
- 'type' => Item::TYPE_PERMISSION,
- 'name' => array_keys($result),
- ]);
- $permissions = [];
- foreach ($query->all($this->db) as $row) {
- $permissions[$row['name']] = $this->populateItem($row);
- }
- return $permissions;
- }
-
-
-
- public function getPermissionsByUser($userId)
- {
- if (empty($userId)) {
- return [];
- }
-
- $query = (new Query)->select('item_name')
- ->from($this->assignmentTable)
- ->where(['user_id' => (string) $userId]);
-
- $childrenList = $this->getChildrenList();
- $result = [];
- foreach ($query->column($this->db) as $roleName) {
- $this->getChildrenRecursive($roleName, $childrenList, $result);
- }
-
- if (empty($result)) {
- return [];
- }
-
- $query = (new Query)->from($this->itemTable)->where([
- 'type' => Item::TYPE_PERMISSION,
- 'name' => array_keys($result),
- ]);
- $permissions = [];
- foreach ($query->all($this->db) as $row) {
- $permissions[$row['name']] = $this->populateItem($row);
- }
- return $permissions;
- }
-
-
-
- protected function getChildrenList()
- {
- $query = (new Query)->from($this->itemChildTable);
- $parents = [];
- foreach ($query->all($this->db) as $row) {
- $parents[$row['parent']][] = $row['child'];
- }
- return $parents;
- }
-
-
-
- protected function getChildrenRecursive($name, $childrenList, &$result)
- {
- if (isset($childrenList[$name])) {
- foreach ($childrenList[$name] as $child) {
- $result[$child] = true;
- $this->getChildrenRecursive($child, $childrenList, $result);
- }
- }
- }
-
-
-
- public function getRule($name)
- {
- if ($this->rules !== null) {
- return isset($this->rules[$name]) ? $this->rules[$name] : null;
- }
-
- $row = (new Query)->select(['data'])
- ->from($this->ruleTable)
- ->where(['name' => $name])
- ->one($this->db);
- return $row === false ? null : unserialize($row['data']);
- }
-
-
-
- public function getRules()
- {
- if ($this->rules !== null) {
- return $this->rules;
- }
-
- $query = (new Query)->from($this->ruleTable);
-
- $rules = [];
- foreach ($query->all($this->db) as $row) {
- $rules[$row['name']] = unserialize($row['data']);
- }
-
- return $rules;
- }
-
-
-
- public function getAssignment($roleName, $userId)
- {
- if (empty($userId)) {
- return null;
- }
-
- $row = (new Query)->from($this->assignmentTable)
- ->where(['user_id' => (string) $userId, 'item_name' => $roleName])
- ->one($this->db);
-
- if ($row === false) {
- return null;
- }
-
- return new Assignment([
- 'userId' => $row['user_id'],
- 'roleName' => $row['item_name'],
- 'createdAt' => $row['created_at'],
- ]);
- }
-
-
-
- public function getAssignments($userId)
- {
- if (empty($userId)) {
- return [];
- }
-
- $query = (new Query)
- ->from($this->assignmentTable)
- ->where(['user_id' => (string) $userId]);
-
- $assignments = [];
- foreach ($query->all($this->db) as $row) {
- $assignments[$row['item_name']] = new Assignment([
- 'userId' => $row['user_id'],
- 'roleName' => $row['item_name'],
- 'createdAt' => $row['created_at'],
- ]);
- }
-
- return $assignments;
- }
-
-
-
- public function addChild($parent, $child)
- {
- if ($parent->name === $child->name) {
- throw new InvalidParamException("Cannot add '{$parent->name}' as a child of itself.");
- }
-
- if ($parent instanceof Permission && $child instanceof Role) {
- throw new InvalidParamException("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.");
- }
-
- $this->db->createCommand()
- ->insert($this->itemChildTable, ['parent' => $parent->name, 'child' => $child->name])
- ->execute();
-
- $this->invalidateCache();
-
- return true;
- }
-
-
-
- public function removeChild($parent, $child)
- {
- $result = $this->db->createCommand()
- ->delete($this->itemChildTable, ['parent' => $parent->name, 'child' => $child->name])
- ->execute() > 0;
-
- $this->invalidateCache();
-
- return $result;
- }
-
-
-
- public function removeChildren($parent)
- {
- $result = $this->db->createCommand()
- ->delete($this->itemChildTable, ['parent' => $parent->name])
- ->execute() > 0;
-
- $this->invalidateCache();
-
- return $result;
- }
-
-
-
- public function hasChild($parent, $child)
- {
- return (new Query)
- ->from($this->itemChildTable)
- ->where(['parent' => $parent->name, 'child' => $child->name])
- ->one($this->db) !== false;
- }
-
-
-
- public function getChildren($name)
- {
- $query = (new Query)
- ->select(['name', 'type', 'description', 'rule_name', 'data', 'created_at', 'updated_at'])
- ->from([$this->itemTable, $this->itemChildTable])
- ->where(['parent' => $name, 'name' => new Expression('[[child]]')]);
-
- $children = [];
- foreach ($query->all($this->db) as $row) {
- $children[$row['name']] = $this->populateItem($row);
- }
-
- return $children;
- }
-
-
-
- protected function detectLoop($parent, $child)
- {
- if ($child->name === $parent->name) {
- return true;
- }
- foreach ($this->getChildren($child->name) as $grandchild) {
- if ($this->detectLoop($parent, $grandchild)) {
- return true;
- }
- }
- return false;
- }
-
-
-
- public function assign($role, $userId)
- {
- $assignment = new Assignment([
- 'userId' => $userId,
- 'roleName' => $role->name,
- 'createdAt' => time(),
- ]);
-
- $this->db->createCommand()
- ->insert($this->assignmentTable, [
- 'user_id' => $assignment->userId,
- 'item_name' => $assignment->roleName,
- 'created_at' => $assignment->createdAt,
- ])->execute();
-
- return $assignment;
- }
-
-
-
- public function revoke($role, $userId)
- {
- if (empty($userId)) {
- return false;
- }
-
- return $this->db->createCommand()
- ->delete($this->assignmentTable, ['user_id' => (string) $userId, 'item_name' => $role->name])
- ->execute() > 0;
- }
-
-
-
- public function revokeAll($userId)
- {
- if (empty($userId)) {
- return false;
- }
-
- return $this->db->createCommand()
- ->delete($this->assignmentTable, ['user_id' => (string) $userId])
- ->execute() > 0;
- }
-
-
-
- public function removeAll()
- {
- $this->removeAllAssignments();
- $this->db->createCommand()->delete($this->itemChildTable)->execute();
- $this->db->createCommand()->delete($this->itemTable)->execute();
- $this->db->createCommand()->delete($this->ruleTable)->execute();
- $this->invalidateCache();
- }
-
-
-
- public function removeAllPermissions()
- {
- $this->removeAllItems(Item::TYPE_PERMISSION);
- }
-
-
-
- public function removeAllRoles()
- {
- $this->removeAllItems(Item::TYPE_ROLE);
- }
-
-
-
- protected function removeAllItems($type)
- {
- if (!$this->supportsCascadeUpdate()) {
- $names = (new Query)
- ->select(['name'])
- ->from($this->itemTable)
- ->where(['type' => $type])
- ->column($this->db);
- if (empty($names)) {
- return;
- }
- $key = $type == Item::TYPE_PERMISSION ? 'child' : 'parent';
- $this->db->createCommand()
- ->delete($this->itemChildTable, [$key => $names])
- ->execute();
- $this->db->createCommand()
- ->delete($this->assignmentTable, ['item_name' => $names])
- ->execute();
- }
- $this->db->createCommand()
- ->delete($this->itemTable, ['type' => $type])
- ->execute();
-
- $this->invalidateCache();
- }
-
-
-
- public function removeAllRules()
- {
- if (!$this->supportsCascadeUpdate()) {
- $this->db->createCommand()
- ->update($this->itemTable, ['ruleName' => null])
- ->execute();
- }
-
- $this->db->createCommand()->delete($this->ruleTable)->execute();
-
- $this->invalidateCache();
- }
-
-
-
- public function removeAllAssignments()
- {
- $this->db->createCommand()->delete($this->assignmentTable)->execute();
- }
-
- public function invalidateCache()
- {
- if ($this->cache !== null) {
- $this->cache->delete($this->cacheKey);
- $this->items = null;
- $this->rules = null;
- $this->parents = null;
- }
- }
-
- public function loadFromCache()
- {
- if ($this->items !== null || !$this->cache instanceof Cache) {
- return;
- }
-
- $data = $this->cache->get($this->cacheKey);
- if (is_array($data) && isset($data[0], $data[1], $data[2])) {
- list ($this->items, $this->rules, $this->parents) = $data;
- return;
- }
-
- $query = (new Query)->from($this->itemTable);
- $this->items = [];
- foreach ($query->all($this->db) as $row) {
- $this->items[$row['name']] = $this->populateItem($row);
- }
-
- $query = (new Query)->from($this->ruleTable);
- $this->rules = [];
- foreach ($query->all($this->db) as $row) {
- $this->rules[$row['name']] = unserialize($row['data']);
- }
-
- $query = (new Query)->from($this->itemChildTable);
- $this->parents = [];
- foreach ($query->all($this->db) as $row) {
- if (isset($this->items[$row['child']])) {
- $this->parents[$row['child']][] = $row['parent'];
- }
- }
-
- $this->cache->set($this->cacheKey, [$this->items, $this->rules, $this->parents]);
- }
- }
|