AccessRule.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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\filters;
  8. use Closure;
  9. use yii\base\Action;
  10. use yii\base\Component;
  11. use yii\base\Controller;
  12. use yii\base\InvalidConfigException;
  13. use yii\helpers\StringHelper;
  14. use yii\web\Request;
  15. use yii\web\User;
  16. /**
  17. * This class represents an access rule defined by the [[AccessControl]] action filter.
  18. *
  19. * @author Qiang Xue <qiang.xue@gmail.com>
  20. * @since 2.0
  21. */
  22. class AccessRule extends Component
  23. {
  24. /**
  25. * @var bool whether this is an 'allow' rule or 'deny' rule.
  26. */
  27. public $allow;
  28. /**
  29. * @var array list of action IDs that this rule applies to. The comparison is case-sensitive.
  30. * If not set or empty, it means this rule applies to all actions.
  31. */
  32. public $actions;
  33. /**
  34. * @var array list of the controller IDs that this rule applies to.
  35. *
  36. * The comparison uses [[\yii\base\Controller::uniqueId]], so each controller ID is prefixed
  37. * with the module ID (if any). For a `product` controller in the application, you would specify
  38. * this property like `['product']` and if that controller is located in a `shop` module, this
  39. * would be `['shop/product']`.
  40. *
  41. * The comparison is case-sensitive.
  42. *
  43. * If not set or empty, it means this rule applies to all controllers.
  44. *
  45. * Since version 2.0.12 controller IDs can be specified as wildcards, e.g. `module/*`.
  46. */
  47. public $controllers;
  48. /**
  49. * @var array list of roles that this rule applies to (requires properly configured User component).
  50. * Two special roles are recognized, and they are checked via [[User::isGuest]]:
  51. *
  52. * - `?`: matches a guest user (not authenticated yet)
  53. * - `@`: matches an authenticated user
  54. *
  55. * If you are using RBAC (Role-Based Access Control), you may also specify role names.
  56. * In this case, [[User::can()]] will be called to check access.
  57. *
  58. * Note that it is preferred to check for permissions instead.
  59. *
  60. * If this property is not set or empty, it means this rule applies regardless of roles.
  61. * @see $permissions
  62. * @see $roleParams
  63. */
  64. public $roles;
  65. /**
  66. * @var array list of RBAC (Role-Based Access Control) permissions that this rules applies to.
  67. * [[User::can()]] will be called to check access.
  68. *
  69. * If this property is not set or empty, it means this rule applies regardless of permissions.
  70. * @since 2.0.12
  71. * @see $roles
  72. * @see $roleParams
  73. */
  74. public $permissions;
  75. /**
  76. * @var array|Closure parameters to pass to the [[User::can()]] function for evaluating
  77. * user permissions in [[$roles]].
  78. *
  79. * If this is an array, it will be passed directly to [[User::can()]]. For example for passing an
  80. * ID from the current request, you may use the following:
  81. *
  82. * ```php
  83. * ['postId' => Yii::$app->request->get('id')]
  84. * ```
  85. *
  86. * You may also specify a closure that returns an array. This can be used to
  87. * evaluate the array values only if they are needed, for example when a model needs to be
  88. * loaded like in the following code:
  89. *
  90. * ```php
  91. * 'rules' => [
  92. * [
  93. * 'allow' => true,
  94. * 'actions' => ['update'],
  95. * 'roles' => ['updatePost'],
  96. * 'roleParams' => function($rule) {
  97. * return ['post' => Post::findOne(Yii::$app->request->get('id'))];
  98. * },
  99. * ],
  100. * ],
  101. * ```
  102. *
  103. * A reference to the [[AccessRule]] instance will be passed to the closure as the first parameter.
  104. *
  105. * @see $roles
  106. * @since 2.0.12
  107. */
  108. public $roleParams = [];
  109. /**
  110. * @var array list of user IP addresses that this rule applies to. An IP address
  111. * can contain the wildcard `*` at the end so that it matches IP addresses with the same prefix.
  112. * For example, '192.168.*' matches all IP addresses in the segment '192.168.'.
  113. * If not set or empty, it means this rule applies to all IP addresses.
  114. * @see Request::userIP
  115. */
  116. public $ips;
  117. /**
  118. * @var array list of request methods (e.g. `GET`, `POST`) that this rule applies to.
  119. * If not set or empty, it means this rule applies to all request methods.
  120. * @see \yii\web\Request::method
  121. */
  122. public $verbs;
  123. /**
  124. * @var callable a callback that will be called to determine if the rule should be applied.
  125. * The signature of the callback should be as follows:
  126. *
  127. * ```php
  128. * function ($rule, $action)
  129. * ```
  130. *
  131. * where `$rule` is this rule, and `$action` is the current [[Action|action]] object.
  132. * The callback should return a boolean value indicating whether this rule should be applied.
  133. */
  134. public $matchCallback;
  135. /**
  136. * @var callable a callback that will be called if this rule determines the access to
  137. * the current action should be denied. This is the case when this rule matches
  138. * and [[$allow]] is set to `false`.
  139. *
  140. * If not set, the behavior will be determined by [[AccessControl]],
  141. * either using [[AccessControl::denyAccess()]]
  142. * or [[AccessControl::$denyCallback]], if configured.
  143. *
  144. * The signature of the callback should be as follows:
  145. *
  146. * ```php
  147. * function ($rule, $action)
  148. * ```
  149. *
  150. * where `$rule` is this rule, and `$action` is the current [[Action|action]] object.
  151. * @see AccessControl::$denyCallback
  152. */
  153. public $denyCallback;
  154. /**
  155. * Checks whether the Web user is allowed to perform the specified action.
  156. * @param Action $action the action to be performed
  157. * @param User|false $user the user object or `false` in case of detached User component
  158. * @param Request $request
  159. * @return bool|null `true` if the user is allowed, `false` if the user is denied, `null` if the rule does not apply to the user
  160. */
  161. public function allows($action, $user, $request)
  162. {
  163. if ($this->matchAction($action)
  164. && $this->matchRole($user)
  165. && $this->matchIP($request->getUserIP())
  166. && $this->matchVerb($request->getMethod())
  167. && $this->matchController($action->controller)
  168. && $this->matchCustom($action)
  169. ) {
  170. return $this->allow ? true : false;
  171. }
  172. return null;
  173. }
  174. /**
  175. * @param Action $action the action
  176. * @return bool whether the rule applies to the action
  177. */
  178. protected function matchAction($action)
  179. {
  180. return empty($this->actions) || in_array($action->id, $this->actions, true);
  181. }
  182. /**
  183. * @param Controller $controller the controller
  184. * @return bool whether the rule applies to the controller
  185. */
  186. protected function matchController($controller)
  187. {
  188. if (empty($this->controllers)) {
  189. return true;
  190. }
  191. $id = $controller->getUniqueId();
  192. foreach ($this->controllers as $pattern) {
  193. if (StringHelper::matchWildcard($pattern, $id)) {
  194. return true;
  195. }
  196. }
  197. return false;
  198. }
  199. /**
  200. * @param User $user the user object
  201. * @return bool whether the rule applies to the role
  202. * @throws InvalidConfigException if User component is detached
  203. */
  204. protected function matchRole($user)
  205. {
  206. $items = empty($this->roles) ? [] : $this->roles;
  207. if (!empty($this->permissions)) {
  208. $items = array_merge($items, $this->permissions);
  209. }
  210. if (empty($items)) {
  211. return true;
  212. }
  213. if ($user === false) {
  214. throw new InvalidConfigException('The user application component must be available to specify roles in AccessRule.');
  215. }
  216. foreach ($items as $item) {
  217. if ($item === '?') {
  218. if ($user->getIsGuest()) {
  219. return true;
  220. }
  221. } elseif ($item === '@') {
  222. if (!$user->getIsGuest()) {
  223. return true;
  224. }
  225. } else {
  226. if (!isset($roleParams)) {
  227. $roleParams = $this->roleParams instanceof Closure ? call_user_func($this->roleParams, $this) : $this->roleParams;
  228. }
  229. if ($user->can($item, $roleParams)) {
  230. return true;
  231. }
  232. }
  233. }
  234. return false;
  235. }
  236. /**
  237. * @param string|null $ip the IP address
  238. * @return bool whether the rule applies to the IP address
  239. */
  240. protected function matchIP($ip)
  241. {
  242. if (empty($this->ips)) {
  243. return true;
  244. }
  245. foreach ($this->ips as $rule) {
  246. if ($rule === '*' ||
  247. $rule === $ip ||
  248. (
  249. $ip !== null &&
  250. ($pos = strpos($rule, '*')) !== false &&
  251. strncmp($ip, $rule, $pos) === 0
  252. )
  253. ) {
  254. return true;
  255. }
  256. }
  257. return false;
  258. }
  259. /**
  260. * @param string $verb the request method.
  261. * @return bool whether the rule applies to the request
  262. */
  263. protected function matchVerb($verb)
  264. {
  265. return empty($this->verbs) || in_array(strtoupper($verb), array_map('strtoupper', $this->verbs), true);
  266. }
  267. /**
  268. * @param Action $action the action to be performed
  269. * @return bool whether the rule should be applied
  270. */
  271. protected function matchCustom($action)
  272. {
  273. return empty($this->matchCallback) || call_user_func($this->matchCallback, $this, $action);
  274. }
  275. }