Manager.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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\Component;
  10. use yii\base\InvalidParamException;
  11. /**
  12. * Manager is the base class for authorization manager classes.
  13. *
  14. * Manager extends [[Component]] and implements some methods
  15. * that are common among authorization manager classes.
  16. *
  17. * Manager together with its concrete child classes implement the Role-Based
  18. * Access Control (RBAC).
  19. *
  20. * The main idea is that permissions are organized as a hierarchy of
  21. * [[Item]] authorization items. Items on higher level inherit the permissions
  22. * represented by items on lower level. And roles are simply top-level authorization items
  23. * that may be assigned to individual users. A user is said to have a permission
  24. * to do something if the corresponding authorization item is inherited by one of his roles.
  25. *
  26. * Using authorization manager consists of two aspects. First, the authorization hierarchy
  27. * and assignments have to be established. Manager and its child classes
  28. * provides APIs to accomplish this task. Developers may need to develop some GUI
  29. * so that it is more intuitive to end-users. Second, developers call [[Manager::checkAccess()]]
  30. * at appropriate places in the application code to check if the current user
  31. * has the needed permission for an operation.
  32. *
  33. * @property Item[] $operations Operations (name => AuthItem). This property is read-only.
  34. * @property Item[] $roles Roles (name => AuthItem). This property is read-only.
  35. * @property Item[] $tasks Tasks (name => AuthItem). This property is read-only.
  36. *
  37. * @author Qiang Xue <[email protected]>
  38. * @author Alexander Kochetov <[email protected]>
  39. * @since 2.0
  40. */
  41. abstract class Manager extends Component
  42. {
  43. /**
  44. * @var boolean Enable error reporting for bizRules.
  45. */
  46. public $showErrors = false;
  47. /**
  48. * @var array list of role names that are assigned to all users implicitly.
  49. * These roles do not need to be explicitly assigned to any user.
  50. * When calling [[checkAccess()]], these roles will be checked first.
  51. * For performance reason, you should minimize the number of such roles.
  52. * A typical usage of such roles is to define an 'authenticated' role and associate
  53. * it with a biz rule which checks if the current user is authenticated.
  54. * And then declare 'authenticated' in this property so that it can be applied to
  55. * every authenticated user.
  56. */
  57. public $defaultRoles = [];
  58. /**
  59. * Creates a role.
  60. * This is a shortcut method to [[Manager::createItem()]].
  61. * @param string $name the item name
  62. * @param string $description the item description.
  63. * @param string $bizRule the business rule associated with this item
  64. * @param mixed $data additional data to be passed when evaluating the business rule
  65. * @return Item the authorization item
  66. */
  67. public function createRole($name, $description = '', $bizRule = null, $data = null)
  68. {
  69. return $this->createItem($name, Item::TYPE_ROLE, $description, $bizRule, $data);
  70. }
  71. /**
  72. * Creates a task.
  73. * This is a shortcut method to [[Manager::createItem()]].
  74. * @param string $name the item name
  75. * @param string $description the item description.
  76. * @param string $bizRule the business rule associated with this item
  77. * @param mixed $data additional data to be passed when evaluating the business rule
  78. * @return Item the authorization item
  79. */
  80. public function createTask($name, $description = '', $bizRule = null, $data = null)
  81. {
  82. return $this->createItem($name, Item::TYPE_TASK, $description, $bizRule, $data);
  83. }
  84. /**
  85. * Creates an operation.
  86. * This is a shortcut method to [[Manager::createItem()]].
  87. * @param string $name the item name
  88. * @param string $description the item description.
  89. * @param string $bizRule the business rule associated with this item
  90. * @param mixed $data additional data to be passed when evaluating the business rule
  91. * @return Item the authorization item
  92. */
  93. public function createOperation($name, $description = '', $bizRule = null, $data = null)
  94. {
  95. return $this->createItem($name, Item::TYPE_OPERATION, $description, $bizRule, $data);
  96. }
  97. /**
  98. * Returns roles.
  99. * This is a shortcut method to [[Manager::getItems()]].
  100. * @param mixed $userId the user ID. If not null, only the roles directly assigned to the user
  101. * will be returned. Otherwise, all roles will be returned.
  102. * @return Item[] roles (name => AuthItem)
  103. */
  104. public function getRoles($userId = null)
  105. {
  106. return $this->getItems($userId, Item::TYPE_ROLE);
  107. }
  108. /**
  109. * Returns tasks.
  110. * This is a shortcut method to [[Manager::getItems()]].
  111. * @param mixed $userId the user ID. If not null, only the tasks directly assigned to the user
  112. * will be returned. Otherwise, all tasks will be returned.
  113. * @return Item[] tasks (name => AuthItem)
  114. */
  115. public function getTasks($userId = null)
  116. {
  117. return $this->getItems($userId, Item::TYPE_TASK);
  118. }
  119. /**
  120. * Returns operations.
  121. * This is a shortcut method to [[Manager::getItems()]].
  122. * @param mixed $userId the user ID. If not null, only the operations directly assigned to the user
  123. * will be returned. Otherwise, all operations will be returned.
  124. * @return Item[] operations (name => AuthItem)
  125. */
  126. public function getOperations($userId = null)
  127. {
  128. return $this->getItems($userId, Item::TYPE_OPERATION);
  129. }
  130. /**
  131. * Executes the specified business rule.
  132. * @param string $bizRule the business rule to be executed.
  133. * @param array $params parameters passed to [[Manager::checkAccess()]].
  134. * @param mixed $data additional data associated with the authorization item or assignment.
  135. * @return boolean whether the business rule returns true.
  136. * If the business rule is empty, it will still return true.
  137. */
  138. public function executeBizRule($bizRule, $params, $data)
  139. {
  140. return $bizRule === '' || $bizRule === null || ($this->showErrors ? eval($bizRule) != 0 : @eval($bizRule) != 0);
  141. }
  142. /**
  143. * Checks the item types to make sure a child can be added to a parent.
  144. * @param integer $parentType parent item type
  145. * @param integer $childType child item type
  146. * @throws InvalidParamException if the item cannot be added as a child due to its incompatible type.
  147. */
  148. protected function checkItemChildType($parentType, $childType)
  149. {
  150. static $types = ['operation', 'task', 'role'];
  151. if ($parentType < $childType) {
  152. throw new InvalidParamException("Cannot add an item of type '{$types[$childType]}' to an item of type '{$types[$parentType]}'.");
  153. }
  154. }
  155. /**
  156. * Performs access check for the specified user.
  157. * @param mixed $userId the user ID. This should be either an integer or a string representing
  158. * the unique identifier of a user. See [[User::id]].
  159. * @param string $itemName the name of the operation that we are checking access to
  160. * @param array $params name-value pairs that would be passed to biz rules associated
  161. * with the tasks and roles assigned to the user.
  162. * @return boolean whether the operations can be performed by the user.
  163. */
  164. abstract public function checkAccess($userId, $itemName, $params = []);
  165. /**
  166. * Creates an authorization item.
  167. * An authorization item represents an action permission (e.g. creating a post).
  168. * It has three types: operation, task and role.
  169. * Authorization items form a hierarchy. Higher level items inheirt permissions representing
  170. * by lower level items.
  171. * @param string $name the item name. This must be a unique identifier.
  172. * @param integer $type the item type (0: operation, 1: task, 2: role).
  173. * @param string $description description of the item
  174. * @param string $bizRule business rule associated with the item. This is a piece of
  175. * PHP code that will be executed when [[checkAccess()]] is called for the item.
  176. * @param mixed $data additional data associated with the item.
  177. * @throws \yii\base\Exception if an item with the same name already exists
  178. * @return Item the authorization item
  179. */
  180. abstract public function createItem($name, $type, $description = '', $bizRule = null, $data = null);
  181. /**
  182. * Removes the specified authorization item.
  183. * @param string $name the name of the item to be removed
  184. * @return boolean whether the item exists in the storage and has been removed
  185. */
  186. abstract public function removeItem($name);
  187. /**
  188. * Returns the authorization items of the specific type and user.
  189. * @param mixed $userId the user ID. Defaults to null, meaning returning all items even if
  190. * they are not assigned to a user.
  191. * @param integer $type the item type (0: operation, 1: task, 2: role). Defaults to null,
  192. * meaning returning all items regardless of their type.
  193. * @return Item[] the authorization items of the specific type.
  194. */
  195. abstract public function getItems($userId = null, $type = null);
  196. /**
  197. * Returns the authorization item with the specified name.
  198. * @param string $name the name of the item
  199. * @return Item the authorization item. Null if the item cannot be found.
  200. */
  201. abstract public function getItem($name);
  202. /**
  203. * Saves an authorization item to persistent storage.
  204. * @param Item $item the item to be saved.
  205. * @param string $oldName the old item name. If null, it means the item name is not changed.
  206. */
  207. abstract public function saveItem($item, $oldName = null);
  208. /**
  209. * Adds an item as a child of another item.
  210. * @param string $itemName the parent item name
  211. * @param string $childName the child item name
  212. * @throws \yii\base\Exception if either parent or child doesn't exist or if a loop has been detected.
  213. */
  214. abstract public function addItemChild($itemName, $childName);
  215. /**
  216. * Removes a child from its parent.
  217. * Note, the child item is not deleted. Only the parent-child relationship is removed.
  218. * @param string $itemName the parent item name
  219. * @param string $childName the child item name
  220. * @return boolean whether the removal is successful
  221. */
  222. abstract public function removeItemChild($itemName, $childName);
  223. /**
  224. * Returns a value indicating whether a child exists within a parent.
  225. * @param string $itemName the parent item name
  226. * @param string $childName the child item name
  227. * @return boolean whether the child exists
  228. */
  229. abstract public function hasItemChild($itemName, $childName);
  230. /**
  231. * Returns the children of the specified item.
  232. * @param mixed $itemName the parent item name. This can be either a string or an array.
  233. * The latter represents a list of item names.
  234. * @return Item[] all child items of the parent
  235. */
  236. abstract public function getItemChildren($itemName);
  237. /**
  238. * Assigns an authorization item to a user.
  239. * @param mixed $userId the user ID (see [[User::id]])
  240. * @param string $itemName the item name
  241. * @param string $bizRule the business rule to be executed when [[checkAccess()]] is called
  242. * for this particular authorization item.
  243. * @param mixed $data additional data associated with this assignment
  244. * @return Assignment the authorization assignment information.
  245. * @throws \yii\base\Exception if the item does not exist or if the item has already been assigned to the user
  246. */
  247. abstract public function assign($userId, $itemName, $bizRule = null, $data = null);
  248. /**
  249. * Revokes an authorization assignment from a user.
  250. * @param mixed $userId the user ID (see [[User::id]])
  251. * @param string $itemName the item name
  252. * @return boolean whether removal is successful
  253. */
  254. abstract public function revoke($userId, $itemName);
  255. /**
  256. * Revokes all authorization assignments from a user.
  257. * @param mixed $userId the user ID (see [[User::id]])
  258. * @return boolean whether removal is successful
  259. */
  260. abstract public function revokeAll($userId);
  261. /**
  262. * Returns a value indicating whether the item has been assigned to the user.
  263. * @param mixed $userId the user ID (see [[User::id]])
  264. * @param string $itemName the item name
  265. * @return boolean whether the item has been assigned to the user.
  266. */
  267. abstract public function isAssigned($userId, $itemName);
  268. /**
  269. * Returns the item assignment information.
  270. * @param mixed $userId the user ID (see [[User::id]])
  271. * @param string $itemName the item name
  272. * @return Assignment the item assignment information. Null is returned if
  273. * the item is not assigned to the user.
  274. */
  275. abstract public function getAssignment($userId, $itemName);
  276. /**
  277. * Returns the item assignments for the specified user.
  278. * @param mixed $userId the user ID (see [[User::id]])
  279. * @return Item[] the item assignment information for the user. An empty array will be
  280. * returned if there is no item assigned to the user.
  281. */
  282. abstract public function getAssignments($userId);
  283. /**
  284. * Saves the changes to an authorization assignment.
  285. * @param Assignment $assignment the assignment that has been changed.
  286. */
  287. abstract public function saveAssignment($assignment);
  288. /**
  289. * Removes all authorization data.
  290. */
  291. abstract public function clearAll();
  292. /**
  293. * Removes all authorization assignments.
  294. */
  295. abstract public function clearAssignments();
  296. /**
  297. * Saves authorization data into persistent storage.
  298. * If any change is made to the authorization data, please make
  299. * sure you call this method to save the changed data into persistent storage.
  300. */
  301. abstract public function save();
  302. }