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