ChangePasswordBehavior.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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.2
  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 cakephp1.3 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. * TODO: allowEmpty and nonEmptyToEmpty - maybe with checkbox "set_new_pwd"
  31. * feel free to help me out
  32. *
  33. * 2011-08-24 ms
  34. */
  35. App::uses('Security', 'Utility');
  36. class ChangePasswordBehavior extends ModelBehavior {
  37. public $settings = array();
  38. /**
  39. * @access protected
  40. */
  41. public $_defaultSettings = array(
  42. 'field' => 'password',
  43. 'confirm' => true, # set to false if in admin view and no confirmation (pwd_repeat) is required
  44. 'allowEmpty' => false,
  45. 'current' => false, # expect the current password for security purposes
  46. 'formField' => 'pwd',
  47. 'formFieldRepeat' => 'pwd_repeat',
  48. 'formFieldCurrent' => 'pwd_current',
  49. 'hashType' => null,
  50. 'hashSalt' => true,
  51. 'auth' => 'Auth', # which component,
  52. 'allowSame' => true, # dont allow the old password on change //TODO: implement
  53. 'nonEmptyToEmpty' => false, # allow resetting nonempty pwds to empty once set (prevents problems with default edit actions)
  54. );
  55. public $_validationRules = array(
  56. 'formField' => array(
  57. 'between' => array(
  58. 'rule' => array('between', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  59. 'message' => array('valErrBetweenCharacters %s %s', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  60. 'last' => true,
  61. )
  62. ),
  63. 'formFieldRepeat' => array(
  64. 'between' => array(
  65. 'rule' => array('between', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  66. 'message' => array('valErrBetweenCharacters %s %s', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  67. 'last' => true,
  68. ),
  69. 'validateIdentical' => array(
  70. 'rule' => array('validateIdentical', 'formField'),
  71. 'message' => 'valErrPwdNotMatch',
  72. 'last' => true,
  73. ),
  74. ),
  75. 'formFieldCurrent' => array(
  76. 'notEmpty' => array(
  77. 'rule' => array('notEmpty'),
  78. 'message' => 'valErrProvideCurrentPwd',
  79. 'last' => true,
  80. ),
  81. 'validateCurrentPwd' => array(
  82. 'rule' => 'validateCurrentPwd',
  83. 'message' => 'valErrCurrentPwdIncorrect',
  84. )
  85. ),
  86. );
  87. /**
  88. * if not implemented in app_model
  89. * 2011-07-22 ms
  90. */
  91. public function validateCurrentPwd(Model $Model, $data) {
  92. if (is_array($data)) {
  93. $pwd = array_shift($data);
  94. } else {
  95. $pwd = $data;
  96. }
  97. $uid = null;
  98. if ($Model->id) {
  99. $uid = $Model->id;
  100. } elseif (!empty($Model->data[$Model->alias]['id'])) {
  101. $uid = $Model->data[$Model->alias]['id'];
  102. } else {
  103. trigger_error('No user id given');
  104. return false;
  105. }
  106. if (class_exists('AuthExtComponent')) {
  107. $this->Auth = new AuthExtComponent(new ComponentCollection());
  108. } elseif (class_exists($this->settings[$Model->alias]['auth'].'Component')) {
  109. $auth = $this->settings[$Model->alias]['auth'].'Component';
  110. $this->Auth = new $auth(new ComponentCollection());
  111. } else {
  112. trigger_error('No validation class found');
  113. return true;
  114. }
  115. $this->Auth->constructAuthenticate();
  116. //debug($this->Auth); die();
  117. return $this->Auth->verifyUser($uid, $pwd);
  118. }
  119. /**
  120. * if not implemented in app_model
  121. * 2011-07-22 ms
  122. */
  123. public function validateIdentical(Model $Model, $data, $compareWith = null) {
  124. if (is_array($data)) {
  125. $value = array_shift($data);
  126. } else {
  127. $value = $data;
  128. }
  129. $compareValue = $Model->data[$Model->alias][$compareWith];
  130. return ($compareValue == $value);
  131. }
  132. /**
  133. * if not implemented in app_model
  134. * 2011-11-10 ms
  135. */
  136. public function validateNotSame(Model $Model, $data, $field1, $field2) {
  137. $value1 = $Model->data[$Model->alias][$field1];
  138. $value2 = $Model->data[$Model->alias][$field2];
  139. return ($value1 != $value2);
  140. }
  141. /**
  142. * adding validation rules
  143. * also adds and merges config settings (direct + configure)
  144. * 2011-08-24 ms
  145. */
  146. public function setup(Model $Model, $config = array()) {
  147. $defaults = $this->_defaultSettings;
  148. if ($configureDefaults = Configure::read('ChangePassword')) {
  149. $defaults = Set::merge($defaults, $configureDefaults);
  150. }
  151. $this->settings[$Model->alias] = Set::merge($defaults, $config);
  152. $formField = $this->settings[$Model->alias]['formField'];
  153. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  154. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  155. # add the validation rules if not already attached
  156. if (!isset($Model->validate[$formField])) {
  157. $Model->validate[$formField] = $this->_validationRules['formField'];
  158. }
  159. if (!isset($Model->validate[$formFieldRepeat])) {
  160. $Model->validate[$formFieldRepeat] = $this->_validationRules['formFieldRepeat'];
  161. $Model->validate[$formFieldRepeat]['validateIdentical']['rule'][1] = $formField;
  162. }
  163. if ($this->settings[$Model->alias]['current'] && !isset($Model->validate[$formFieldCurrent])) {
  164. $Model->validate[$formFieldCurrent] = $this->_validationRules['formFieldCurrent'];
  165. if (!$this->settings[$Model->alias]['allowSame']) {
  166. $Model->validate[$formField]['validateNotSame'] = array(
  167. 'rule' => array('validateNotSame', $formField, $formFieldCurrent),
  168. 'message' => 'valErrPwdSameAsBefore',
  169. 'last' => true,
  170. );
  171. }
  172. }
  173. # allowEmpty?
  174. if (!empty($this->settings[$Model->alias]['allowEmpty'])) {
  175. $Model->validate[$formField]['between']['rule'][1] = 0;
  176. }
  177. }
  178. /**
  179. * whitelisting
  180. * 2011-07-22 ms
  181. */
  182. public function beforeValidate(Model $Model) {
  183. # add fields to whitelist!
  184. $whitelist = array($this->settings[$Model->alias]['formField'], $this->settings[$Model->alias]['formFieldRepeat']);
  185. if ($this->settings[$Model->alias]['current']) {
  186. $whitelist[] = $this->settings[$Model->alias]['formFieldCurrent'];
  187. }
  188. if (!empty($Model->whitelist)) {
  189. $Model->whitelist = am($Model->whitelist, $whitelist);
  190. }
  191. # make sure fields are set and validation rules are triggered - prevents tempering of form data
  192. $formField = $this->settings[$Model->alias]['formField'];
  193. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  194. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  195. if (!isset($Model->data[$Model->alias][$formField])) {
  196. $Model->data[$Model->alias][$formField] = '';
  197. }
  198. if ($this->settings[$Model->alias]['confirm'] && !isset($Model->data[$Model->alias][$formFieldRepeat])) {
  199. $Model->data[$Model->alias][$formFieldRepeat] = '';
  200. }
  201. if ($this->settings[$Model->alias]['current'] && !isset($Model->data[$Model->alias][$formFieldCurrent])) {
  202. $Model->data[$Model->alias][$formFieldCurrent] = '';
  203. }
  204. return true;
  205. }
  206. /**
  207. * hashing the password now
  208. * 2011-07-22 ms
  209. */
  210. public function beforeSave(Model $Model) {
  211. $formField = $this->settings[$Model->alias]['formField'];
  212. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  213. $field = $this->settings[$Model->alias]['field'];
  214. $type = $this->settings[$Model->alias]['hashType'];
  215. $salt = $this->settings[$Model->alias]['hashSalt'];
  216. if (empty($Model->data[$Model->alias][$formField]) && !$this->settings[$Model->alias]['nonEmptyToEmpty']) {
  217. # is edit? previous password was "notEmpty"?
  218. 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)) {
  219. unset($Model->data[$Model->alias][$formField]);
  220. }
  221. }
  222. if (isset($Model->data[$Model->alias][$formField])) {
  223. $Model->data[$Model->alias][$field] = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  224. unset($Model->data[$Model->alias][$formField]);
  225. if ($this->settings[$Model->alias]['confirm']) {
  226. unset($Model->data[$Model->alias][$formFieldRepeat]);
  227. }
  228. # update whitelist
  229. if (!empty($Model->whitelist)) {
  230. $Model->whitelist = am($Model->whitelist, array($field));
  231. }
  232. }
  233. return true;
  234. }
  235. }