DbManager.php 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\rbac;
  8. use Yii;
  9. use yii\caching\Cache;
  10. use yii\db\Connection;
  11. use yii\db\Query;
  12. use yii\db\Expression;
  13. use yii\base\InvalidCallException;
  14. use yii\base\InvalidParamException;
  15. use yii\di\Instance;
  16. /**
  17. * DbManager represents an authorization manager that stores authorization information in database.
  18. *
  19. * The database connection is specified by [[db]]. The database schema could be initialized by applying migration:
  20. *
  21. * ```
  22. * yii migrate --migrationPath=@yii/rbac/migrations/
  23. * ```
  24. *
  25. * If you don't want to use migration and need SQL instead, files for all databases are in migrations directory.
  26. *
  27. * You may change the names of the tables used to store the authorization and rule data by setting [[itemTable]],
  28. * [[itemChildTable]], [[assignmentTable]] and [[ruleTable]].
  29. *
  30. * For more details and usage information on DbManager, see the [guide article on security authorization](guide:security-authorization).
  31. *
  32. * @author Qiang Xue <qiang.xue@gmail.com>
  33. * @author Alexander Kochetov <creocoder@gmail.com>
  34. * @since 2.0
  35. */
  36. class DbManager extends BaseManager
  37. {
  38. /**
  39. * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
  40. * After the DbManager object is created, if you want to change this property, you should only assign it
  41. * with a DB connection object.
  42. * Starting from version 2.0.2, this can also be a configuration array for creating the object.
  43. */
  44. public $db = 'db';
  45. /**
  46. * @var string the name of the table storing authorization items. Defaults to "auth_item".
  47. */
  48. public $itemTable = '{{%auth_item}}';
  49. /**
  50. * @var string the name of the table storing authorization item hierarchy. Defaults to "auth_item_child".
  51. */
  52. public $itemChildTable = '{{%auth_item_child}}';
  53. /**
  54. * @var string the name of the table storing authorization item assignments. Defaults to "auth_assignment".
  55. */
  56. public $assignmentTable = '{{%auth_assignment}}';
  57. /**
  58. * @var string the name of the table storing rules. Defaults to "auth_rule".
  59. */
  60. public $ruleTable = '{{%auth_rule}}';
  61. /**
  62. * @var Cache|array|string the cache used to improve RBAC performance. This can be one of the following:
  63. *
  64. * - an application component ID (e.g. `cache`)
  65. * - a configuration array
  66. * - a [[\yii\caching\Cache]] object
  67. *
  68. * When this is not set, it means caching is not enabled.
  69. *
  70. * Note that by enabling RBAC cache, all auth items, rules and auth item parent-child relationships will
  71. * be cached and loaded into memory. This will improve the performance of RBAC permission check. However,
  72. * it does require extra memory and as a result may not be appropriate if your RBAC system contains too many
  73. * auth items. You should seek other RBAC implementations (e.g. RBAC based on Redis storage) in this case.
  74. *
  75. * Also note that if you modify RBAC items, rules or parent-child relationships from outside of this component,
  76. * you have to manually call [[invalidateCache()]] to ensure data consistency.
  77. *
  78. * @since 2.0.3
  79. */
  80. public $cache;
  81. /**
  82. * @var string the key used to store RBAC data in cache
  83. * @see cache
  84. * @since 2.0.3
  85. */
  86. public $cacheKey = 'rbac';
  87. /**
  88. * @var Item[] all auth items (name => Item)
  89. */
  90. protected $items;
  91. /**
  92. * @var Rule[] all auth rules (name => Rule)
  93. */
  94. protected $rules;
  95. /**
  96. * @var array auth item parent-child relationships (childName => list of parents)
  97. */
  98. protected $parents;
  99. /**
  100. * Initializes the application component.
  101. * This method overrides the parent implementation by establishing the database connection.
  102. */
  103. public function init()
  104. {
  105. parent::init();
  106. $this->db = Instance::ensure($this->db, Connection::className());
  107. if ($this->cache !== null) {
  108. $this->cache = Instance::ensure($this->cache, Cache::className());
  109. }
  110. }
  111. /**
  112. * @inheritdoc
  113. */
  114. public function checkAccess($userId, $permissionName, $params = [])
  115. {
  116. $assignments = $this->getAssignments($userId);
  117. if ($this->hasNoAssignments($assignments)) {
  118. return false;
  119. }
  120. $this->loadFromCache();
  121. if ($this->items !== null) {
  122. return $this->checkAccessFromCache($userId, $permissionName, $params, $assignments);
  123. } else {
  124. return $this->checkAccessRecursive($userId, $permissionName, $params, $assignments);
  125. }
  126. }
  127. /**
  128. * Performs access check for the specified user based on the data loaded from cache.
  129. * This method is internally called by [[checkAccess()]] when [[cache]] is enabled.
  130. * @param string|int $user the user ID. This should can be either an integer or a string representing
  131. * the unique identifier of a user. See [[\yii\web\User::id]].
  132. * @param string $itemName the name of the operation that need access check
  133. * @param array $params name-value pairs that would be passed to rules associated
  134. * with the tasks and roles assigned to the user. A param with name 'user' is added to this array,
  135. * which holds the value of `$userId`.
  136. * @param Assignment[] $assignments the assignments to the specified user
  137. * @return bool whether the operations can be performed by the user.
  138. * @since 2.0.3
  139. */
  140. protected function checkAccessFromCache($user, $itemName, $params, $assignments)
  141. {
  142. if (!isset($this->items[$itemName])) {
  143. return false;
  144. }
  145. $item = $this->items[$itemName];
  146. Yii::trace($item instanceof Role ? "Checking role: $itemName" : "Checking permission: $itemName", __METHOD__);
  147. if (!$this->executeRule($user, $item, $params)) {
  148. return false;
  149. }
  150. if (isset($assignments[$itemName]) || in_array($itemName, $this->defaultRoles)) {
  151. return true;
  152. }
  153. if (!empty($this->parents[$itemName])) {
  154. foreach ($this->parents[$itemName] as $parent) {
  155. if ($this->checkAccessFromCache($user, $parent, $params, $assignments)) {
  156. return true;
  157. }
  158. }
  159. }
  160. return false;
  161. }
  162. /**
  163. * Performs access check for the specified user.
  164. * This method is internally called by [[checkAccess()]].
  165. * @param string|int $user the user ID. This should can be either an integer or a string representing
  166. * the unique identifier of a user. See [[\yii\web\User::id]].
  167. * @param string $itemName the name of the operation that need access check
  168. * @param array $params name-value pairs that would be passed to rules associated
  169. * with the tasks and roles assigned to the user. A param with name 'user' is added to this array,
  170. * which holds the value of `$userId`.
  171. * @param Assignment[] $assignments the assignments to the specified user
  172. * @return bool whether the operations can be performed by the user.
  173. */
  174. protected function checkAccessRecursive($user, $itemName, $params, $assignments)
  175. {
  176. if (($item = $this->getItem($itemName)) === null) {
  177. return false;
  178. }
  179. Yii::trace($item instanceof Role ? "Checking role: $itemName" : "Checking permission: $itemName", __METHOD__);
  180. if (!$this->executeRule($user, $item, $params)) {
  181. return false;
  182. }
  183. if (isset($assignments[$itemName]) || in_array($itemName, $this->defaultRoles)) {
  184. return true;
  185. }
  186. $query = new Query;
  187. $parents = $query->select(['parent'])
  188. ->from($this->itemChildTable)
  189. ->where(['child' => $itemName])
  190. ->column($this->db);
  191. foreach ($parents as $parent) {
  192. if ($this->checkAccessRecursive($user, $parent, $params, $assignments)) {
  193. return true;
  194. }
  195. }
  196. return false;
  197. }
  198. /**
  199. * @inheritdoc
  200. */
  201. protected function getItem($name)
  202. {
  203. if (empty($name)) {
  204. return null;
  205. }
  206. if (!empty($this->items[$name])) {
  207. return $this->items[$name];
  208. }
  209. $row = (new Query)->from($this->itemTable)
  210. ->where(['name' => $name])
  211. ->one($this->db);
  212. if ($row === false) {
  213. return null;
  214. }
  215. return $this->populateItem($row);
  216. }
  217. /**
  218. * Returns a value indicating whether the database supports cascading update and delete.
  219. * The default implementation will return false for SQLite database and true for all other databases.
  220. * @return bool whether the database supports cascading update and delete.
  221. */
  222. protected function supportsCascadeUpdate()
  223. {
  224. return strncmp($this->db->getDriverName(), 'sqlite', 6) !== 0;
  225. }
  226. /**
  227. * @inheritdoc
  228. */
  229. protected function addItem($item)
  230. {
  231. $time = time();
  232. if ($item->createdAt === null) {
  233. $item->createdAt = $time;
  234. }
  235. if ($item->updatedAt === null) {
  236. $item->updatedAt = $time;
  237. }
  238. $this->db->createCommand()
  239. ->insert($this->itemTable, [
  240. 'name' => $item->name,
  241. 'type' => $item->type,
  242. 'description' => $item->description,
  243. 'rule_name' => $item->ruleName,
  244. 'data' => $item->data === null ? null : serialize($item->data),
  245. 'created_at' => $item->createdAt,
  246. 'updated_at' => $item->updatedAt,
  247. ])->execute();
  248. $this->invalidateCache();
  249. return true;
  250. }
  251. /**
  252. * @inheritdoc
  253. */
  254. protected function removeItem($item)
  255. {
  256. if (!$this->supportsCascadeUpdate()) {
  257. $this->db->createCommand()
  258. ->delete($this->itemChildTable, ['or', '[[parent]]=:name', '[[child]]=:name'], [':name' => $item->name])
  259. ->execute();
  260. $this->db->createCommand()
  261. ->delete($this->assignmentTable, ['item_name' => $item->name])
  262. ->execute();
  263. }
  264. $this->db->createCommand()
  265. ->delete($this->itemTable, ['name' => $item->name])
  266. ->execute();
  267. $this->invalidateCache();
  268. return true;
  269. }
  270. /**
  271. * @inheritdoc
  272. */
  273. protected function updateItem($name, $item)
  274. {
  275. if ($item->name !== $name && !$this->supportsCascadeUpdate()) {
  276. $this->db->createCommand()
  277. ->update($this->itemChildTable, ['parent' => $item->name], ['parent' => $name])
  278. ->execute();
  279. $this->db->createCommand()
  280. ->update($this->itemChildTable, ['child' => $item->name], ['child' => $name])
  281. ->execute();
  282. $this->db->createCommand()
  283. ->update($this->assignmentTable, ['item_name' => $item->name], ['item_name' => $name])
  284. ->execute();
  285. }
  286. $item->updatedAt = time();
  287. $this->db->createCommand()
  288. ->update($this->itemTable, [
  289. 'name' => $item->name,
  290. 'description' => $item->description,
  291. 'rule_name' => $item->ruleName,
  292. 'data' => $item->data === null ? null : serialize($item->data),
  293. 'updated_at' => $item->updatedAt,
  294. ], [
  295. 'name' => $name,
  296. ])->execute();
  297. $this->invalidateCache();
  298. return true;
  299. }
  300. /**
  301. * @inheritdoc
  302. */
  303. protected function addRule($rule)
  304. {
  305. $time = time();
  306. if ($rule->createdAt === null) {
  307. $rule->createdAt = $time;
  308. }
  309. if ($rule->updatedAt === null) {
  310. $rule->updatedAt = $time;
  311. }
  312. $this->db->createCommand()
  313. ->insert($this->ruleTable, [
  314. 'name' => $rule->name,
  315. 'data' => serialize($rule),
  316. 'created_at' => $rule->createdAt,
  317. 'updated_at' => $rule->updatedAt,
  318. ])->execute();
  319. $this->invalidateCache();
  320. return true;
  321. }
  322. /**
  323. * @inheritdoc
  324. */
  325. protected function updateRule($name, $rule)
  326. {
  327. if ($rule->name !== $name && !$this->supportsCascadeUpdate()) {
  328. $this->db->createCommand()
  329. ->update($this->itemTable, ['rule_name' => $rule->name], ['rule_name' => $name])
  330. ->execute();
  331. }
  332. $rule->updatedAt = time();
  333. $this->db->createCommand()
  334. ->update($this->ruleTable, [
  335. 'name' => $rule->name,
  336. 'data' => serialize($rule),
  337. 'updated_at' => $rule->updatedAt,
  338. ], [
  339. 'name' => $name,
  340. ])->execute();
  341. $this->invalidateCache();
  342. return true;
  343. }
  344. /**
  345. * @inheritdoc
  346. */
  347. protected function removeRule($rule)
  348. {
  349. if (!$this->supportsCascadeUpdate()) {
  350. $this->db->createCommand()
  351. ->update($this->itemTable, ['rule_name' => null], ['rule_name' => $rule->name])
  352. ->execute();
  353. }
  354. $this->db->createCommand()
  355. ->delete($this->ruleTable, ['name' => $rule->name])
  356. ->execute();
  357. $this->invalidateCache();
  358. return true;
  359. }
  360. /**
  361. * @inheritdoc
  362. */
  363. protected function getItems($type)
  364. {
  365. $query = (new Query)
  366. ->from($this->itemTable)
  367. ->where(['type' => $type]);
  368. $items = [];
  369. foreach ($query->all($this->db) as $row) {
  370. $items[$row['name']] = $this->populateItem($row);
  371. }
  372. return $items;
  373. }
  374. /**
  375. * Populates an auth item with the data fetched from database
  376. * @param array $row the data from the auth item table
  377. * @return Item the populated auth item instance (either Role or Permission)
  378. */
  379. protected function populateItem($row)
  380. {
  381. $class = $row['type'] == Item::TYPE_PERMISSION ? Permission::className() : Role::className();
  382. if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
  383. $data = null;
  384. }
  385. return new $class([
  386. 'name' => $row['name'],
  387. 'type' => $row['type'],
  388. 'description' => $row['description'],
  389. 'ruleName' => $row['rule_name'],
  390. 'data' => $data,
  391. 'createdAt' => $row['created_at'],
  392. 'updatedAt' => $row['updated_at'],
  393. ]);
  394. }
  395. /**
  396. * @inheritdoc
  397. */
  398. public function getRolesByUser($userId)
  399. {
  400. if (!isset($userId) || $userId === '') {
  401. return [];
  402. }
  403. $query = (new Query)->select('b.*')
  404. ->from(['a' => $this->assignmentTable, 'b' => $this->itemTable])
  405. ->where('{{a}}.[[item_name]]={{b}}.[[name]]')
  406. ->andWhere(['a.user_id' => (string) $userId])
  407. ->andWhere(['b.type' => Item::TYPE_ROLE]);
  408. $roles = [];
  409. foreach ($query->all($this->db) as $row) {
  410. $roles[$row['name']] = $this->populateItem($row);
  411. }
  412. return $roles;
  413. }
  414. /**
  415. * @inheritdoc
  416. */
  417. public function getChildRoles($roleName)
  418. {
  419. $role = $this->getRole($roleName);
  420. if (is_null($role)) {
  421. throw new InvalidParamException("Role \"$roleName\" not found.");
  422. }
  423. $result = [];
  424. $this->getChildrenRecursive($roleName, $this->getChildrenList(), $result);
  425. $roles = [$roleName => $role];
  426. $roles += array_filter($this->getRoles(), function (Role $roleItem) use ($result) {
  427. return array_key_exists($roleItem->name, $result);
  428. });
  429. return $roles;
  430. }
  431. /**
  432. * @inheritdoc
  433. */
  434. public function getPermissionsByRole($roleName)
  435. {
  436. $childrenList = $this->getChildrenList();
  437. $result = [];
  438. $this->getChildrenRecursive($roleName, $childrenList, $result);
  439. if (empty($result)) {
  440. return [];
  441. }
  442. $query = (new Query)->from($this->itemTable)->where([
  443. 'type' => Item::TYPE_PERMISSION,
  444. 'name' => array_keys($result),
  445. ]);
  446. $permissions = [];
  447. foreach ($query->all($this->db) as $row) {
  448. $permissions[$row['name']] = $this->populateItem($row);
  449. }
  450. return $permissions;
  451. }
  452. /**
  453. * @inheritdoc
  454. */
  455. public function getPermissionsByUser($userId)
  456. {
  457. if (empty($userId)) {
  458. return [];
  459. }
  460. $directPermission = $this->getDirectPermissionsByUser($userId);
  461. $inheritedPermission = $this->getInheritedPermissionsByUser($userId);
  462. return array_merge($directPermission, $inheritedPermission);
  463. }
  464. /**
  465. * Returns all permissions that are directly assigned to user.
  466. * @param string|int $userId the user ID (see [[\yii\web\User::id]])
  467. * @return Permission[] all direct permissions that the user has. The array is indexed by the permission names.
  468. * @since 2.0.7
  469. */
  470. protected function getDirectPermissionsByUser($userId)
  471. {
  472. $query = (new Query)->select('b.*')
  473. ->from(['a' => $this->assignmentTable, 'b' => $this->itemTable])
  474. ->where('{{a}}.[[item_name]]={{b}}.[[name]]')
  475. ->andWhere(['a.user_id' => (string) $userId])
  476. ->andWhere(['b.type' => Item::TYPE_PERMISSION]);
  477. $permissions = [];
  478. foreach ($query->all($this->db) as $row) {
  479. $permissions[$row['name']] = $this->populateItem($row);
  480. }
  481. return $permissions;
  482. }
  483. /**
  484. * Returns all permissions that the user inherits from the roles assigned to him.
  485. * @param string|int $userId the user ID (see [[\yii\web\User::id]])
  486. * @return Permission[] all inherited permissions that the user has. The array is indexed by the permission names.
  487. * @since 2.0.7
  488. */
  489. protected function getInheritedPermissionsByUser($userId)
  490. {
  491. $query = (new Query)->select('item_name')
  492. ->from($this->assignmentTable)
  493. ->where(['user_id' => (string) $userId]);
  494. $childrenList = $this->getChildrenList();
  495. $result = [];
  496. foreach ($query->column($this->db) as $roleName) {
  497. $this->getChildrenRecursive($roleName, $childrenList, $result);
  498. }
  499. if (empty($result)) {
  500. return [];
  501. }
  502. $query = (new Query)->from($this->itemTable)->where([
  503. 'type' => Item::TYPE_PERMISSION,
  504. 'name' => array_keys($result),
  505. ]);
  506. $permissions = [];
  507. foreach ($query->all($this->db) as $row) {
  508. $permissions[$row['name']] = $this->populateItem($row);
  509. }
  510. return $permissions;
  511. }
  512. /**
  513. * Returns the children for every parent.
  514. * @return array the children list. Each array key is a parent item name,
  515. * and the corresponding array value is a list of child item names.
  516. */
  517. protected function getChildrenList()
  518. {
  519. $query = (new Query)->from($this->itemChildTable);
  520. $parents = [];
  521. foreach ($query->all($this->db) as $row) {
  522. $parents[$row['parent']][] = $row['child'];
  523. }
  524. return $parents;
  525. }
  526. /**
  527. * Recursively finds all children and grand children of the specified item.
  528. * @param string $name the name of the item whose children are to be looked for.
  529. * @param array $childrenList the child list built via [[getChildrenList()]]
  530. * @param array $result the children and grand children (in array keys)
  531. */
  532. protected function getChildrenRecursive($name, $childrenList, &$result)
  533. {
  534. if (isset($childrenList[$name])) {
  535. foreach ($childrenList[$name] as $child) {
  536. $result[$child] = true;
  537. $this->getChildrenRecursive($child, $childrenList, $result);
  538. }
  539. }
  540. }
  541. /**
  542. * @inheritdoc
  543. */
  544. public function getRule($name)
  545. {
  546. if ($this->rules !== null) {
  547. return isset($this->rules[$name]) ? $this->rules[$name] : null;
  548. }
  549. $row = (new Query)->select(['data'])
  550. ->from($this->ruleTable)
  551. ->where(['name' => $name])
  552. ->one($this->db);
  553. return $row === false ? null : unserialize($row['data']);
  554. }
  555. /**
  556. * @inheritdoc
  557. */
  558. public function getRules()
  559. {
  560. if ($this->rules !== null) {
  561. return $this->rules;
  562. }
  563. $query = (new Query)->from($this->ruleTable);
  564. $rules = [];
  565. foreach ($query->all($this->db) as $row) {
  566. $rules[$row['name']] = unserialize($row['data']);
  567. }
  568. return $rules;
  569. }
  570. /**
  571. * @inheritdoc
  572. */
  573. public function getAssignment($roleName, $userId)
  574. {
  575. if (empty($userId)) {
  576. return null;
  577. }
  578. $row = (new Query)->from($this->assignmentTable)
  579. ->where(['user_id' => (string) $userId, 'item_name' => $roleName])
  580. ->one($this->db);
  581. if ($row === false) {
  582. return null;
  583. }
  584. return new Assignment([
  585. 'userId' => $row['user_id'],
  586. 'roleName' => $row['item_name'],
  587. 'createdAt' => $row['created_at'],
  588. ]);
  589. }
  590. /**
  591. * @inheritdoc
  592. */
  593. public function getAssignments($userId)
  594. {
  595. if (empty($userId)) {
  596. return [];
  597. }
  598. $query = (new Query)
  599. ->from($this->assignmentTable)
  600. ->where(['user_id' => (string) $userId]);
  601. $assignments = [];
  602. foreach ($query->all($this->db) as $row) {
  603. $assignments[$row['item_name']] = new Assignment([
  604. 'userId' => $row['user_id'],
  605. 'roleName' => $row['item_name'],
  606. 'createdAt' => $row['created_at'],
  607. ]);
  608. }
  609. return $assignments;
  610. }
  611. /**
  612. * @inheritdoc
  613. * @since 2.0.8
  614. */
  615. public function canAddChild($parent, $child)
  616. {
  617. return !$this->detectLoop($parent, $child);
  618. }
  619. /**
  620. * @inheritdoc
  621. */
  622. public function addChild($parent, $child)
  623. {
  624. if ($parent->name === $child->name) {
  625. throw new InvalidParamException("Cannot add '{$parent->name}' as a child of itself.");
  626. }
  627. if ($parent instanceof Permission && $child instanceof Role) {
  628. throw new InvalidParamException('Cannot add a role as a child of a permission.');
  629. }
  630. if ($this->detectLoop($parent, $child)) {
  631. throw new InvalidCallException("Cannot add '{$child->name}' as a child of '{$parent->name}'. A loop has been detected.");
  632. }
  633. $this->db->createCommand()
  634. ->insert($this->itemChildTable, ['parent' => $parent->name, 'child' => $child->name])
  635. ->execute();
  636. $this->invalidateCache();
  637. return true;
  638. }
  639. /**
  640. * @inheritdoc
  641. */
  642. public function removeChild($parent, $child)
  643. {
  644. $result = $this->db->createCommand()
  645. ->delete($this->itemChildTable, ['parent' => $parent->name, 'child' => $child->name])
  646. ->execute() > 0;
  647. $this->invalidateCache();
  648. return $result;
  649. }
  650. /**
  651. * @inheritdoc
  652. */
  653. public function removeChildren($parent)
  654. {
  655. $result = $this->db->createCommand()
  656. ->delete($this->itemChildTable, ['parent' => $parent->name])
  657. ->execute() > 0;
  658. $this->invalidateCache();
  659. return $result;
  660. }
  661. /**
  662. * @inheritdoc
  663. */
  664. public function hasChild($parent, $child)
  665. {
  666. return (new Query)
  667. ->from($this->itemChildTable)
  668. ->where(['parent' => $parent->name, 'child' => $child->name])
  669. ->one($this->db) !== false;
  670. }
  671. /**
  672. * @inheritdoc
  673. */
  674. public function getChildren($name)
  675. {
  676. $query = (new Query)
  677. ->select(['name', 'type', 'description', 'rule_name', 'data', 'created_at', 'updated_at'])
  678. ->from([$this->itemTable, $this->itemChildTable])
  679. ->where(['parent' => $name, 'name' => new Expression('[[child]]')]);
  680. $children = [];
  681. foreach ($query->all($this->db) as $row) {
  682. $children[$row['name']] = $this->populateItem($row);
  683. }
  684. return $children;
  685. }
  686. /**
  687. * Checks whether there is a loop in the authorization item hierarchy.
  688. * @param Item $parent the parent item
  689. * @param Item $child the child item to be added to the hierarchy
  690. * @return bool whether a loop exists
  691. */
  692. protected function detectLoop($parent, $child)
  693. {
  694. if ($child->name === $parent->name) {
  695. return true;
  696. }
  697. foreach ($this->getChildren($child->name) as $grandchild) {
  698. if ($this->detectLoop($parent, $grandchild)) {
  699. return true;
  700. }
  701. }
  702. return false;
  703. }
  704. /**
  705. * @inheritdoc
  706. */
  707. public function assign($role, $userId)
  708. {
  709. $assignment = new Assignment([
  710. 'userId' => $userId,
  711. 'roleName' => $role->name,
  712. 'createdAt' => time(),
  713. ]);
  714. $this->db->createCommand()
  715. ->insert($this->assignmentTable, [
  716. 'user_id' => $assignment->userId,
  717. 'item_name' => $assignment->roleName,
  718. 'created_at' => $assignment->createdAt,
  719. ])->execute();
  720. return $assignment;
  721. }
  722. /**
  723. * @inheritdoc
  724. */
  725. public function revoke($role, $userId)
  726. {
  727. if (empty($userId)) {
  728. return false;
  729. }
  730. return $this->db->createCommand()
  731. ->delete($this->assignmentTable, ['user_id' => (string) $userId, 'item_name' => $role->name])
  732. ->execute() > 0;
  733. }
  734. /**
  735. * @inheritdoc
  736. */
  737. public function revokeAll($userId)
  738. {
  739. if (empty($userId)) {
  740. return false;
  741. }
  742. return $this->db->createCommand()
  743. ->delete($this->assignmentTable, ['user_id' => (string) $userId])
  744. ->execute() > 0;
  745. }
  746. /**
  747. * @inheritdoc
  748. */
  749. public function removeAll()
  750. {
  751. $this->removeAllAssignments();
  752. $this->db->createCommand()->delete($this->itemChildTable)->execute();
  753. $this->db->createCommand()->delete($this->itemTable)->execute();
  754. $this->db->createCommand()->delete($this->ruleTable)->execute();
  755. $this->invalidateCache();
  756. }
  757. /**
  758. * @inheritdoc
  759. */
  760. public function removeAllPermissions()
  761. {
  762. $this->removeAllItems(Item::TYPE_PERMISSION);
  763. }
  764. /**
  765. * @inheritdoc
  766. */
  767. public function removeAllRoles()
  768. {
  769. $this->removeAllItems(Item::TYPE_ROLE);
  770. }
  771. /**
  772. * Removes all auth items of the specified type.
  773. * @param int $type the auth item type (either Item::TYPE_PERMISSION or Item::TYPE_ROLE)
  774. */
  775. protected function removeAllItems($type)
  776. {
  777. if (!$this->supportsCascadeUpdate()) {
  778. $names = (new Query)
  779. ->select(['name'])
  780. ->from($this->itemTable)
  781. ->where(['type' => $type])
  782. ->column($this->db);
  783. if (empty($names)) {
  784. return;
  785. }
  786. $key = $type == Item::TYPE_PERMISSION ? 'child' : 'parent';
  787. $this->db->createCommand()
  788. ->delete($this->itemChildTable, [$key => $names])
  789. ->execute();
  790. $this->db->createCommand()
  791. ->delete($this->assignmentTable, ['item_name' => $names])
  792. ->execute();
  793. }
  794. $this->db->createCommand()
  795. ->delete($this->itemTable, ['type' => $type])
  796. ->execute();
  797. $this->invalidateCache();
  798. }
  799. /**
  800. * @inheritdoc
  801. */
  802. public function removeAllRules()
  803. {
  804. if (!$this->supportsCascadeUpdate()) {
  805. $this->db->createCommand()
  806. ->update($this->itemTable, ['rule_name' => null])
  807. ->execute();
  808. }
  809. $this->db->createCommand()->delete($this->ruleTable)->execute();
  810. $this->invalidateCache();
  811. }
  812. /**
  813. * @inheritdoc
  814. */
  815. public function removeAllAssignments()
  816. {
  817. $this->db->createCommand()->delete($this->assignmentTable)->execute();
  818. }
  819. public function invalidateCache()
  820. {
  821. if ($this->cache !== null) {
  822. $this->cache->delete($this->cacheKey);
  823. $this->items = null;
  824. $this->rules = null;
  825. $this->parents = null;
  826. }
  827. }
  828. public function loadFromCache()
  829. {
  830. if ($this->items !== null || !$this->cache instanceof Cache) {
  831. return;
  832. }
  833. $data = $this->cache->get($this->cacheKey);
  834. if (is_array($data) && isset($data[0], $data[1], $data[2])) {
  835. list ($this->items, $this->rules, $this->parents) = $data;
  836. return;
  837. }
  838. $query = (new Query)->from($this->itemTable);
  839. $this->items = [];
  840. foreach ($query->all($this->db) as $row) {
  841. $this->items[$row['name']] = $this->populateItem($row);
  842. }
  843. $query = (new Query)->from($this->ruleTable);
  844. $this->rules = [];
  845. foreach ($query->all($this->db) as $row) {
  846. $this->rules[$row['name']] = unserialize($row['data']);
  847. }
  848. $query = (new Query)->from($this->itemChildTable);
  849. $this->parents = [];
  850. foreach ($query->all($this->db) as $row) {
  851. if (isset($this->items[$row['child']])) {
  852. $this->parents[$row['child']][] = $row['parent'];
  853. }
  854. }
  855. $this->cache->set($this->cacheKey, [$this->items, $this->rules, $this->parents]);
  856. }
  857. /**
  858. * Returns all role assignment information for the specified role.
  859. * @param string $roleName
  860. * @return Assignment[] the assignments. An empty array will be
  861. * returned if role is not assigned to any user.
  862. * @since 2.0.7
  863. */
  864. public function getUserIdsByRole($roleName)
  865. {
  866. if (empty($roleName)) {
  867. return [];
  868. }
  869. return (new Query)->select('[[user_id]]')
  870. ->from($this->assignmentTable)
  871. ->where(['item_name' => $roleName])->column($this->db);
  872. }
  873. }