TinyAuthorize.php 6.7 KB

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