ChangePasswordBehavior.php 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. * @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. * @version 1.5
  40. * @author Mark Scherer
  41. * @license MIT
  42. * 2011-08-24 ms
  43. */
  44. class ChangePasswordBehavior extends ModelBehavior {
  45. public $settings = array();
  46. /**
  47. * @access protected
  48. */
  49. public $_defaultSettings = array(
  50. 'field' => 'password',
  51. 'confirm' => true, # set to false if in admin view and no confirmation (pwd_repeat) is required
  52. 'allowEmpty' => false, # if password must be provided or be changed (set to true for update sites)
  53. 'current' => false, # expect the current password for security purposes
  54. 'formField' => 'pwd',
  55. 'formFieldRepeat' => 'pwd_repeat',
  56. 'formFieldCurrent' => 'pwd_current',
  57. 'hashType' => null,
  58. 'hashSalt' => true,
  59. 'auth' => 'Auth', # which component,
  60. 'allowSame' => true, # dont allow the old password on change
  61. );
  62. public $_validationRules = array(
  63. 'formField' => 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. 'allowEmpty' => null,
  68. 'last' => true,
  69. )
  70. ),
  71. 'formFieldRepeat' => array(
  72. 'between' => array(
  73. 'rule' => array('between', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  74. 'message' => array('valErrBetweenCharacters %s %s', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  75. 'allowEmpty' => null,
  76. 'last' => true,
  77. ),
  78. 'validateIdentical' => array(
  79. 'rule' => array('validateIdentical', 'formField'),
  80. 'message' => 'valErrPwdNotMatch',
  81. 'allowEmpty' => null,
  82. 'last' => true,
  83. ),
  84. ),
  85. 'formFieldCurrent' => array(
  86. 'notEmpty' => array(
  87. 'rule' => array('notEmpty'),
  88. 'message' => 'valErrProvideCurrentPwd',
  89. 'allowEmpty' => null,
  90. 'last' => true,
  91. ),
  92. 'validateCurrentPwd' => array(
  93. 'rule' => 'validateCurrentPwd',
  94. 'message' => 'valErrCurrentPwdIncorrect',
  95. 'allowEmpty' => null,
  96. 'last' => true,
  97. )
  98. ),
  99. );
  100. /**
  101. * if not implemented in AppModel
  102. * @throws CakeException
  103. * @return bool $success
  104. * 2011-07-22 ms
  105. */
  106. public function validateCurrentPwd(Model $Model, $data) {
  107. if (is_array($data)) {
  108. $pwd = array_shift($data);
  109. } else {
  110. $pwd = $data;
  111. }
  112. $uid = null;
  113. if ($Model->id) {
  114. $uid = $Model->id;
  115. } elseif (!empty($Model->data[$Model->alias]['id'])) {
  116. $uid = $Model->data[$Model->alias]['id'];
  117. } else {
  118. trigger_error('No user id given');
  119. return false;
  120. }
  121. if (class_exists('AuthExtComponent')) {
  122. $this->Auth = new AuthExtComponent(new ComponentCollection());
  123. } elseif (class_exists($this->settings[$Model->alias]['auth'].'Component')) {
  124. $auth = $this->settings[$Model->alias]['auth'].'Component';
  125. $this->Auth = new $auth(new ComponentCollection());
  126. } else {
  127. throw new CakeException('No validation class found');
  128. }
  129. # easiest authenticate method via form and (id + pwd)
  130. $this->Auth->authenticate = array('Form'=>array('fields'=>array('username' => 'id', 'password'=>$this->settings[$Model->alias]['field'])));
  131. $request = new CakeRequest(null, false);
  132. $request->data['User'] = array('id'=>$uid, 'password'=>$pwd);
  133. $response = new CakeResponse();
  134. return $this->Auth->identify($request, $response);
  135. }
  136. /**
  137. * if not implemented in AppModel
  138. * @return bool $success
  139. * 2011-07-22 ms
  140. */
  141. public function validateIdentical(Model $Model, $data, $compareWith = null) {debug($compareWith); ob_flush();
  142. if (is_array($data)) {
  143. $value = array_shift($data);
  144. } else {
  145. $value = $data;
  146. }
  147. $compareValue = $Model->data[$Model->alias][$compareWith];
  148. return ($compareValue == $value);
  149. }
  150. /**
  151. * if not implemented in AppModel
  152. * @return bool $success
  153. * 2011-11-10 ms
  154. */
  155. public function validateNotSame(Model $Model, $data, $field1, $field2) {
  156. $value1 = $Model->data[$Model->alias][$field1];
  157. $value2 = $Model->data[$Model->alias][$field2];
  158. return ($value1 != $value2);
  159. }
  160. /**
  161. * adding validation rules
  162. * also adds and merges config settings (direct + configure)
  163. * 2011-08-24 ms
  164. */
  165. public function setup(Model $Model, $config = array()) {
  166. $defaults = $this->_defaultSettings;
  167. if ($configureDefaults = Configure::read('ChangePassword')) {
  168. $defaults = Set::merge($defaults, $configureDefaults);
  169. }
  170. $this->settings[$Model->alias] = Set::merge($defaults, $config);
  171. $formField = $this->settings[$Model->alias]['formField'];
  172. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  173. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  174. $rules = $this->_validationRules;
  175. # add the validation rules if not already attached
  176. if (!isset($Model->validate[$formField])) {
  177. $Model->validate[$formField] = $rules['formField'];
  178. }
  179. if (!isset($Model->validate[$formFieldRepeat])) {
  180. $Model->validate[$formFieldRepeat] = $rules['formFieldRepeat'];
  181. $Model->validate[$formFieldRepeat]['validateIdentical']['rule'][1] = $formField;
  182. }
  183. if ($this->settings[$Model->alias]['current'] && !isset($Model->validate[$formFieldCurrent])) {
  184. $Model->validate[$formFieldCurrent] = $rules['formFieldCurrent'];
  185. if (!$this->settings[$Model->alias]['allowSame']) {
  186. $Model->validate[$formField]['validateNotSame'] = array(
  187. 'rule' => array('validateNotSame', $formField, $formFieldCurrent),
  188. 'message' => 'valErrPwdSameAsBefore',
  189. 'allowEmpty' => $this->settings[$Model->alias]['allowEmpty'],
  190. 'last' => true,
  191. );
  192. }
  193. }
  194. }
  195. /**
  196. * whitelisting
  197. * 2011-07-22 ms
  198. */
  199. public function beforeValidate(Model $Model) {
  200. $formField = $this->settings[$Model->alias]['formField'];
  201. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  202. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  203. # make sure fields are set and validation rules are triggered - prevents tempering of form data
  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. # check if we need to trigger any validation rules
  214. if ($this->settings[$Model->alias]['allowEmpty']) {
  215. $current = !empty($Model->data[$Model->alias][$formFieldCurrent]);
  216. $new = !empty($Model->data[$Model->alias][$formField]) || !empty($Model->data[$Model->alias][$formFieldRepeat]);
  217. if (!$new && !$current) {
  218. //$Model->validator()->remove($formField); // tmp only!
  219. //unset($Model->validate[$formField]);
  220. unset($Model->data[$Model->alias][$formField]);
  221. if ($this->settings[$Model->alias]['confirm']) {
  222. //$Model->validator()->remove($formFieldRepeat); // tmp only!
  223. //unset($Model->validate[$formFieldRepeat]);
  224. unset($Model->data[$Model->alias][$formFieldRepeat]);
  225. }
  226. if ($this->settings[$Model->alias]['current']) {
  227. //$Model->validator()->remove($formFieldCurrent); // tmp only!
  228. //unset($Model->validate[$formFieldCurrent]);
  229. unset($Model->data[$Model->alias][$formFieldCurrent]);
  230. }
  231. debug($Model->data);
  232. return true;
  233. }
  234. }
  235. # add fields to whitelist!
  236. $whitelist = array($this->settings[$Model->alias]['formField'], $this->settings[$Model->alias]['formFieldRepeat']);
  237. if ($this->settings[$Model->alias]['current']) {
  238. $whitelist[] = $this->settings[$Model->alias]['formFieldCurrent'];
  239. }
  240. if (!empty($Model->whitelist)) {
  241. $Model->whitelist = array_merge($Model->whitelist, $whitelist);
  242. }
  243. return true;
  244. }
  245. /**
  246. * hashing the password now
  247. * 2011-07-22 ms
  248. */
  249. public function beforeSave(Model $Model) {
  250. //debug($Model->data);
  251. $formField = $this->settings[$Model->alias]['formField'];
  252. $field = $this->settings[$Model->alias]['field'];
  253. $type = $this->settings[$Model->alias]['hashType'];
  254. $salt = $this->settings[$Model->alias]['hashSalt'];
  255. if (isset($Model->data[$Model->alias][$formField])) {
  256. $Model->data[$Model->alias][$field] = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  257. unset($Model->data[$Model->alias][$formField]);
  258. if ($this->settings[$Model->alias]['confirm']) {
  259. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  260. unset($Model->data[$Model->alias][$formFieldRepeat]);
  261. }
  262. if ($this->settings[$Model->alias]['current']) {
  263. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  264. unset($Model->data[$Model->alias][$formFieldCurrent]);
  265. }
  266. # update whitelist
  267. if (!empty($Model->whitelist)) {
  268. $Model->whitelist = array_merge($Model->whitelist, array($field));
  269. }
  270. }
  271. return true;
  272. }
  273. }