TinyAuthorize.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. <?php
  2. App::uses('Inflector', 'Utility');
  3. App::uses('Hash', 'Utility');
  4. App::uses('BaseAuthorize', 'Controller/Component/Auth');
  5. if (!defined('CLASS_USER')) {
  6. define('CLASS_USER', 'User'); // override if you have it in a plugin: PluginName.User etc
  7. }
  8. if (!defined('AUTH_CACHE')) {
  9. define('AUTH_CACHE', '_cake_core_'); // use the most persistent cache by default
  10. }
  11. if (!defined('ACL_FILE')) {
  12. define('ACL_FILE', 'acl.ini'); // stored in /app/Config/
  13. }
  14. /**
  15. * Probably the most simple and fastest Acl out there.
  16. * Only one config file `acl.ini` necessary
  17. * Doesn't even need a Role Model / roles table
  18. * Uses most persistent _cake_core_ cache by default
  19. * @link http://www.dereuromark.de/2011/12/18/tinyauth-the-fastest-and-easiest-authorization-for-cake2
  20. *
  21. * Usage:
  22. * Include it in your beforeFilter() method of the AppController
  23. * $this->Auth->authorize = array('Tools.Tiny');
  24. *
  25. * Or with admin prefix protection only
  26. * $this->Auth->authorize = array('Tools.Tiny'=>array('allowUser'=>true));
  27. *
  28. * @version 1.2 - now allows other parent model relations besides Role/role_id
  29. * @author Mark Scherer
  30. * @license MIT
  31. */
  32. class TinyAuthorize extends BaseAuthorize {
  33. protected $_acl = null;
  34. protected $_defaultConfig = array(
  35. 'superadminRole' => null, // quick way to allow access to every action
  36. 'allowUser' => false, // quick way to allow user access to non prefixed urls
  37. 'allowAdmin' => false, // quick way to allow admin access to admin prefixed urls
  38. 'adminPrefix' => 'admin_',
  39. 'adminRole' => null, // needed together with adminPrefix if allowAdmin is enabled
  40. 'cache' => AUTH_CACHE,
  41. 'cacheKey' => 'tiny_auth_acl',
  42. 'autoClearCache' => false, // usually done by Cache automatically in debug mode,
  43. 'aclModel' => 'Role', // only for multiple roles per user (HABTM)
  44. 'aclKey' => 'role_id', // only for single roles per user (BT)
  45. );
  46. /**
  47. * TinyAuthorize::__construct()
  48. *
  49. * @param ComponentCollection $Collection
  50. * @param array $config
  51. */
  52. public function __construct(ComponentCollection $Collection, $config = array()) {
  53. $config += $this->_defaultConfig;
  54. parent::__construct($Collection, $config);
  55. if (Cache::config($config['cache']) === false) {
  56. throw new CakeException(__d('dev', 'TinyAuth could not find `%s` cache - expects at least a `default` cache', $settings['cache']));
  57. }
  58. }
  59. /**
  60. * Authorize a user using the AclComponent.
  61. * allows single or multi role based authorization
  62. *
  63. * Examples:
  64. * - User HABTM Roles (Role array in User array)
  65. * - User belongsTo Roles (role_id in User array)
  66. *
  67. * @param array $user The user to authorize
  68. * @param CakeRequest $request The request needing authorization.
  69. * @return bool Success
  70. */
  71. public function authorize($user, CakeRequest $request) {
  72. if (isset($user[$this->settings['aclModel']])) {
  73. if (isset($user[$this->settings['aclModel']][0]['id'])) {
  74. $roles = Hash::extract($user[$this->settings['aclModel']], '{n}.id');
  75. } elseif (isset($user[$this->settings['aclModel']]['id'])) {
  76. $roles = array($user[$this->settings['aclModel']]['id']);
  77. } else {
  78. $roles = (array)$user[$this->settings['aclModel']];
  79. }
  80. } elseif (isset($user[$this->settings['aclKey']])) {
  81. $roles = array($user[$this->settings['aclKey']]);
  82. } else {
  83. $acl = $this->settings['aclModel'] . '/' . $this->settings['aclKey'];
  84. trigger_error(__d('dev', 'Missing acl information (%s) in user session', $acl));
  85. $roles = array();
  86. }
  87. return $this->validate($roles, $request->params['plugin'], $request->params['controller'], $request->params['action']);
  88. }
  89. /**
  90. * Validate the url to the role(s)
  91. * allows single or multi role based authorization
  92. *
  93. * @return bool Success
  94. */
  95. public function validate($roles, $plugin, $controller, $action) {
  96. $action = Inflector::underscore($action);
  97. $controller = Inflector::underscore($controller);
  98. $plugin = Inflector::underscore($plugin);
  99. if (!empty($this->settings['allowUser'])) {
  100. // all user actions are accessable for logged in users
  101. if (mb_strpos($action, $this->settings['adminPrefix']) !== 0) {
  102. return true;
  103. }
  104. }
  105. if (!empty($this->settings['allowAdmin']) && !empty($this->settings['adminRole'])) {
  106. // all admin actions are accessable for logged in admins
  107. if (mb_strpos($action, $this->settings['adminPrefix']) === 0) {
  108. if (in_array((string)$this->settings['adminRole'], $roles)) {
  109. return true;
  110. }
  111. }
  112. }
  113. if ($this->_acl === null) {
  114. $this->_acl = $this->_getAcl();
  115. }
  116. // allow_all check
  117. if (!empty($this->settings['superadminRole'])) {
  118. foreach ($roles as $role) {
  119. if ($role == $this->settings['superadminRole']) {
  120. return true;
  121. }
  122. }
  123. }
  124. // controller wildcard
  125. if (isset($this->_acl[$controller]['*'])) {
  126. $matchArray = $this->_acl[$controller]['*'];
  127. if (in_array('-1', $matchArray)) {
  128. return true;
  129. }
  130. foreach ($roles as $role) {
  131. if (in_array((string)$role, $matchArray)) {
  132. return true;
  133. }
  134. }
  135. }
  136. // specific controller/action
  137. if (!empty($controller) && !empty($action)) {
  138. if (array_key_exists($controller, $this->_acl) && !empty($this->_acl[$controller][$action])) {
  139. $matchArray = $this->_acl[$controller][$action];
  140. // direct access? (even if he has no roles = GUEST)
  141. if (in_array('-1', $matchArray)) {
  142. return true;
  143. }
  144. // normal access (rolebased)
  145. foreach ($roles as $role) {
  146. if (in_array((string)$role, $matchArray)) {
  147. return true;
  148. }
  149. }
  150. }
  151. }
  152. return false;
  153. }
  154. /**
  155. * @return object The User model
  156. */
  157. public function getModel() {
  158. return ClassRegistry::init(CLASS_USER);
  159. }
  160. /**
  161. * Parse ini file and returns the allowed roles per action
  162. * - uses cache for maximum performance
  163. * improved speed by several actions before caching:
  164. * - resolves role slugs to their primary key / identifier
  165. * - resolves wildcards to their verbose translation
  166. *
  167. * @return array Roles
  168. */
  169. protected function _getAcl($path = null) {
  170. if ($path === null) {
  171. $path = APP . 'Config' . DS;
  172. }
  173. $res = array();
  174. if ($this->settings['autoClearCache'] && Configure::read('debug') > 0) {
  175. Cache::delete($this->settings['cacheKey'], $this->settings['cache']);
  176. }
  177. if (($roles = Cache::read($this->settings['cacheKey'], $this->settings['cache'])) !== false) {
  178. return $roles;
  179. }
  180. if (!file_exists($path . ACL_FILE)) {
  181. touch($path . ACL_FILE);
  182. }
  183. if (function_exists('parse_ini_file')) {
  184. $iniArray = parse_ini_file($path . ACL_FILE, true);
  185. } else {
  186. $iniArray = parse_ini_string(file_get_contents($path . ACL_FILE), true);
  187. }
  188. $availableRoles = Configure::read($this->settings['aclModel']);
  189. if (!is_array($availableRoles)) {
  190. $Model = $this->getModel();
  191. if (!isset($Model->{$this->settings['aclModel']})) {
  192. throw new CakeException('Missing relationship between User and Role.');
  193. }
  194. $availableRoles = $Model->{$this->settings['aclModel']}->find('list', array('fields' => array('alias', 'id')));
  195. Configure::write($this->settings['aclModel'], $availableRoles);
  196. }
  197. if (!is_array($availableRoles) || !is_array($iniArray)) {
  198. trigger_error(__d('dev', 'Invalid Role Setup for TinyAuthorize (no roles found)'));
  199. return array();
  200. }
  201. foreach ($iniArray as $key => $array) {
  202. list($plugin, $controllerName) = pluginSplit($key);
  203. $controllerName = Inflector::underscore($controllerName);
  204. foreach ($array as $actions => $roles) {
  205. $actions = explode(',', $actions);
  206. $roles = explode(',', $roles);
  207. foreach ($roles as $key => $role) {
  208. if (!($role = trim($role))) {
  209. continue;
  210. }
  211. if ($role === '*') {
  212. unset($roles[$key]);
  213. $roles = array_merge($roles, array_keys(Configure::read($this->settings['aclModel'])));
  214. }
  215. }
  216. foreach ($actions as $action) {
  217. if (!($action = trim($action))) {
  218. continue;
  219. }
  220. $actionName = Inflector::underscore($action);
  221. foreach ($roles as $role) {
  222. if (!($role = trim($role)) || $role === '*') {
  223. continue;
  224. }
  225. $newRole = Configure::read($this->settings['aclModel'] . '.' . strtolower($role));
  226. if (!empty($res[$controllerName][$actionName]) && in_array((string)$newRole, $res[$controllerName][$actionName])) {
  227. continue;
  228. }
  229. $res[$controllerName][$actionName][] = $newRole;
  230. }
  231. }
  232. }
  233. }
  234. Cache::write($this->settings['cacheKey'], $res, $this->settings['cache']);
  235. return $res;
  236. }
  237. }