AuthExtComponent.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. */
  44. public function __construct(ComponentCollection $Collection, $settings = array()) {
  45. $settings = array_merge($this->settings, (array)Configure::read('Auth'), (array)$settings);
  46. parent::__construct($Collection, $settings);
  47. }
  48. public function initialize(Controller $Controller) {
  49. $this->Controller = $Controller;
  50. parent::initialize($Controller);
  51. }
  52. /**
  53. * AuthExtComponent::login()
  54. *
  55. * @overwrite
  56. * @param mixed $user
  57. * @return boolean Success
  58. */
  59. public function login($user = null) {
  60. $Model = $this->getModel();
  61. $this->_setDefaults();
  62. if (empty($user)) {
  63. $user = $this->identify($this->Controller->request, $this->Controller->response);
  64. }
  65. $user = $this->completeAuth($user);
  66. if (empty($user)) {
  67. $this->loginError = __('invalidLoginCredentials');
  68. return false;
  69. }
  70. // custom checks
  71. if (isset($user['active'])) {
  72. if (empty($user['active'])) {
  73. $this->loginError = __('Account not active yet');
  74. return false;
  75. }
  76. if (!empty($user['suspended'])) {
  77. $this->loginError = __('Account temporarily locked');
  78. if (!empty($user['suspended_reason'])) {
  79. $this->loginError .= BR . BR . __('Reason') . ':' . BR . nl2br(h($user['suspended_reason']));
  80. }
  81. return false;
  82. }
  83. } else {
  84. if (isset($user['status']) && empty($user['status'])) {
  85. $this->loginError = __('Account not active yet');
  86. return false;
  87. }
  88. if (isset($user['status']) && defined('User::STATUS_PENDING') && $user['status'] == User::STATUS_PENDING) {
  89. $this->loginError = __('Account not active yet');
  90. return false;
  91. }
  92. if (isset($user['status']) && defined('User::STATUS_SUSPENDED') && $user['status'] == User::STATUS_SUSPENDED) {
  93. $this->loginError = __('Account temporarily locked');
  94. if (!empty($user['suspended_reason'])) {
  95. $this->loginError .= BR . BR . __('Reason') . ':' . BR . nl2br(h($user['suspended_reason']));
  96. }
  97. return false;
  98. }
  99. if (isset($user['status']) && defined('User::STATUS_DEL') && $user['status'] == User::STATUS_DEL) {
  100. $this->loginError = __('Account deleted');
  101. if (!empty($user['suspended_reason'])) {
  102. $this->loginError .= BR . BR . __('Reason') . ':' . BR . nl2br(h($user['suspended_reason']));
  103. }
  104. return false;
  105. }
  106. if (isset($user['status']) && defined('User::STATUS_ACTIVE') && $user['status'] != User::STATUS_ACTIVE) {
  107. $this->loginError = __('Unknown Error');
  108. return false;
  109. }
  110. }
  111. if (isset($user['email_confirmed']) && empty($user['email_confirmed'])) {
  112. $this->loginError = __('Email not active yet');
  113. return false;
  114. }
  115. if ($user) {
  116. // update login counter
  117. if (isset($user['logins'])) {
  118. $user['logins'] = $user['logins'] + 1;
  119. if (method_exists($Model, 'loginUpdate')) {
  120. $Model->loginUpdate($user);
  121. }
  122. }
  123. $this->Session->renew();
  124. $this->Session->write(self::$sessionKey, $user);
  125. }
  126. return $this->loggedIn();
  127. }
  128. /**
  129. * Gather session data.
  130. *
  131. * @return array User
  132. */
  133. public function completeAuth($user) {
  134. $Model = $this->getModel();
  135. $userArray = $user;
  136. if (!is_array($userArray)) {
  137. $user = $Model->get($user);
  138. if (!$user) {
  139. return array();
  140. }
  141. $userArray = array_shift($user);
  142. }
  143. if (isset($Model->hasAndBelongsToMany[$this->roleModel]['className'])) {
  144. $with = $Model->hasAndBelongsToMany[$this->roleModel]['className'];
  145. } elseif (isset($Model->hasMany[$this->intermediateModel]['className'])) {
  146. $with = $Model->hasMany[$this->intermediateModel]['className'];
  147. } elseif (isset($Model->belongsTo[$this->roleModel]['className'])) {
  148. $with = $Model->belongsTo[$this->roleModel]['className'];
  149. }
  150. if (empty($with) && $this->settings['parentModelAlias'] !== false) {
  151. trigger_error('No relation from user to role found');
  152. return $user;
  153. }
  154. // roles
  155. if (!empty($with)) {
  156. list($plugin, $withModel) = pluginSplit($with);
  157. if (!isset($this->{$withModel})) {
  158. $this->{$withModel} = ClassRegistry::init($with);
  159. }
  160. // only for multi
  161. if ($this->settings['multi'] || !isset($userArray['role_id'])) {
  162. $parentModelAlias = $this->settings['parentModelAlias'];
  163. $userArray[$parentModelAlias] = array(); # default: no roles!
  164. $roles = $this->{$withModel}->find('list', array('fields' => array($withModel . '.role_id'), 'conditions' => array($withModel . '.user_id' => $userArray['id'])));
  165. if (!empty($roles)) {
  166. //$primaryRole = $this->user($this->fieldKey);
  167. // retrieve associated role that are not the primary one
  168. // MAYBE USEFUL FOR GUEST!!!
  169. //$roles = set::extract('/'.$with.'['.$this->fieldKey.'!='.$primaryRole.']/'.$this->fieldKey, $roles);
  170. // add the suplemental roles id under the Auth session key
  171. $userArray[$parentModelAlias] = $roles;
  172. //pr($completeAuth);
  173. }
  174. } else {
  175. //$userArray[$parentModelAlias][] = $userArray['role_id'];
  176. }
  177. }
  178. if (method_exists($Model, 'completeAuth')) {
  179. $userArray = $Model->completeAuth($userArray);
  180. }
  181. return $userArray;
  182. }
  183. /**
  184. * Main execution method. Handles redirecting of invalid users, and processing
  185. * of login form data.
  186. *
  187. * @overwrite
  188. * @param Controller $controller A reference to the instantiating controller object
  189. * @return boolean
  190. */
  191. public function startup(Controller $controller) {
  192. if ($controller->name === 'CakeError') {
  193. return true;
  194. }
  195. $methods = array_flip(array_map('strtolower', $controller->methods));
  196. // fix: reverse camelCase first
  197. $action = strtolower(Inflector::underscore($controller->request->params['action']));
  198. $isMissingAction = (
  199. $controller->scaffold === false &&
  200. !isset($methods[$action])
  201. );
  202. if ($isMissingAction) {
  203. return true;
  204. }
  205. if (!$this->_setDefaults()) {
  206. return false;
  207. }
  208. if ($this->_isAllowed($controller)) {
  209. return true;
  210. }
  211. if (!$this->_getUser()) {
  212. return $this->_unauthenticated($controller);
  213. }
  214. if (empty($this->authorize) || $this->isAuthorized($this->user())) {
  215. return true;
  216. }
  217. return $this->_unauthorized($controller);
  218. }
  219. /**
  220. * Returns the current User model
  221. *
  222. * @return object User
  223. */
  224. public function getModel() {
  225. $model = $this->settings['userModel'];
  226. return ClassRegistry::init($model);
  227. }
  228. /**
  229. * @deprecated
  230. * @return boolean Success
  231. */
  232. public function verifyUser($id, $pwd) {
  233. trigger_error('deprecated - use Authenticate class');
  234. $options = array(
  235. 'conditions' => array('id' => $id, 'password' => $this->password($pwd)),
  236. );
  237. return $this->getModel()->find('first', $options);
  238. $this->constructAuthenticate();
  239. $this->request->data['User']['password'] = $pwd;
  240. return $this->identify($this->request, $this->response);
  241. }
  242. }