AuthExtComponent.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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
  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. //$this->Controller = $Collection->getController();
  48. parent::__construct($Collection, $settings);
  49. }
  50. public function initialize(Controller $Controller) {
  51. $this->Controller = $Controller;
  52. parent::initialize($Controller);
  53. }
  54. /**
  55. * 2.1 fix for allowing * as wildcard (tmp solution)
  56. * 2012-01-10 ms
  57. */
  58. public function allow($action = null) {
  59. if (((array)$action) === array('*')) {
  60. parent::allow();
  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. }
  75. if (empty($user)) {
  76. $this->loginError = __('invalidLoginCredentials');
  77. return false;
  78. }
  79. # custom checks
  80. if (isset($user['active'])) {
  81. if (empty($user['active'])) {
  82. $this->loginError = __('Account not active yet');
  83. return false;
  84. }
  85. if (!empty($user['suspended'])) {
  86. $this->loginError = __('Account wurde vorübergehend gesperrt');
  87. if (!empty($user['suspended_reason'])) {
  88. $this->loginError .= BR . BR . 'Grund:' . BR . nl2br(h($user['suspended_reason']));
  89. }
  90. return false;
  91. }
  92. } else {
  93. if (isset($user['status']) && empty($user['status'])) {
  94. $this->loginError = __('Account not active yet');
  95. return false;
  96. }
  97. if (isset($user['status']) && defined('User::STATUS_PENDING') && $user['status'] == User::STATUS_PENDING) {
  98. $this->loginError = __('Account wurde noch nicht freigeschalten');
  99. return false;
  100. }
  101. if (isset($user['status']) && defined('User::STATUS_SUSPENDED') && $user['status'] == User::STATUS_SUSPENDED) {
  102. $this->loginError = 'Account wurde vorübergehend gesperrt';
  103. if (!empty($user['suspended_reason'])) {
  104. $this->loginError .= BR . BR . 'Grund:' . BR . nl2br(h($user['suspended_reason']));
  105. }
  106. return false;
  107. }
  108. if (isset($user['status']) && defined('User::STATUS_DEL') && $user['status'] == User::STATUS_DEL) {
  109. $this->loginError = 'Account wurde gelöscht';
  110. if (!empty($user['suspended_reason'])) {
  111. $this->loginError .= BR . BR . 'Grund:' . BR . nl2br(h($user['suspended_reason']));
  112. }
  113. return false;
  114. }
  115. if (isset($user['status']) && defined('User::STATUS_ACTIVE') && $user['status'] != User::STATUS_ACTIVE) {
  116. $this->loginError = __('Unknown Error');
  117. return false;
  118. }
  119. }
  120. if (isset($user['email_confirmed']) && empty($user['email_confirmed'])) {
  121. $this->loginError = __('Email not active yet');
  122. return false;
  123. }
  124. if ($user) {
  125. # update login counter
  126. if (isset($user['logins'])) {
  127. $user['logins'] = $user['logins'] + 1;
  128. if (method_exists($Model, 'loginUpdate')) {
  129. $Model->loginUpdate($user);
  130. }
  131. }
  132. $this->Session->renew();
  133. $this->Session->write(self::$sessionKey, $user);
  134. $this->Session->write(self::$sessionKey, $this->completeAuth($user));
  135. }
  136. return $this->loggedIn();
  137. }
  138. /**
  139. * return array $user or bool false on failure
  140. * 2011-11-03 ms
  141. */
  142. public function completeAuth($user) {
  143. $Model = $this->getModel();
  144. if (!is_array($user)) {
  145. $user = $Model->get($user);
  146. if (!$user) {
  147. return false;
  148. }
  149. $user = array_shift($user);
  150. }
  151. if (isset($Model->hasMany[$this->intermediateModel]['className'])) {
  152. $with = $Model->hasMany[$this->intermediateModel]['className'];
  153. } elseif (isset($Model->belongsTo[$this->roleModel]['className'])) {
  154. $with = $Model->belongsTo[$this->roleModel]['className'];
  155. }
  156. if (empty($with) && $this->settings['parentModelAlias'] !== false) {
  157. trigger_error('No relation from user to role found');
  158. return false;
  159. }
  160. $completeAuth = array($this->settings['userModel']=>$user);
  161. # roles
  162. if (!empty($with)) {
  163. list($plugin, $withModel) = pluginSplit($with);
  164. if (!isset($this->{$withModel})) {
  165. $this->{$withModel} = ClassRegistry::init($with);
  166. }
  167. # only for multi
  168. if ($this->settings['multi'] || !isset($completeAuth[$this->settings['userModel']]['role_id'])) {
  169. $parentModelAlias = $this->settings['parentModelAlias'];
  170. $completeAuth[$this->settings['userModel']][$parentModelAlias] = array(); # default: no roles!
  171. $roles = $this->{$withModel}->find('list', array('fields' => array($withModel.'.role_id'), 'conditions' => array($withModel.'.user_id' => $user['id'])));
  172. if (!empty($roles)) {
  173. //$primaryRole = $this->user($this->fieldKey);
  174. // retrieve associated role that are not the primary one
  175. # MAYBE USEFUL FOR GUEST!!!
  176. //$roles = set::extract('/'.$with.'['.$this->fieldKey.'!='.$primaryRole.']/'.$this->fieldKey, $roles);
  177. // add the suplemental roles id under the Auth session key
  178. $completeAuth[$this->settings['userModel']][$parentModelAlias] = $roles; // or USER_ROLE_KEY
  179. //pr($completeAuth);
  180. }
  181. } else {
  182. //$completeAuth[$this->settings['userModel']][$parentModelAlias][] = $completeAuth[$this->settings['userModel']]['role_id'];
  183. }
  184. }
  185. # deprecated!
  186. if (isset($Model->hasOne['UserInfo'])) {
  187. $with = $Model->hasOne['UserInfo']['className'];
  188. list($plugin, $withModel) = pluginSplit($with);
  189. if (!isset($this->{$withModel})) {
  190. $this->{$withModel} = ClassRegistry::init($with);
  191. }
  192. $infos = $this->{$withModel}->find('first', array('fields' => array(), 'conditions' => array($withModel.'.id' => $user['id'])));
  193. $completeAuth[$this->settings['userModel']][USER_INFO_KEY] = array(); # default: no rights!
  194. if (!empty($infos)) {
  195. $completeAuth[$this->settings['userModel']][USER_INFO_KEY] = $infos[$with];
  196. //pr($completeAuth);
  197. }
  198. }
  199. # deprecated!
  200. if (isset($Model->hasOne['UserRight'])) {
  201. $with = $Model->hasOne['UserRight']['className'];
  202. list($plugin, $withModel) = pluginSplit($with);
  203. if (!isset($this->{$withModel})) {
  204. $this->{$withModel} = ClassRegistry::init($with);
  205. }
  206. $rights = $this->{$withModel}->find('first', array('fields' => array(), 'conditions' => array($withModel.'.id' => $user['id'])));
  207. $completeAuth[$this->settings['userModel']][USER_RIGHT_KEY] = array(); # default: no rights!
  208. if (!empty($rights)) {
  209. // add the suplemental roles id under the Auth session key
  210. $completeAuth[$this->settings['userModel']][USER_RIGHT_KEY] = $rights[$with];
  211. //pr($completeAuth);
  212. }
  213. }
  214. if (method_exists($Model, 'completeAuth')) {
  215. $completeAuth = $Model->completeAuth($completeAuth);
  216. return $completeAuth[$this->settings['userModel']];
  217. }
  218. return $completeAuth[$this->settings['userModel']];
  219. }
  220. /**
  221. * Main execution method. Handles redirecting of invalid users, and processing
  222. * of login form data.
  223. *
  224. * @param Controller $controller A reference to the instantiating controller object
  225. * @return boolean
  226. */
  227. public function startup(Controller $controller) {
  228. //parent::startup($controller);
  229. if ($controller->name == 'CakeError') {
  230. return true;
  231. }
  232. $methods = array_flip(array_map('strtolower', $controller->methods));
  233. # fix: reverse camelCase first
  234. $action = strtolower(Inflector::underscore($controller->request->params['action']));
  235. $isMissingAction = (
  236. $controller->scaffold === false &&
  237. !isset($methods[$action])
  238. );
  239. if ($isMissingAction) {
  240. return true;
  241. }
  242. if (!$this->_setDefaults()) {
  243. return false;
  244. }
  245. $request = $controller->request;
  246. $url = '';
  247. if (isset($request->url)) {
  248. $url = $request->url;
  249. }
  250. $url = Router::normalize($url);
  251. $loginAction = Router::normalize($this->loginAction);
  252. $allowedActions = $this->allowedActions;
  253. $isAllowed = (
  254. $this->allowedActions == array('*') ||
  255. in_array($action, array_map('strtolower', $allowedActions))
  256. );
  257. if ($loginAction != $url && $isAllowed) {
  258. return true;
  259. }
  260. if ($loginAction == $url) {
  261. if (empty($request->data)) {
  262. if (!$this->Session->check('Auth.redirect') && !$this->loginRedirect && env('HTTP_REFERER')) {
  263. $this->Session->write('Auth.redirect', $controller->referer(null, true));
  264. }
  265. }
  266. return true;
  267. } else {
  268. if (!$this->_getUser()) {
  269. if (!$request->is('ajax')) {
  270. $this->flash($this->authError);
  271. $this->Session->write('Auth.redirect', $request->here());
  272. $controller->redirect($loginAction);
  273. return false;
  274. } elseif (!empty($this->ajaxLogin)) {
  275. $controller->viewPath = 'Elements';
  276. echo $controller->render($this->ajaxLogin, $this->RequestHandler->ajaxLayout);
  277. $this->_stop();
  278. return false;
  279. } else {
  280. $controller->redirect(null, 403);
  281. }
  282. }
  283. }
  284. if (empty($this->authorize) || $this->isAuthorized($this->user())) {
  285. return true;
  286. }
  287. $this->flash($this->authError);
  288. $default = '/';
  289. if (!empty($this->loginRedirect)) {
  290. $default = $this->loginRedirect;
  291. }
  292. $controller->redirect($controller->referer($default), null, true);
  293. return false;
  294. }
  295. /**
  296. * Quickfix
  297. * TODO: improve - maybe use Authenticate
  298. * @deprecated
  299. * @return bool $success
  300. */
  301. public function verifyUser($id, $pwd) {
  302. //trigger_error('deprecated - use Authenticate class');
  303. $options = array(
  304. 'conditions' => array('id'=>$id, 'password'=>$this->password($pwd)),
  305. );
  306. return $this->getModel()->find('first', $options);
  307. $this->constructAuthenticate();
  308. $this->request->data['User']['password'] = $pwd;
  309. return $this->identify($this->request, $this->response);
  310. }
  311. /**
  312. * returns the current User model
  313. * @return object $User
  314. */
  315. public function getModel() {
  316. return ClassRegistry::init(CLASS_USER);
  317. }
  318. }