AuthExtComponent.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. <?php
  2. if (!defined('USER_ROLE_KEY')) {
  3. define('USER_ROLE_KEY', 'Role');
  4. }
  5. if (!defined('USER_INFO_KEY')) {
  6. define('USER_INFO_KEY', 'Info');
  7. }
  8. if (!defined('USER_RIGHT_KEY')) {
  9. define('USER_RIGHT_KEY', 'Right');
  10. }
  11. if (!defined('CLASS_USER')) {
  12. define('CLASS_USER', 'User');
  13. }
  14. App::uses('AuthComponent', 'Controller/Component');
  15. /**
  16. * Important:
  17. * index the ACO on alias, index the Aro on model+id
  18. *
  19. * Extends AuthComponent with the following addons:
  20. * - allows multiple roles per user
  21. * - auto-raises login counter and sets last_login date
  22. * - preps the session data according to completeAuth() method (adds parent data etc)
  23. * - dynamic login scope validation
  24. *
  25. * @author Mark Scherer
  26. * @cakephp 2.x
  27. * @license MIT
  28. * 2011-12-18 ms
  29. */
  30. class AuthExtComponent extends AuthComponent {
  31. public $intermediateModel = 'RoleUser';
  32. public $roleModel = 'Role';
  33. public $fieldKey = 'role_id';
  34. public $loginAction = array('controller' => 'account', 'action' => 'login', 'admin' => false, 'plugin' => false);
  35. public $loginRedirect = array('controller' => 'overview', 'action' => 'home', 'admin' => false, 'plugin' => false);
  36. public $autoRedirect = false;
  37. public $loginError = null;
  38. public $settings = array(
  39. 'multi' => null, # null=auto - yes/no multiple roles (HABTM table between users and roles)
  40. 'parentModelAlias' => USER_ROLE_KEY,
  41. 'userModel' => CLASS_USER //TODO: allow plugin syntax
  42. );
  43. # field name in DB , if none is specified there will be no floodProtection
  44. public $floodProtection = null;
  45. public function __construct(ComponentCollection $Collection, $settings = array()) {
  46. $settings = array_merge($this->settings, (array)Configure::read('Auth'), (array)$settings);
  47. parent::__construct($Collection, $settings);
  48. }
  49. public function initialize(Controller $Controller) {
  50. $this->Controller = $Controller;
  51. parent::initialize($Controller);
  52. }
  53. /**
  54. * 2.1 fix for allowing * as wildcard (tmp solution)
  55. * 2012-01-10 ms
  56. */
  57. public function allow($action = null) {
  58. if (((array)$action) === array('*')) {
  59. parent::allow();
  60. trigger_error('* is deprecated for allow() - use allow() without any argument to allow all actions');
  61. return;
  62. }
  63. $args = func_get_args();
  64. if (empty($args) || $action === null) {
  65. parent::allow();
  66. }
  67. parent::allow($args);
  68. }
  69. public function login($user = null) {
  70. $Model = $this->getModel();
  71. $this->_setDefaults();
  72. if (empty($user)) {
  73. $user = $this->identify($this->Controller->request, $this->Controller->response);
  74. } elseif (!is_array($user)) {
  75. $user = $this->completeAuth($user);
  76. }
  77. if (empty($user)) {
  78. $this->loginError = __('invalidLoginCredentials');
  79. return false;
  80. }
  81. # custom checks
  82. if (isset($user['active'])) {
  83. if (empty($user['active'])) {
  84. $this->loginError = __('Account not active yet');
  85. return false;
  86. }
  87. if (!empty($user['suspended'])) {
  88. $this->loginError = __('Account wurde vorübergehend gesperrt');
  89. if (!empty($user['suspended_reason'])) {
  90. $this->loginError .= BR . BR . 'Grund:' . BR . nl2br(h($user['suspended_reason']));
  91. }
  92. return false;
  93. }
  94. } else {
  95. if (isset($user['status']) && empty($user['status'])) {
  96. $this->loginError = __('Account not active yet');
  97. return false;
  98. }
  99. if (isset($user['status']) && defined('User::STATUS_PENDING') && $user['status'] == User::STATUS_PENDING) {
  100. $this->loginError = __('Account wurde noch nicht freigeschalten');
  101. return false;
  102. }
  103. if (isset($user['status']) && defined('User::STATUS_SUSPENDED') && $user['status'] == User::STATUS_SUSPENDED) {
  104. $this->loginError = 'Account wurde vorübergehend gesperrt';
  105. if (!empty($user['suspended_reason'])) {
  106. $this->loginError .= BR . BR . 'Grund:' . BR . nl2br(h($user['suspended_reason']));
  107. }
  108. return false;
  109. }
  110. if (isset($user['status']) && defined('User::STATUS_DEL') && $user['status'] == User::STATUS_DEL) {
  111. $this->loginError = 'Account wurde gelöscht';
  112. if (!empty($user['suspended_reason'])) {
  113. $this->loginError .= BR . BR . 'Grund:' . BR . nl2br(h($user['suspended_reason']));
  114. }
  115. return false;
  116. }
  117. if (isset($user['status']) && defined('User::STATUS_ACTIVE') && $user['status'] != User::STATUS_ACTIVE) {
  118. $this->loginError = __('Unknown Error');
  119. return false;
  120. }
  121. }
  122. if (isset($user['email_confirmed']) && empty($user['email_confirmed'])) {
  123. $this->loginError = __('Email not active yet');
  124. return false;
  125. }
  126. if ($user) {
  127. # update login counter
  128. if (isset($user['logins'])) {
  129. $user['logins'] = $user['logins'] + 1;
  130. if (method_exists($Model, 'loginUpdate')) {
  131. $Model->loginUpdate($user);
  132. }
  133. }
  134. $this->Session->renew();
  135. $this->Session->write(self::$sessionKey, $user);
  136. $this->Session->write(self::$sessionKey, $this->completeAuth($user));
  137. }
  138. return $this->loggedIn();
  139. }
  140. /**
  141. * @return array $user or bool false on failure
  142. * 2011-11-03 ms
  143. */
  144. public function completeAuth($user) {
  145. $Model = $this->getModel();
  146. if (!is_array($user)) {
  147. $user = $Model->get($user);
  148. if (!$user) {
  149. return false;
  150. }
  151. $user = array_shift($user);
  152. }
  153. if (isset($Model->hasAndBelongsToMany[$this->roleModel]['className'])) {
  154. $with = $Model->hasAndBelongsToMany[$this->roleModel]['className'];
  155. } elseif (isset($Model->hasMany[$this->intermediateModel]['className'])) {
  156. $with = $Model->hasMany[$this->intermediateModel]['className'];
  157. } elseif (isset($Model->belongsTo[$this->roleModel]['className'])) {
  158. $with = $Model->belongsTo[$this->roleModel]['className'];
  159. }
  160. if (empty($with) && $this->settings['parentModelAlias'] !== false) {
  161. trigger_error('No relation from user to role found');
  162. return false;
  163. }
  164. $completeAuth = array($this->settings['userModel']=>$user);
  165. # roles
  166. if (!empty($with)) {
  167. list($plugin, $withModel) = pluginSplit($with);
  168. if (!isset($this->{$withModel})) {
  169. $this->{$withModel} = ClassRegistry::init($with);
  170. }
  171. # only for multi
  172. if ($this->settings['multi'] || !isset($completeAuth[$this->settings['userModel']]['role_id'])) {
  173. $parentModelAlias = $this->settings['parentModelAlias'];
  174. $completeAuth[$this->settings['userModel']][$parentModelAlias] = array(); # default: no roles!
  175. $roles = $this->{$withModel}->find('list', array('fields' => array($withModel.'.role_id'), 'conditions' => array($withModel.'.user_id' => $user['id'])));
  176. if (!empty($roles)) {
  177. //$primaryRole = $this->user($this->fieldKey);
  178. // retrieve associated role that are not the primary one
  179. # MAYBE USEFUL FOR GUEST!!!
  180. //$roles = set::extract('/'.$with.'['.$this->fieldKey.'!='.$primaryRole.']/'.$this->fieldKey, $roles);
  181. // add the suplemental roles id under the Auth session key
  182. $completeAuth[$this->settings['userModel']][$parentModelAlias] = $roles; // or USER_ROLE_KEY
  183. //pr($completeAuth);
  184. }
  185. } else {
  186. //$completeAuth[$this->settings['userModel']][$parentModelAlias][] = $completeAuth[$this->settings['userModel']]['role_id'];
  187. }
  188. }
  189. # deprecated!
  190. if (isset($Model->hasOne['UserInfo'])) {
  191. $with = $Model->hasOne['UserInfo']['className'];
  192. list($plugin, $withModel) = pluginSplit($with);
  193. if (!isset($this->{$withModel})) {
  194. $this->{$withModel} = ClassRegistry::init($with);
  195. }
  196. $infos = $this->{$withModel}->find('first', array('fields' => array(), 'conditions' => array($withModel.'.id' => $user['id'])));
  197. $completeAuth[$this->settings['userModel']][USER_INFO_KEY] = array(); # default: no rights!
  198. if (!empty($infos)) {
  199. $completeAuth[$this->settings['userModel']][USER_INFO_KEY] = $infos[$with];
  200. //pr($completeAuth);
  201. }
  202. }
  203. # deprecated!
  204. if (isset($Model->hasOne['UserRight'])) {
  205. $with = $Model->hasOne['UserRight']['className'];
  206. list($plugin, $withModel) = pluginSplit($with);
  207. if (!isset($this->{$withModel})) {
  208. $this->{$withModel} = ClassRegistry::init($with);
  209. }
  210. $rights = $this->{$withModel}->find('first', array('fields' => array(), 'conditions' => array($withModel.'.id' => $user['id'])));
  211. $completeAuth[$this->settings['userModel']][USER_RIGHT_KEY] = array(); # default: no rights!
  212. if (!empty($rights)) {
  213. // add the suplemental roles id under the Auth session key
  214. $completeAuth[$this->settings['userModel']][USER_RIGHT_KEY] = $rights[$with];
  215. //pr($completeAuth);
  216. }
  217. }
  218. if (method_exists($Model, 'completeAuth')) {
  219. $completeAuth = $Model->completeAuth($completeAuth);
  220. return $completeAuth[$this->settings['userModel']];
  221. }
  222. return $completeAuth[$this->settings['userModel']];
  223. }
  224. /**
  225. * Main execution method. Handles redirecting of invalid users, and processing
  226. * of login form data.
  227. *
  228. * @param Controller $controller A reference to the instantiating controller object
  229. * @return boolean
  230. */
  231. public function startup(Controller $controller) {
  232. //parent::startup($controller);
  233. if ($controller->name === 'CakeError') {
  234. return true;
  235. }
  236. $methods = array_flip(array_map('strtolower', $controller->methods));
  237. # fix: reverse camelCase first
  238. $action = strtolower(Inflector::underscore($controller->request->params['action']));
  239. $isMissingAction = (
  240. $controller->scaffold === false &&
  241. !isset($methods[$action])
  242. );
  243. if ($isMissingAction) {
  244. return true;
  245. }
  246. if (!$this->_setDefaults()) {
  247. return false;
  248. }
  249. $request = $controller->request;
  250. $url = '';
  251. if (isset($request->url)) {
  252. $url = $request->url;
  253. }
  254. $url = Router::normalize($url);
  255. $loginAction = Router::normalize($this->loginAction);
  256. $allowedActions = $this->allowedActions;
  257. $isAllowed = (
  258. $this->allowedActions == array('*') ||
  259. in_array($action, array_map('strtolower', $allowedActions))
  260. );
  261. if ($loginAction != $url && $isAllowed) {
  262. return true;
  263. }
  264. if ($loginAction == $url) {
  265. if (empty($request->data)) {
  266. if (!$this->Session->check('Auth.redirect') && !$this->loginRedirect && env('HTTP_REFERER')) {
  267. $this->Session->write('Auth.redirect', $controller->referer(null, true));
  268. }
  269. }
  270. return true;
  271. } else {
  272. if (!$this->_getUser()) {
  273. if (!$request->is('ajax')) {
  274. $this->flash($this->authError);
  275. $this->Session->write('Auth.redirect', $request->here());
  276. $controller->redirect($loginAction);
  277. return false;
  278. } elseif (!empty($this->ajaxLogin)) {
  279. $controller->viewPath = 'Elements';
  280. echo $controller->render($this->ajaxLogin, $this->RequestHandler->ajaxLayout);
  281. $this->_stop();
  282. return false;
  283. } else {
  284. $controller->redirect(null, 403);
  285. }
  286. }
  287. }
  288. if (empty($this->authorize) || $this->isAuthorized($this->user())) {
  289. return true;
  290. }
  291. $this->flash($this->authError);
  292. $default = '/';
  293. if (!empty($this->loginRedirect)) {
  294. $default = $this->loginRedirect;
  295. }
  296. $controller->redirect($controller->referer($default), null, true);
  297. return false;
  298. }
  299. /**
  300. * @deprecated
  301. * @return bool $success
  302. */
  303. public function verifyUser($id, $pwd) {
  304. trigger_error('deprecated - use Authenticate class');
  305. $options = array(
  306. 'conditions' => array('id'=>$id, 'password'=>$this->password($pwd)),
  307. );
  308. return $this->getModel()->find('first', $options);
  309. $this->constructAuthenticate();
  310. $this->request->data['User']['password'] = $pwd;
  311. return $this->identify($this->request, $this->response);
  312. }
  313. /**
  314. * returns the current User model
  315. * @return object $User
  316. */
  317. public function getModel() {
  318. $model = $this->settings['userModel'];
  319. return ClassRegistry::init($model);
  320. }
  321. }