|
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006 |
- <?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->checkAccessFromCache($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($name)) {
- return null;
- }
-
- 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 (!isset($userId) || $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])
- ->andWhere(['b.type' => Item::TYPE_ROLE]);
-
- $roles = [];
- foreach ($query->all($this->db) as $row) {
- $roles[$row['name']] = $this->populateItem($row);
- }
- return $roles;
- }
-
-
-
- public function getChildRoles($roleName)
- {
- $role = $this->getRole($roleName);
-
- if (is_null($role)) {
- throw new InvalidParamException("Role \"$roleName\" not found.");
- }
-
-
- $this->getChildrenRecursive($roleName, $this->getChildrenList(), $result);
-
- $roles = [$roleName => $role];
-
- $roles += array_filter($this->getRoles(), function (Role $roleItem) use ($result) {
- return array_key_exists($roleItem->name, $result);
- });
-
- 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 [];
- }
-
- $directPermission = $this->getDirectPermissionsByUser($userId);
- $inheritedPermission = $this->getInheritedPermissionsByUser($userId);
-
- return array_merge($directPermission, $inheritedPermission);
- }
-
-
-
- protected function getDirectPermissionsByUser($userId)
- {
- $query = (new Query)->select('b.*')
- ->from(['a' => $this->assignmentTable, 'b' => $this->itemTable])
- ->where('{{a}}.[[item_name]]={{b}}.[[name]]')
- ->andWhere(['a.user_id' => (string) $userId])
- ->andWhere(['b.type' => Item::TYPE_PERMISSION]);
-
- $permissions = [];
- foreach ($query->all($this->db) as $row) {
- $permissions[$row['name']] = $this->populateItem($row);
- }
- return $permissions;
- }
-
-
-
- protected function getInheritedPermissionsByUser($userId)
- {
- $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 canAddChild($parent, $child)
- {
- return !$this->detectLoop($parent, $child);
- }
-
-
-
- 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, ['rule_name' => 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]);
- }
-
-
-
- public function getUserIdsByRole($roleName)
- {
- if (empty($roleName)) {
- return [];
- }
-
- return (new Query)->select('[[user_id]]')
- ->from($this->assignmentTable)
- ->where(['item_name' => $roleName])->column($this->db);
- }
- }
|