ChangePasswordBehavior.php 10.0 KB

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