TinyAuthorize.php 7.6 KB

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