PhpManager.php 17 KB

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