ChangePasswordBehavior.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. <?php
  2. App::uses('CakeResponse', 'Network');
  3. App::uses('Security', 'Utility');
  4. /**
  5. * Copyright 2011, Mark Scherer
  6. *
  7. * Licensed under The MIT License
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @version 1.4
  11. * @license http://www.opensource.org/licenses/mit-license.php The MIT License
  12. */
  13. if (!defined('PWD_MIN_LENGTH')) {
  14. define('PWD_MIN_LENGTH', 3);
  15. }
  16. if (!defined('PWD_MAX_LENGTH')) {
  17. define('PWD_MAX_LENGTH', 20);
  18. }
  19. /**
  20. * A cakephp2 behavior to change passwords the easy way
  21. * - complete validation
  22. * - hashing of password
  23. * - requires fields (no tempering even without security component)
  24. *
  25. * usage: do NOT add it via $actAs = array()
  26. * attach it dynamically in only those actions where you actually change the password like so:
  27. * $this->User->Behaviors->attach('Tools.ChangePassword', array(SETTINGSARRAY));
  28. * as first line in any action where you want to allow the user to change his password
  29. * also add the two form fields in the form (pwd, pwd_confirm)
  30. * the rest is cake automagic :)
  31. *
  32. * now also is capable of:
  33. * - require current password prior to altering it (current=>true)
  34. * - don't allow the same password it was before (allowSame=>false)
  35. *
  36. * TODO: allowEmpty and nonEmptyToEmpty - maybe with checkbox "set_new_pwd"
  37. * feel free to help me out
  38. *
  39. * 2011-08-24 ms
  40. */
  41. class ChangePasswordBehavior extends ModelBehavior {
  42. public $settings = array();
  43. /**
  44. * @access protected
  45. */
  46. public $_defaultSettings = array(
  47. 'field' => 'password',
  48. 'confirm' => true, # set to false if in admin view and no confirmation (pwd_repeat) is required
  49. 'allowEmpty' => false,
  50. 'current' => false, # expect the current password for security purposes
  51. 'formField' => 'pwd',
  52. 'formFieldRepeat' => 'pwd_repeat',
  53. 'formFieldCurrent' => 'pwd_current',
  54. 'hashType' => null,
  55. 'hashSalt' => true,
  56. 'auth' => 'Auth', # which component,
  57. 'allowSame' => true, # dont allow the old password on change
  58. 'nonEmptyToEmpty' => false, # allow resetting nonempty pwds to empty once set (prevents problems with default edit actions)
  59. );
  60. public $_validationRules = array(
  61. 'formField' => array(
  62. 'between' => array(
  63. 'rule' => array('between', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  64. 'message' => array('valErrBetweenCharacters %s %s', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  65. 'last' => true,
  66. )
  67. ),
  68. 'formFieldRepeat' => array(
  69. 'between' => array(
  70. 'rule' => array('between', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  71. 'message' => array('valErrBetweenCharacters %s %s', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  72. 'last' => true,
  73. ),
  74. 'validateIdentical' => array(
  75. 'rule' => array('validateIdentical', 'formField'),
  76. 'message' => 'valErrPwdNotMatch',
  77. 'last' => true,
  78. ),
  79. ),
  80. 'formFieldCurrent' => array(
  81. 'notEmpty' => array(
  82. 'rule' => array('notEmpty'),
  83. 'message' => 'valErrProvideCurrentPwd',
  84. 'last' => true,
  85. ),
  86. 'validateCurrentPwd' => array(
  87. 'rule' => 'validateCurrentPwd',
  88. 'message' => 'valErrCurrentPwdIncorrect',
  89. 'last' => true,
  90. )
  91. ),
  92. );
  93. /**
  94. * if not implemented in AppModel
  95. * @throws CakeException
  96. * @return bool $success
  97. * 2011-07-22 ms
  98. */
  99. public function validateCurrentPwd(Model $Model, $data) {
  100. if (is_array($data)) {
  101. $pwd = array_shift($data);
  102. } else {
  103. $pwd = $data;
  104. }
  105. $uid = null;
  106. if ($Model->id) {
  107. $uid = $Model->id;
  108. } elseif (!empty($Model->data[$Model->alias]['id'])) {
  109. $uid = $Model->data[$Model->alias]['id'];
  110. } else {
  111. trigger_error('No user id given');
  112. return false;
  113. }
  114. if (class_exists('AuthExtComponent')) {
  115. $this->Auth = new AuthExtComponent(new ComponentCollection());
  116. } elseif (class_exists($this->settings[$Model->alias]['auth'].'Component')) {
  117. $auth = $this->settings[$Model->alias]['auth'].'Component';
  118. $this->Auth = new $auth(new ComponentCollection());
  119. } else {
  120. throw new CakeException('No validation class found');
  121. }
  122. # easiest authenticate method via form and (id + pwd)
  123. $this->Auth->authenticate = array('Form'=>array('fields'=>array('username' => 'id', 'password'=>$this->settings[$Model->alias]['field'])));
  124. $request = new CakeRequest(null, false);
  125. $request->data['User'] = array('id'=>$uid, 'password'=>$pwd);
  126. $response = new CakeResponse();
  127. return $this->Auth->identify($request, $response);
  128. }
  129. /**
  130. * if not implemented in AppModel
  131. * @return bool $success
  132. * 2011-07-22 ms
  133. */
  134. public function validateIdentical(Model $Model, $data, $compareWith = null) {
  135. if (is_array($data)) {
  136. $value = array_shift($data);
  137. } else {
  138. $value = $data;
  139. }
  140. $compareValue = $Model->data[$Model->alias][$compareWith];
  141. return ($compareValue == $value);
  142. }
  143. /**
  144. * if not implemented in AppModel
  145. * @return bool $success
  146. * 2011-11-10 ms
  147. */
  148. public function validateNotSame(Model $Model, $data, $field1, $field2) {
  149. $value1 = $Model->data[$Model->alias][$field1];
  150. $value2 = $Model->data[$Model->alias][$field2];
  151. return ($value1 != $value2);
  152. }
  153. /**
  154. * adding validation rules
  155. * also adds and merges config settings (direct + configure)
  156. * 2011-08-24 ms
  157. */
  158. public function setup(Model $Model, $config = array()) {
  159. $defaults = $this->_defaultSettings;
  160. if ($configureDefaults = Configure::read('ChangePassword')) {
  161. $defaults = Set::merge($defaults, $configureDefaults);
  162. }
  163. $this->settings[$Model->alias] = Set::merge($defaults, $config);
  164. $formField = $this->settings[$Model->alias]['formField'];
  165. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  166. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  167. # add the validation rules if not already attached
  168. if (!isset($Model->validate[$formField])) {
  169. $Model->validate[$formField] = $this->_validationRules['formField'];
  170. }
  171. if (!isset($Model->validate[$formFieldRepeat])) {
  172. $Model->validate[$formFieldRepeat] = $this->_validationRules['formFieldRepeat'];
  173. $Model->validate[$formFieldRepeat]['validateIdentical']['rule'][1] = $formField;
  174. }
  175. if ($this->settings[$Model->alias]['current'] && !isset($Model->validate[$formFieldCurrent])) {
  176. $Model->validate[$formFieldCurrent] = $this->_validationRules['formFieldCurrent'];
  177. if (!$this->settings[$Model->alias]['allowSame']) {
  178. $Model->validate[$formField]['validateNotSame'] = array(
  179. 'rule' => array('validateNotSame', $formField, $formFieldCurrent),
  180. 'message' => 'valErrPwdSameAsBefore',
  181. 'last' => true,
  182. );
  183. }
  184. }
  185. # allowEmpty?
  186. if (!empty($this->settings[$Model->alias]['allowEmpty'])) {
  187. $Model->validate[$formField]['between']['rule'][1] = 0;
  188. }
  189. }
  190. /**
  191. * whitelisting
  192. * 2011-07-22 ms
  193. */
  194. public function beforeValidate(Model $Model) {
  195. # add fields to whitelist!
  196. $whitelist = array($this->settings[$Model->alias]['formField'], $this->settings[$Model->alias]['formFieldRepeat']);
  197. if ($this->settings[$Model->alias]['current']) {
  198. $whitelist[] = $this->settings[$Model->alias]['formFieldCurrent'];
  199. }
  200. if (!empty($Model->whitelist)) {
  201. $Model->whitelist = array_merge($Model->whitelist, $whitelist);
  202. }
  203. # make sure fields are set and validation rules are triggered - prevents tempering of form data
  204. $formField = $this->settings[$Model->alias]['formField'];
  205. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  206. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  207. if (!isset($Model->data[$Model->alias][$formField])) {
  208. $Model->data[$Model->alias][$formField] = '';
  209. }
  210. if ($this->settings[$Model->alias]['confirm'] && !isset($Model->data[$Model->alias][$formFieldRepeat])) {
  211. $Model->data[$Model->alias][$formFieldRepeat] = '';
  212. }
  213. if ($this->settings[$Model->alias]['current'] && !isset($Model->data[$Model->alias][$formFieldCurrent])) {
  214. $Model->data[$Model->alias][$formFieldCurrent] = '';
  215. }
  216. return true;
  217. }
  218. /**
  219. * hashing the password now
  220. * 2011-07-22 ms
  221. */
  222. public function beforeSave(Model $Model) {
  223. $formField = $this->settings[$Model->alias]['formField'];
  224. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  225. $field = $this->settings[$Model->alias]['field'];
  226. $type = $this->settings[$Model->alias]['hashType'];
  227. $salt = $this->settings[$Model->alias]['hashSalt'];
  228. if (empty($Model->data[$Model->alias][$formField]) && !$this->settings[$Model->alias]['nonEmptyToEmpty']) {
  229. # is edit? previous password was "notEmpty"?
  230. if (!empty($Model->data[$Model->alias][$Model->primaryKey]) && ($oldPwd = $Model->field($field, array($Model->alias.'.id'=>$Model->data[$Model->alias][$Model->primaryKey]))) && $oldPwd != Security::hash('', $type, $salt)) {
  231. unset($Model->data[$Model->alias][$formField]);
  232. }
  233. }
  234. if (isset($Model->data[$Model->alias][$formField])) {
  235. $Model->data[$Model->alias][$field] = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  236. unset($Model->data[$Model->alias][$formField]);
  237. if ($this->settings[$Model->alias]['confirm']) {
  238. unset($Model->data[$Model->alias][$formFieldRepeat]);
  239. }
  240. # update whitelist
  241. if (!empty($Model->whitelist)) {
  242. $Model->whitelist = array_merge($Model->whitelist, array($field));
  243. }
  244. }
  245. return true;
  246. }
  247. }