ChangePasswordBehavior.php 8.9 KB

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