TinyAuthorize.php 7.0 KB

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