AuthExtComponent.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. <?php
  2. if (!defined('USER_ROLE_KEY')) {
  3. define('USER_ROLE_KEY', 'Role');
  4. }
  5. if (!defined('CLASS_USER')) {
  6. define('CLASS_USER', 'User');
  7. }
  8. App::uses('AuthComponent', 'Controller/Component');
  9. /**
  10. * Important:
  11. * index the ACO on alias, index the Aro on model+id
  12. *
  13. * Extends AuthComponent with the following addons:
  14. * - allows multiple roles per user
  15. * - auto-raises login counter and sets last_login date
  16. * - preps the session data according to completeAuth() method (adds parent data etc)
  17. * - dynamic login scope validation
  18. *
  19. * @author Mark Scherer
  20. * @cakephp 2.x
  21. * @license MIT
  22. */
  23. class AuthExtComponent extends AuthComponent {
  24. public $intermediateModel = 'RoleUser';
  25. public $roleModel = 'Role';
  26. public $fieldKey = 'role_id';
  27. public $loginAction = array('controller' => 'account', 'action' => 'login', 'admin' => false, 'plugin' => false);
  28. public $loginRedirect = array('controller' => 'overview', 'action' => 'home', 'admin' => false, 'plugin' => false);
  29. public $autoRedirect = false;
  30. public $loginError = null;
  31. public $settings = array(
  32. 'multi' => null, # null=auto - yes/no multiple roles (HABTM table between users and roles)
  33. 'parentModelAlias' => USER_ROLE_KEY,
  34. 'userModel' => CLASS_USER //TODO: allow plugin syntax
  35. );
  36. # field name in DB , if none is specified there will be no floodProtection
  37. public $floodProtection = null;
  38. /**
  39. * Merge in Configure::read('Auth') settings
  40. *
  41. * @param mixed $Collection
  42. * @param mixed $settings
  43. * @return void
  44. */
  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. * AuthExtComponent::login()
  55. *
  56. * @overwrite
  57. * @param mixed $user
  58. * @return boolean Success
  59. */
  60. public function login($user = null) {
  61. $Model = $this->getModel();
  62. $this->_setDefaults();
  63. if (empty($user)) {
  64. $user = $this->identify($this->Controller->request, $this->Controller->response);
  65. }
  66. $user = $this->completeAuth($user);
  67. if (empty($user)) {
  68. $this->loginError = __('invalidLoginCredentials');
  69. return false;
  70. }
  71. # custom checks
  72. if (isset($user['active'])) {
  73. if (empty($user['active'])) {
  74. $this->loginError = __('Account not active yet');
  75. return false;
  76. }
  77. if (!empty($user['suspended'])) {
  78. $this->loginError = __('Account wurde vorübergehend gesperrt');
  79. if (!empty($user['suspended_reason'])) {
  80. $this->loginError .= BR . BR . 'Grund:' . BR . nl2br(h($user['suspended_reason']));
  81. }
  82. return false;
  83. }
  84. } else {
  85. if (isset($user['status']) && empty($user['status'])) {
  86. $this->loginError = __('Account not active yet');
  87. return false;
  88. }
  89. if (isset($user['status']) && defined('User::STATUS_PENDING') && $user['status'] == User::STATUS_PENDING) {
  90. $this->loginError = __('Account wurde noch nicht freigeschalten');
  91. return false;
  92. }
  93. if (isset($user['status']) && defined('User::STATUS_SUSPENDED') && $user['status'] == User::STATUS_SUSPENDED) {
  94. $this->loginError = 'Account wurde vorübergehend gesperrt';
  95. if (!empty($user['suspended_reason'])) {
  96. $this->loginError .= BR . BR . 'Grund:' . BR . nl2br(h($user['suspended_reason']));
  97. }
  98. return false;
  99. }
  100. if (isset($user['status']) && defined('User::STATUS_DEL') && $user['status'] == User::STATUS_DEL) {
  101. $this->loginError = 'Account wurde gelöscht';
  102. if (!empty($user['suspended_reason'])) {
  103. $this->loginError .= BR . BR . 'Grund:' . BR . nl2br(h($user['suspended_reason']));
  104. }
  105. return false;
  106. }
  107. if (isset($user['status']) && defined('User::STATUS_ACTIVE') && $user['status'] != User::STATUS_ACTIVE) {
  108. $this->loginError = __('Unknown Error');
  109. return false;
  110. }
  111. }
  112. if (isset($user['email_confirmed']) && empty($user['email_confirmed'])) {
  113. $this->loginError = __('Email not active yet');
  114. return false;
  115. }
  116. if ($user) {
  117. # update login counter
  118. if (isset($user['logins'])) {
  119. $user['logins'] = $user['logins'] + 1;
  120. if (method_exists($Model, 'loginUpdate')) {
  121. $Model->loginUpdate($user);
  122. }
  123. }
  124. $this->Session->renew();
  125. $this->Session->write(self::$sessionKey, $user);
  126. }
  127. return $this->loggedIn();
  128. }
  129. /**
  130. * Gather session data.
  131. *
  132. * @return array User
  133. */
  134. public function completeAuth($user) {
  135. $Model = $this->getModel();
  136. $userArray = $user;
  137. if (!is_array($userArray)) {
  138. $user = $Model->get($user);
  139. if (!$user) {
  140. return array();
  141. }
  142. $userArray = array_shift($user);
  143. }
  144. if (isset($Model->hasAndBelongsToMany[$this->roleModel]['className'])) {
  145. $with = $Model->hasAndBelongsToMany[$this->roleModel]['className'];
  146. } elseif (isset($Model->hasMany[$this->intermediateModel]['className'])) {
  147. $with = $Model->hasMany[$this->intermediateModel]['className'];
  148. } elseif (isset($Model->belongsTo[$this->roleModel]['className'])) {
  149. $with = $Model->belongsTo[$this->roleModel]['className'];
  150. }
  151. if (empty($with) && $this->settings['parentModelAlias'] !== false) {
  152. trigger_error('No relation from user to role found');
  153. return $user;
  154. }
  155. # roles
  156. if (!empty($with)) {
  157. list($plugin, $withModel) = pluginSplit($with);
  158. if (!isset($this->{$withModel})) {
  159. $this->{$withModel} = ClassRegistry::init($with);
  160. }
  161. # only for multi
  162. if ($this->settings['multi'] || !isset($userArray['role_id'])) {
  163. $parentModelAlias = $this->settings['parentModelAlias'];
  164. $userArray[$parentModelAlias] = array(); # default: no roles!
  165. $roles = $this->{$withModel}->find('list', array('fields' => array($withModel.'.role_id'), 'conditions' => array($withModel.'.user_id' => $user['id'])));
  166. if (!empty($roles)) {
  167. //$primaryRole = $this->user($this->fieldKey);
  168. // retrieve associated role that are not the primary one
  169. # MAYBE USEFUL FOR GUEST!!!
  170. //$roles = set::extract('/'.$with.'['.$this->fieldKey.'!='.$primaryRole.']/'.$this->fieldKey, $roles);
  171. // add the suplemental roles id under the Auth session key
  172. $userArray[$parentModelAlias] = $roles;
  173. //pr($completeAuth);
  174. }
  175. } else {
  176. //$userArray[$parentModelAlias][] = $userArray['role_id'];
  177. }
  178. }
  179. if (method_exists($Model, 'completeAuth')) {
  180. $userArray = $Model->completeAuth($userArray);
  181. }
  182. return $userArray;
  183. }
  184. /**
  185. * Main execution method. Handles redirecting of invalid users, and processing
  186. * of login form data.
  187. *
  188. * @overwrite
  189. * @param Controller $controller A reference to the instantiating controller object
  190. * @return boolean
  191. */
  192. public function startup(Controller $controller) {
  193. if ($controller->name === 'CakeError') {
  194. return true;
  195. }
  196. $methods = array_flip(array_map('strtolower', $controller->methods));
  197. # fix: reverse camelCase first
  198. $action = strtolower(Inflector::underscore($controller->request->params['action']));
  199. $isMissingAction = (
  200. $controller->scaffold === false &&
  201. !isset($methods[$action])
  202. );
  203. if ($isMissingAction) {
  204. return true;
  205. }
  206. if (!$this->_setDefaults()) {
  207. return false;
  208. }
  209. if ($this->_isAllowed($controller)) {
  210. return true;
  211. }
  212. if (!$this->_getUser()) {
  213. return $this->_unauthenticated($controller);
  214. }
  215. if (empty($this->authorize) || $this->isAuthorized($this->user())) {
  216. return true;
  217. }
  218. return $this->_unauthorized($controller);
  219. }
  220. /**
  221. * Returns the current User model
  222. *
  223. * @return object User
  224. */
  225. public function getModel() {
  226. $model = $this->settings['userModel'];
  227. return ClassRegistry::init($model);
  228. }
  229. /**
  230. * @deprecated
  231. * @return boolean Success
  232. */
  233. public function verifyUser($id, $pwd) {
  234. trigger_error('deprecated - use Authenticate class');
  235. $options = array(
  236. 'conditions' => array('id' => $id, 'password' => $this->password($pwd)),
  237. );
  238. return $this->getModel()->find('first', $options);
  239. $this->constructAuthenticate();
  240. $this->request->data['User']['password'] = $pwd;
  241. return $this->identify($this->request, $this->response);
  242. }
  243. }