TinyAuthorize.php 8.3 KB

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