DbManager.php 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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(is_resource($row['data']) ? stream_get_contents($row['data']) : $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 = $this->getDefaultRoleInstances();
  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 ($role === null) {
  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. if ($row === false) {
  554. return null;
  555. }
  556. $data = $row['data'];
  557. if (is_resource($data)) {
  558. $data = stream_get_contents($data);
  559. }
  560. return unserialize($data);
  561. }
  562. /**
  563. * @inheritdoc
  564. */
  565. public function getRules()
  566. {
  567. if ($this->rules !== null) {
  568. return $this->rules;
  569. }
  570. $query = (new Query)->from($this->ruleTable);
  571. $rules = [];
  572. foreach ($query->all($this->db) as $row) {
  573. $data = $row['data'];
  574. if (is_resource($data)) {
  575. $data = stream_get_contents($data);
  576. }
  577. $rules[$row['name']] = unserialize($data);
  578. }
  579. return $rules;
  580. }
  581. /**
  582. * @inheritdoc
  583. */
  584. public function getAssignment($roleName, $userId)
  585. {
  586. if (empty($userId)) {
  587. return null;
  588. }
  589. $row = (new Query)->from($this->assignmentTable)
  590. ->where(['user_id' => (string) $userId, 'item_name' => $roleName])
  591. ->one($this->db);
  592. if ($row === false) {
  593. return null;
  594. }
  595. return new Assignment([
  596. 'userId' => $row['user_id'],
  597. 'roleName' => $row['item_name'],
  598. 'createdAt' => $row['created_at'],
  599. ]);
  600. }
  601. /**
  602. * @inheritdoc
  603. */
  604. public function getAssignments($userId)
  605. {
  606. if (empty($userId)) {
  607. return [];
  608. }
  609. $query = (new Query)
  610. ->from($this->assignmentTable)
  611. ->where(['user_id' => (string) $userId]);
  612. $assignments = [];
  613. foreach ($query->all($this->db) as $row) {
  614. $assignments[$row['item_name']] = new Assignment([
  615. 'userId' => $row['user_id'],
  616. 'roleName' => $row['item_name'],
  617. 'createdAt' => $row['created_at'],
  618. ]);
  619. }
  620. return $assignments;
  621. }
  622. /**
  623. * @inheritdoc
  624. * @since 2.0.8
  625. */
  626. public function canAddChild($parent, $child)
  627. {
  628. return !$this->detectLoop($parent, $child);
  629. }
  630. /**
  631. * @inheritdoc
  632. */
  633. public function addChild($parent, $child)
  634. {
  635. if ($parent->name === $child->name) {
  636. throw new InvalidParamException("Cannot add '{$parent->name}' as a child of itself.");
  637. }
  638. if ($parent instanceof Permission && $child instanceof Role) {
  639. throw new InvalidParamException('Cannot add a role as a child of a permission.');
  640. }
  641. if ($this->detectLoop($parent, $child)) {
  642. throw new InvalidCallException("Cannot add '{$child->name}' as a child of '{$parent->name}'. A loop has been detected.");
  643. }
  644. $this->db->createCommand()
  645. ->insert($this->itemChildTable, ['parent' => $parent->name, 'child' => $child->name])
  646. ->execute();
  647. $this->invalidateCache();
  648. return true;
  649. }
  650. /**
  651. * @inheritdoc
  652. */
  653. public function removeChild($parent, $child)
  654. {
  655. $result = $this->db->createCommand()
  656. ->delete($this->itemChildTable, ['parent' => $parent->name, 'child' => $child->name])
  657. ->execute() > 0;
  658. $this->invalidateCache();
  659. return $result;
  660. }
  661. /**
  662. * @inheritdoc
  663. */
  664. public function removeChildren($parent)
  665. {
  666. $result = $this->db->createCommand()
  667. ->delete($this->itemChildTable, ['parent' => $parent->name])
  668. ->execute() > 0;
  669. $this->invalidateCache();
  670. return $result;
  671. }
  672. /**
  673. * @inheritdoc
  674. */
  675. public function hasChild($parent, $child)
  676. {
  677. return (new Query)
  678. ->from($this->itemChildTable)
  679. ->where(['parent' => $parent->name, 'child' => $child->name])
  680. ->one($this->db) !== false;
  681. }
  682. /**
  683. * @inheritdoc
  684. */
  685. public function getChildren($name)
  686. {
  687. $query = (new Query)
  688. ->select(['name', 'type', 'description', 'rule_name', 'data', 'created_at', 'updated_at'])
  689. ->from([$this->itemTable, $this->itemChildTable])
  690. ->where(['parent' => $name, 'name' => new Expression('[[child]]')]);
  691. $children = [];
  692. foreach ($query->all($this->db) as $row) {
  693. $children[$row['name']] = $this->populateItem($row);
  694. }
  695. return $children;
  696. }
  697. /**
  698. * Checks whether there is a loop in the authorization item hierarchy.
  699. * @param Item $parent the parent item
  700. * @param Item $child the child item to be added to the hierarchy
  701. * @return bool whether a loop exists
  702. */
  703. protected function detectLoop($parent, $child)
  704. {
  705. if ($child->name === $parent->name) {
  706. return true;
  707. }
  708. foreach ($this->getChildren($child->name) as $grandchild) {
  709. if ($this->detectLoop($parent, $grandchild)) {
  710. return true;
  711. }
  712. }
  713. return false;
  714. }
  715. /**
  716. * @inheritdoc
  717. */
  718. public function assign($role, $userId)
  719. {
  720. $assignment = new Assignment([
  721. 'userId' => $userId,
  722. 'roleName' => $role->name,
  723. 'createdAt' => time(),
  724. ]);
  725. $this->db->createCommand()
  726. ->insert($this->assignmentTable, [
  727. 'user_id' => $assignment->userId,
  728. 'item_name' => $assignment->roleName,
  729. 'created_at' => $assignment->createdAt,
  730. ])->execute();
  731. return $assignment;
  732. }
  733. /**
  734. * @inheritdoc
  735. */
  736. public function revoke($role, $userId)
  737. {
  738. if (empty($userId)) {
  739. return false;
  740. }
  741. return $this->db->createCommand()
  742. ->delete($this->assignmentTable, ['user_id' => (string) $userId, 'item_name' => $role->name])
  743. ->execute() > 0;
  744. }
  745. /**
  746. * @inheritdoc
  747. */
  748. public function revokeAll($userId)
  749. {
  750. if (empty($userId)) {
  751. return false;
  752. }
  753. return $this->db->createCommand()
  754. ->delete($this->assignmentTable, ['user_id' => (string) $userId])
  755. ->execute() > 0;
  756. }
  757. /**
  758. * @inheritdoc
  759. */
  760. public function removeAll()
  761. {
  762. $this->removeAllAssignments();
  763. $this->db->createCommand()->delete($this->itemChildTable)->execute();
  764. $this->db->createCommand()->delete($this->itemTable)->execute();
  765. $this->db->createCommand()->delete($this->ruleTable)->execute();
  766. $this->invalidateCache();
  767. }
  768. /**
  769. * @inheritdoc
  770. */
  771. public function removeAllPermissions()
  772. {
  773. $this->removeAllItems(Item::TYPE_PERMISSION);
  774. }
  775. /**
  776. * @inheritdoc
  777. */
  778. public function removeAllRoles()
  779. {
  780. $this->removeAllItems(Item::TYPE_ROLE);
  781. }
  782. /**
  783. * Removes all auth items of the specified type.
  784. * @param int $type the auth item type (either Item::TYPE_PERMISSION or Item::TYPE_ROLE)
  785. */
  786. protected function removeAllItems($type)
  787. {
  788. if (!$this->supportsCascadeUpdate()) {
  789. $names = (new Query)
  790. ->select(['name'])
  791. ->from($this->itemTable)
  792. ->where(['type' => $type])
  793. ->column($this->db);
  794. if (empty($names)) {
  795. return;
  796. }
  797. $key = $type == Item::TYPE_PERMISSION ? 'child' : 'parent';
  798. $this->db->createCommand()
  799. ->delete($this->itemChildTable, [$key => $names])
  800. ->execute();
  801. $this->db->createCommand()
  802. ->delete($this->assignmentTable, ['item_name' => $names])
  803. ->execute();
  804. }
  805. $this->db->createCommand()
  806. ->delete($this->itemTable, ['type' => $type])
  807. ->execute();
  808. $this->invalidateCache();
  809. }
  810. /**
  811. * @inheritdoc
  812. */
  813. public function removeAllRules()
  814. {
  815. if (!$this->supportsCascadeUpdate()) {
  816. $this->db->createCommand()
  817. ->update($this->itemTable, ['rule_name' => null])
  818. ->execute();
  819. }
  820. $this->db->createCommand()->delete($this->ruleTable)->execute();
  821. $this->invalidateCache();
  822. }
  823. /**
  824. * @inheritdoc
  825. */
  826. public function removeAllAssignments()
  827. {
  828. $this->db->createCommand()->delete($this->assignmentTable)->execute();
  829. }
  830. public function invalidateCache()
  831. {
  832. if ($this->cache !== null) {
  833. $this->cache->delete($this->cacheKey);
  834. $this->items = null;
  835. $this->rules = null;
  836. $this->parents = null;
  837. }
  838. }
  839. public function loadFromCache()
  840. {
  841. if ($this->items !== null || !$this->cache instanceof Cache) {
  842. return;
  843. }
  844. $data = $this->cache->get($this->cacheKey);
  845. if (is_array($data) && isset($data[0], $data[1], $data[2])) {
  846. list ($this->items, $this->rules, $this->parents) = $data;
  847. return;
  848. }
  849. $query = (new Query)->from($this->itemTable);
  850. $this->items = [];
  851. foreach ($query->all($this->db) as $row) {
  852. $this->items[$row['name']] = $this->populateItem($row);
  853. }
  854. $query = (new Query)->from($this->ruleTable);
  855. $this->rules = [];
  856. foreach ($query->all($this->db) as $row) {
  857. $data = $row['data'];
  858. if (is_resource($data)) {
  859. $data = stream_get_contents($data);
  860. }
  861. $this->rules[$row['name']] = unserialize($data);
  862. }
  863. $query = (new Query)->from($this->itemChildTable);
  864. $this->parents = [];
  865. foreach ($query->all($this->db) as $row) {
  866. if (isset($this->items[$row['child']])) {
  867. $this->parents[$row['child']][] = $row['parent'];
  868. }
  869. }
  870. $this->cache->set($this->cacheKey, [$this->items, $this->rules, $this->parents]);
  871. }
  872. /**
  873. * Returns all role assignment information for the specified role.
  874. * @param string $roleName
  875. * @return string[] the ids. An empty array will be
  876. * returned if role is not assigned to any user.
  877. * @since 2.0.7
  878. */
  879. public function getUserIdsByRole($roleName)
  880. {
  881. if (empty($roleName)) {
  882. return [];
  883. }
  884. return (new Query)->select('[[user_id]]')
  885. ->from($this->assignmentTable)
  886. ->where(['item_name' => $roleName])->column($this->db);
  887. }
  888. }