ChangePasswordBehavior.php 9.0 KB

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