DbManager.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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\db\Connection;
  10. use yii\db\Query;
  11. use yii\db\Expression;
  12. use yii\base\Exception;
  13. use yii\base\InvalidConfigException;
  14. use yii\base\InvalidCallException;
  15. use yii\base\InvalidParamException;
  16. /**
  17. * DbManager represents an authorization manager that stores authorization information in database.
  18. *
  19. * The database connection is specified by [[db]]. And the database schema
  20. * should be as described in "framework/rbac/*.sql". You may change the names of
  21. * the three tables used to store the authorization data by setting [[itemTable]],
  22. * [[itemChildTable]] and [[assignmentTable]].
  23. *
  24. * @property Item[] $items The authorization items of the specific type. This property is read-only.
  25. *
  26. * @author Qiang Xue <[email protected]>
  27. * @author Alexander Kochetov <[email protected]>
  28. * @since 2.0
  29. */
  30. class DbManager extends Manager
  31. {
  32. /**
  33. * @var Connection|string the DB connection object or the application component ID of the DB connection.
  34. * After the DbManager object is created, if you want to change this property, you should only assign it
  35. * with a DB connection object.
  36. */
  37. public $db = 'db';
  38. /**
  39. * @var string the name of the table storing authorization items. Defaults to 'tbl_auth_item'.
  40. */
  41. public $itemTable = '{{%auth_item}}';
  42. /**
  43. * @var string the name of the table storing authorization item hierarchy. Defaults to 'tbl_auth_item_child'.
  44. */
  45. public $itemChildTable = '{{%auth_item_child}}';
  46. /**
  47. * @var string the name of the table storing authorization item assignments. Defaults to 'tbl_auth_assignment'.
  48. */
  49. public $assignmentTable = '{{%auth_assignment}}';
  50. private $_usingSqlite;
  51. /**
  52. * Initializes the application component.
  53. * This method overrides the parent implementation by establishing the database connection.
  54. */
  55. public function init()
  56. {
  57. if (is_string($this->db)) {
  58. $this->db = Yii::$app->getComponent($this->db);
  59. }
  60. if (!$this->db instanceof Connection) {
  61. throw new InvalidConfigException("DbManager::db must be either a DB connection instance or the application component ID of a DB connection.");
  62. }
  63. $this->_usingSqlite = !strncmp($this->db->getDriverName(), 'sqlite', 6);
  64. parent::init();
  65. }
  66. /**
  67. * Performs access check for the specified user.
  68. * @param mixed $userId the user ID. This should can be either an integer or a string representing
  69. * the unique identifier of a user. See [[User::id]].
  70. * @param string $itemName the name of the operation that need access check
  71. * @param array $params name-value pairs that would be passed to biz rules associated
  72. * with the tasks and roles assigned to the user. A param with name 'userId' is added to this array,
  73. * which holds the value of `$userId`.
  74. * @return boolean whether the operations can be performed by the user.
  75. */
  76. public function checkAccess($userId, $itemName, $params = [])
  77. {
  78. $assignments = $this->getAssignments($userId);
  79. return $this->checkAccessRecursive($userId, $itemName, $params, $assignments);
  80. }
  81. /**
  82. * Performs access check for the specified user.
  83. * This method is internally called by [[checkAccess()]].
  84. * @param mixed $userId the user ID. This should can be either an integer or a string representing
  85. * the unique identifier of a user. See [[User::id]].
  86. * @param string $itemName the name of the operation that need access check
  87. * @param array $params name-value pairs that would be passed to biz rules associated
  88. * with the tasks and roles assigned to the user. A param with name 'userId' is added to this array,
  89. * which holds the value of `$userId`.
  90. * @param Assignment[] $assignments the assignments to the specified user
  91. * @return boolean whether the operations can be performed by the user.
  92. */
  93. protected function checkAccessRecursive($userId, $itemName, $params, $assignments)
  94. {
  95. if (($item = $this->getItem($itemName)) === null) {
  96. return false;
  97. }
  98. Yii::trace('Checking permission: ' . $item->getName(), __METHOD__);
  99. if (!isset($params['userId'])) {
  100. $params['userId'] = $userId;
  101. }
  102. if ($this->executeBizRule($item->bizRule, $params, $item->data)) {
  103. if (in_array($itemName, $this->defaultRoles)) {
  104. return true;
  105. }
  106. if (isset($assignments[$itemName])) {
  107. $assignment = $assignments[$itemName];
  108. if ($this->executeBizRule($assignment->bizRule, $params, $assignment->data)) {
  109. return true;
  110. }
  111. }
  112. $query = new Query;
  113. $parents = $query->select(['parent'])
  114. ->from($this->itemChildTable)
  115. ->where(['child' => $itemName])
  116. ->createCommand($this->db)
  117. ->queryColumn();
  118. foreach ($parents as $parent) {
  119. if ($this->checkAccessRecursive($userId, $parent, $params, $assignments)) {
  120. return true;
  121. }
  122. }
  123. }
  124. return false;
  125. }
  126. /**
  127. * Adds an item as a child of another item.
  128. * @param string $itemName the parent item name
  129. * @param string $childName the child item name
  130. * @return boolean whether the item is added successfully
  131. * @throws Exception if either parent or child doesn't exist.
  132. * @throws InvalidCallException if a loop has been detected.
  133. */
  134. public function addItemChild($itemName, $childName)
  135. {
  136. if ($itemName === $childName) {
  137. throw new Exception("Cannot add '$itemName' as a child of itself.");
  138. }
  139. $query = new Query;
  140. $rows = $query->from($this->itemTable)
  141. ->where(['or', 'name=:name1', 'name=:name2'], [':name1' => $itemName, ':name2' => $childName])
  142. ->createCommand($this->db)
  143. ->queryAll();
  144. if (count($rows) == 2) {
  145. if ($rows[0]['name'] === $itemName) {
  146. $parentType = $rows[0]['type'];
  147. $childType = $rows[1]['type'];
  148. } else {
  149. $childType = $rows[0]['type'];
  150. $parentType = $rows[1]['type'];
  151. }
  152. $this->checkItemChildType($parentType, $childType);
  153. if ($this->detectLoop($itemName, $childName)) {
  154. throw new InvalidCallException("Cannot add '$childName' as a child of '$itemName'. A loop has been detected.");
  155. }
  156. $this->db->createCommand()
  157. ->insert($this->itemChildTable, ['parent' => $itemName, 'child' => $childName])
  158. ->execute();
  159. return true;
  160. } else {
  161. throw new Exception("Either '$itemName' or '$childName' does not exist.");
  162. }
  163. }
  164. /**
  165. * Removes a child from its parent.
  166. * Note, the child item is not deleted. Only the parent-child relationship is removed.
  167. * @param string $itemName the parent item name
  168. * @param string $childName the child item name
  169. * @return boolean whether the removal is successful
  170. */
  171. public function removeItemChild($itemName, $childName)
  172. {
  173. return $this->db->createCommand()
  174. ->delete($this->itemChildTable, ['parent' => $itemName, 'child' => $childName])
  175. ->execute() > 0;
  176. }
  177. /**
  178. * Returns a value indicating whether a child exists within a parent.
  179. * @param string $itemName the parent item name
  180. * @param string $childName the child item name
  181. * @return boolean whether the child exists
  182. */
  183. public function hasItemChild($itemName, $childName)
  184. {
  185. $query = new Query;
  186. return $query->select(['parent'])
  187. ->from($this->itemChildTable)
  188. ->where(['parent' => $itemName, 'child' => $childName])
  189. ->createCommand($this->db)
  190. ->queryScalar() !== false;
  191. }
  192. /**
  193. * Returns the children of the specified item.
  194. * @param mixed $names the parent item name. This can be either a string or an array.
  195. * The latter represents a list of item names.
  196. * @return Item[] all child items of the parent
  197. */
  198. public function getItemChildren($names)
  199. {
  200. $query = new Query;
  201. $rows = $query->select(['name', 'type', 'description', 'biz_rule', 'data'])
  202. ->from([$this->itemTable, $this->itemChildTable])
  203. ->where(['parent' => $names, 'name' => new Expression('child')])
  204. ->createCommand($this->db)
  205. ->queryAll();
  206. $children = [];
  207. foreach ($rows as $row) {
  208. if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
  209. $data = null;
  210. }
  211. $children[$row['name']] = new Item([
  212. 'manager' => $this,
  213. 'name' => $row['name'],
  214. 'type' => $row['type'],
  215. 'description' => $row['description'],
  216. 'bizRule' => $row['biz_rule'],
  217. 'data' => $data,
  218. ]);
  219. }
  220. return $children;
  221. }
  222. /**
  223. * Assigns an authorization item to a user.
  224. * @param mixed $userId the user ID (see [[User::id]])
  225. * @param string $itemName the item name
  226. * @param string $bizRule the business rule to be executed when [[checkAccess()]] is called
  227. * for this particular authorization item.
  228. * @param mixed $data additional data associated with this assignment
  229. * @return Assignment the authorization assignment information.
  230. * @throws InvalidParamException if the item does not exist or if the item has already been assigned to the user
  231. */
  232. public function assign($userId, $itemName, $bizRule = null, $data = null)
  233. {
  234. if ($this->usingSqlite() && $this->getItem($itemName) === null) {
  235. throw new InvalidParamException("The item '$itemName' does not exist.");
  236. }
  237. $this->db->createCommand()
  238. ->insert($this->assignmentTable, [
  239. 'user_id' => $userId,
  240. 'item_name' => $itemName,
  241. 'biz_rule' => $bizRule,
  242. 'data' => $data === null ? null : serialize($data),
  243. ])
  244. ->execute();
  245. return new Assignment([
  246. 'manager' => $this,
  247. 'userId' => $userId,
  248. 'itemName' => $itemName,
  249. 'bizRule' => $bizRule,
  250. 'data' => $data,
  251. ]);
  252. }
  253. /**
  254. * Revokes an authorization assignment from a user.
  255. * @param mixed $userId the user ID (see [[User::id]])
  256. * @param string $itemName the item name
  257. * @return boolean whether removal is successful
  258. */
  259. public function revoke($userId, $itemName)
  260. {
  261. return $this->db->createCommand()
  262. ->delete($this->assignmentTable, ['user_id' => $userId, 'item_name' => $itemName])
  263. ->execute() > 0;
  264. }
  265. /**
  266. * Revokes all authorization assignments from a user.
  267. * @param mixed $userId the user ID (see [[User::id]])
  268. * @return boolean whether removal is successful
  269. */
  270. public function revokeAll($userId)
  271. {
  272. return $this->db->createCommand()
  273. ->delete($this->assignmentTable, ['user_id' => $userId])
  274. ->execute() > 0;
  275. }
  276. /**
  277. * Returns a value indicating whether the item has been assigned to the user.
  278. * @param mixed $userId the user ID (see [[User::id]])
  279. * @param string $itemName the item name
  280. * @return boolean whether the item has been assigned to the user.
  281. */
  282. public function isAssigned($userId, $itemName)
  283. {
  284. $query = new Query;
  285. return $query->select(['item_name'])
  286. ->from($this->assignmentTable)
  287. ->where(['user_id' => $userId, 'item_name' => $itemName])
  288. ->createCommand($this->db)
  289. ->queryScalar() !== false;
  290. }
  291. /**
  292. * Returns the item assignment information.
  293. * @param mixed $userId the user ID (see [[User::id]])
  294. * @param string $itemName the item name
  295. * @return Assignment the item assignment information. Null is returned if
  296. * the item is not assigned to the user.
  297. */
  298. public function getAssignment($userId, $itemName)
  299. {
  300. $query = new Query;
  301. $row = $query->from($this->assignmentTable)
  302. ->where(['user_id' => $userId, 'item_name' => $itemName])
  303. ->createCommand($this->db)
  304. ->queryOne();
  305. if ($row !== false) {
  306. if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
  307. $data = null;
  308. }
  309. return new Assignment([
  310. 'manager' => $this,
  311. 'userId' => $row['user_id'],
  312. 'itemName' => $row['item_name'],
  313. 'bizRule' => $row['biz_rule'],
  314. 'data' => $data,
  315. ]);
  316. } else {
  317. return null;
  318. }
  319. }
  320. /**
  321. * Returns the item assignments for the specified user.
  322. * @param mixed $userId the user ID (see [[User::id]])
  323. * @return Assignment[] the item assignment information for the user. An empty array will be
  324. * returned if there is no item assigned to the user.
  325. */
  326. public function getAssignments($userId)
  327. {
  328. $query = new Query;
  329. $rows = $query->from($this->assignmentTable)
  330. ->where(['user_id' => $userId])
  331. ->createCommand($this->db)
  332. ->queryAll();
  333. $assignments = [];
  334. foreach ($rows as $row) {
  335. if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
  336. $data = null;
  337. }
  338. $assignments[$row['item_name']] = new Assignment([
  339. 'manager' => $this,
  340. 'userId' => $row['user_id'],
  341. 'itemName' => $row['item_name'],
  342. 'bizRule' => $row['biz_rule'],
  343. 'data' => $data,
  344. ]);
  345. }
  346. return $assignments;
  347. }
  348. /**
  349. * Saves the changes to an authorization assignment.
  350. * @param Assignment $assignment the assignment that has been changed.
  351. */
  352. public function saveAssignment($assignment)
  353. {
  354. $this->db->createCommand()
  355. ->update($this->assignmentTable, [
  356. 'biz_rule' => $assignment->bizRule,
  357. 'data' => $assignment->data === null ? null : serialize($assignment->data),
  358. ], [
  359. 'user_id' => $assignment->userId,
  360. 'item_name' => $assignment->itemName,
  361. ])
  362. ->execute();
  363. }
  364. /**
  365. * Returns the authorization items of the specific type and user.
  366. * @param mixed $userId the user ID. Defaults to null, meaning returning all items even if
  367. * they are not assigned to a user.
  368. * @param integer $type the item type (0: operation, 1: task, 2: role). Defaults to null,
  369. * meaning returning all items regardless of their type.
  370. * @return Item[] the authorization items of the specific type.
  371. */
  372. public function getItems($userId = null, $type = null)
  373. {
  374. $query = new Query;
  375. if ($userId === null && $type === null) {
  376. $command = $query->from($this->itemTable)
  377. ->createCommand($this->db);
  378. } elseif ($userId === null) {
  379. $command = $query->from($this->itemTable)
  380. ->where(['type' => $type])
  381. ->createCommand($this->db);
  382. } elseif ($type === null) {
  383. $command = $query->select(['name', 'type', 'description', 't1.biz_rule', 't1.data'])
  384. ->from([$this->itemTable . ' t1', $this->assignmentTable . ' t2'])
  385. ->where(['user_id' => $userId, 'name' => new Expression('item_name')])
  386. ->createCommand($this->db);
  387. } else {
  388. $command = $query->select(['name', 'type', 'description', 't1.biz_rule', 't1.data'])
  389. ->from([$this->itemTable . ' t1', $this->assignmentTable . ' t2'])
  390. ->where(['user_id' => $userId, 'type' => $type, 'name' => new Expression('item_name')])
  391. ->createCommand($this->db);
  392. }
  393. $items = [];
  394. foreach ($command->queryAll() as $row) {
  395. if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
  396. $data = null;
  397. }
  398. $items[$row['name']] = new Item([
  399. 'manager' => $this,
  400. 'name' => $row['name'],
  401. 'type' => $row['type'],
  402. 'description' => $row['description'],
  403. 'bizRule' => $row['biz_rule'],
  404. 'data' => $data,
  405. ]);
  406. }
  407. return $items;
  408. }
  409. /**
  410. * Creates an authorization item.
  411. * An authorization item represents an action permission (e.g. creating a post).
  412. * It has three types: operation, task and role.
  413. * Authorization items form a hierarchy. Higher level items inheirt permissions representing
  414. * by lower level items.
  415. * @param string $name the item name. This must be a unique identifier.
  416. * @param integer $type the item type (0: operation, 1: task, 2: role).
  417. * @param string $description description of the item
  418. * @param string $bizRule business rule associated with the item. This is a piece of
  419. * PHP code that will be executed when [[checkAccess()]] is called for the item.
  420. * @param mixed $data additional data associated with the item.
  421. * @return Item the authorization item
  422. * @throws Exception if an item with the same name already exists
  423. */
  424. public function createItem($name, $type, $description = '', $bizRule = null, $data = null)
  425. {
  426. $this->db->createCommand()
  427. ->insert($this->itemTable, [
  428. 'name' => $name,
  429. 'type' => $type,
  430. 'description' => $description,
  431. 'biz_rule' => $bizRule,
  432. 'data' => $data === null ? null : serialize($data),
  433. ])
  434. ->execute();
  435. return new Item([
  436. 'manager' => $this,
  437. 'name' => $name,
  438. 'type' => $type,
  439. 'description' => $description,
  440. 'bizRule' => $bizRule,
  441. 'data' => $data,
  442. ]);
  443. }
  444. /**
  445. * Removes the specified authorization item.
  446. * @param string $name the name of the item to be removed
  447. * @return boolean whether the item exists in the storage and has been removed
  448. */
  449. public function removeItem($name)
  450. {
  451. if ($this->usingSqlite()) {
  452. $this->db->createCommand()
  453. ->delete($this->itemChildTable, ['or', 'parent=:name', 'child=:name'], [':name' => $name])
  454. ->execute();
  455. $this->db->createCommand()
  456. ->delete($this->assignmentTable, ['item_name' => $name])
  457. ->execute();
  458. }
  459. return $this->db->createCommand()
  460. ->delete($this->itemTable, ['name' => $name])
  461. ->execute() > 0;
  462. }
  463. /**
  464. * Returns the authorization item with the specified name.
  465. * @param string $name the name of the item
  466. * @return Item the authorization item. Null if the item cannot be found.
  467. */
  468. public function getItem($name)
  469. {
  470. $query = new Query;
  471. $row = $query->from($this->itemTable)
  472. ->where(['name' => $name])
  473. ->createCommand($this->db)
  474. ->queryOne();
  475. if ($row !== false) {
  476. if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
  477. $data = null;
  478. }
  479. return new Item([
  480. 'manager' => $this,
  481. 'name' => $row['name'],
  482. 'type' => $row['type'],
  483. 'description' => $row['description'],
  484. 'bizRule' => $row['biz_rule'],
  485. 'data' => $data,
  486. ]);
  487. } else {
  488. return null;
  489. }
  490. }
  491. /**
  492. * Saves an authorization item to persistent storage.
  493. * @param Item $item the item to be saved.
  494. * @param string $oldName the old item name. If null, it means the item name is not changed.
  495. */
  496. public function saveItem($item, $oldName = null)
  497. {
  498. if ($this->usingSqlite() && $oldName !== null && $item->getName() !== $oldName) {
  499. $this->db->createCommand()
  500. ->update($this->itemChildTable, ['parent' => $item->getName()], ['parent' => $oldName])
  501. ->execute();
  502. $this->db->createCommand()
  503. ->update($this->itemChildTable, ['child' => $item->getName()], ['child' => $oldName])
  504. ->execute();
  505. $this->db->createCommand()
  506. ->update($this->assignmentTable, ['item_name' => $item->getName()], ['item_name' => $oldName])
  507. ->execute();
  508. }
  509. $this->db->createCommand()
  510. ->update($this->itemTable, [
  511. 'name' => $item->getName(),
  512. 'type' => $item->type,
  513. 'description' => $item->description,
  514. 'biz_rule' => $item->bizRule,
  515. 'data' => $item->data === null ? null : serialize($item->data),
  516. ], [
  517. 'name' => $oldName === null ? $item->getName() : $oldName,
  518. ])
  519. ->execute();
  520. }
  521. /**
  522. * Saves the authorization data to persistent storage.
  523. */
  524. public function save()
  525. {
  526. }
  527. /**
  528. * Removes all authorization data.
  529. */
  530. public function clearAll()
  531. {
  532. $this->clearAssignments();
  533. $this->db->createCommand()->delete($this->itemChildTable)->execute();
  534. $this->db->createCommand()->delete($this->itemTable)->execute();
  535. }
  536. /**
  537. * Removes all authorization assignments.
  538. */
  539. public function clearAssignments()
  540. {
  541. $this->db->createCommand()->delete($this->assignmentTable)->execute();
  542. }
  543. /**
  544. * Checks whether there is a loop in the authorization item hierarchy.
  545. * @param string $itemName parent item name
  546. * @param string $childName the name of the child item that is to be added to the hierarchy
  547. * @return boolean whether a loop exists
  548. */
  549. protected function detectLoop($itemName, $childName)
  550. {
  551. if ($childName === $itemName) {
  552. return true;
  553. }
  554. foreach ($this->getItemChildren($childName) as $child) {
  555. if ($this->detectLoop($itemName, $child->getName())) {
  556. return true;
  557. }
  558. }
  559. return false;
  560. }
  561. /**
  562. * @return boolean whether the database is a SQLite database
  563. */
  564. protected function usingSqlite()
  565. {
  566. return $this->_usingSqlite;
  567. }
  568. }