TinyAuthorize.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. <?php
  2. App::uses('Inflector', 'Utility');
  3. if (!defined('CLASS_USER')) {
  4. define('CLASS_USER', 'User'); # override if you have it in a plugin: PluginName.User etc
  5. }
  6. if (!defined('AUTH_CACHE')) {
  7. define('AUTH_CACHE', '_cake_core_'); # use the most persistent cache by default
  8. }
  9. if (!defined('ACL_FILE')) {
  10. define('ACL_FILE', 'acl.ini'); # stored in /app/Config/
  11. }
  12. /**
  13. * Probably the most simple and fastest Acl out there.
  14. * Only one config file `roles.ini` necessary
  15. * Doesnt even need a Role Model/table
  16. * @link http://www.dereuromark.de/2011/12/18/tinyauth-the-fastest-and-easiest-authorization-for-cake2
  17. *
  18. * Usage:
  19. * Include it in your beforeFilter() method of the AppController
  20. * $this->Auth->authorize = array('Tools.Tiny');
  21. *
  22. * Or with admin prefix protection only
  23. * $this->Auth->authorize = array('Tools.Tiny'=>array('allowUser'=>true));
  24. *
  25. * @version 1.1 - now uses most persistent _cake_core_ cache by default
  26. * @author Mark Scherer
  27. * @cakephp 2.0
  28. * @license MIT
  29. * 2011-12-31 ms
  30. */
  31. class TinyAuthorize extends BaseAuthorize {
  32. protected $_matchArray = array();
  33. protected $_defaults = array(
  34. 'allowUser' => false, # quick way to allow user access to non prefixed urls
  35. 'adminPrefix' => 'admin_',
  36. 'cache' => AUTH_CACHE,
  37. 'cacheKey' => 'tiny_auth_acl',
  38. 'autoClearCache' => false # usually done by Cache automatically in debug mode
  39. );
  40. public function __construct(ComponentCollection $Collection, $settings = array()) {
  41. $settings = am($this->_defaults, $settings);
  42. parent::__construct($Collection, $settings);
  43. if (Cache::config($settings['cache']) === false) {
  44. throw new CakeException(__('TinyAuth could not find `%s` cache - expects at least a `default` cache', $settings['cache']));
  45. }
  46. $this->_matchArray = $this->_getRoles();
  47. }
  48. /**
  49. * Authorize a user using the AclComponent.
  50. * allows single or multi role based authorization
  51. * - User HABTM Roles (Role array in User array)
  52. * - User belongsTo Roles (role_id in User array)
  53. *
  54. * @param array $user The user to authorize
  55. * @param CakeRequest $request The request needing authorization.
  56. * @return boolean
  57. */
  58. public function authorize($user, CakeRequest $request) {
  59. if (isset($user['Role'])) {
  60. $roles = (array)$user['Role'];
  61. } else {
  62. $roles = array($user['role_id']);
  63. }
  64. return $this->validate($roles, $request->params['plugin'], $request->params['controller'], $request->params['action']);
  65. }
  66. /**
  67. * validate the url to the role(s)
  68. * allows single or multi role based authorization
  69. * @return bool $success
  70. */
  71. public function validate($roles, $plugin, $controller, $action) {
  72. $action = Inflector::underscore($action);
  73. $controller = Inflector::underscore($controller);
  74. $plugin = Inflector::underscore($plugin);
  75. if (!empty($this->settings['allowUser'])) {
  76. # all user actions are accessable for logged in users
  77. if (mb_strpos($action, $this->settings['adminPrefix']) !== 0) {
  78. return true;
  79. }
  80. }
  81. if (isset($this->_matchArray[$controller]['*'])) {
  82. $matchArray = $this->_matchArray[$controller]['*'];
  83. if (in_array(-1, $matchArray)) {
  84. return true;
  85. }
  86. foreach ($roles as $role) {
  87. if (in_array($role, $matchArray)) {
  88. return true;
  89. }
  90. }
  91. }
  92. if (!empty($controller) && !empty($action)) {
  93. if (array_key_exists($controller, $this->_matchArray) && !empty($this->_matchArray[$controller][$action])) {
  94. $matchArray = $this->_matchArray[$controller][$action];
  95. # direct access? (even if he has no roles = GUEST)
  96. if (in_array(-1, $matchArray)) {
  97. return true;
  98. }
  99. # normal access (rolebased)
  100. foreach ($roles as $role) {
  101. if (in_array($role, $matchArray)) {
  102. return true;
  103. }
  104. }
  105. }
  106. }
  107. return false;
  108. }
  109. /**
  110. * @return object $User: the User model
  111. */
  112. public function getModel() {
  113. return ClassRegistry::init(CLASS_USER);
  114. }
  115. /**
  116. * parse ini file and returns the allowed roles per action
  117. * - uses cache for maximum performance
  118. * improved speed by several actions before caching:
  119. * - resolves role slugs to their primary key / identifier
  120. * - resolves wildcards to their verbose translation
  121. * @return array $roles
  122. */
  123. protected function _getRoles() {
  124. $res = array();
  125. if ($this->settings['autoClearCache'] && Configure::read('debug') > 0) {
  126. Cache::delete($this->settings['cacheKey'], $this->settings['cache']);
  127. }
  128. if (($roles = Cache::read($this->settings['cacheKey'], $this->settings['cache'])) !== false) {
  129. return $roles;
  130. }
  131. if (!file_exists(APP . 'Config' . DS . ACL_FILE)) {
  132. touch(APP . 'Config' . DS . ACL_FILE);
  133. }
  134. $iniArray = parse_ini_file(APP . 'Config' . DS . ACL_FILE, true);
  135. $availableRoles = Configure::read('Role');
  136. if (!is_array($availableRoles)) {
  137. $Model = $this->getModel();
  138. $availableRoles = $Model->Role->find('list', array('fields'=>array('alias', 'id')));
  139. Configure::write('Role', $availableRoles);
  140. }
  141. if (!is_array($availableRoles) || !is_array($iniArray)) {
  142. trigger_error('Invalid Role Setup for TinyAuthorize (no roles found)');
  143. return false;
  144. }
  145. foreach ($iniArray as $key => $array) {
  146. list($plugin, $controllerName) = pluginSplit($key);
  147. $controllerName = Inflector::underscore($controllerName);
  148. foreach ($array as $actions => $roles) {
  149. $actions = explode(',', $actions);
  150. $roles = explode(',', $roles);
  151. foreach ($roles as $key => $role) {
  152. if (!($role = trim($role))) {
  153. continue;
  154. }
  155. if ($role == '*') {
  156. unset($roles[$key]);
  157. $roles = array_merge($roles, array_keys(Configure::read('Role')));
  158. }
  159. }
  160. foreach ($actions as $action) {
  161. if (!($action = trim($action))) {
  162. continue;
  163. }
  164. $actionName = Inflector::underscore($action);
  165. foreach ($roles as $role) {
  166. if (!($role = trim($role)) || $role == '*') {
  167. continue;
  168. }
  169. $newRole = Configure::read('Role.'.strtolower($role));
  170. if (!empty($res[$controllerName][$actionName]) && in_array($newRole, $res[$controllerName][$actionName])) {
  171. continue;
  172. }
  173. $res[$controllerName][$actionName][] = $newRole;
  174. }
  175. }
  176. }
  177. }
  178. Cache::write($this->settings['cacheKey'], $res, $this->settings['cache']);
  179. return $res;
  180. }
  181. }