ChangePasswordBehavior.php 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. <?php
  2. App::uses('ModelBehavior', 'Model');
  3. App::uses('CakeResponse', 'Network');
  4. App::uses('Security', 'Utility');
  5. if (!defined('PWD_MIN_LENGTH')) {
  6. define('PWD_MIN_LENGTH', 3);
  7. }
  8. if (!defined('PWD_MAX_LENGTH')) {
  9. define('PWD_MAX_LENGTH', 20);
  10. }
  11. /**
  12. * A cakephp2 behavior to work with passwords the easy way
  13. * - complete validation
  14. * - hashing of password
  15. * - requires fields (no tempering even without security component)
  16. * - usable for edit forms (allowEmpty=>true for optional password update)
  17. *
  18. * usage: do NOT add it via $actAs = array()
  19. * attach it dynamically in only those actions where you actually change the password like so:
  20. * $this->User->Behaviors->attach('Tools.ChangePassword', array(SETTINGSARRAY));
  21. * as first line in any action where you want to allow the user to change his password
  22. * also add the two form fields in the form (pwd, pwd_confirm)
  23. * the rest is cake automagic :)
  24. *
  25. * now also is capable of:
  26. * - require current password prior to altering it (current=>true)
  27. * - don't allow the same password it was before (allowSame=>false)
  28. *
  29. * TODO: allowEmpty and nonEmptyToEmpty - maybe with checkbox "set_new_pwd"
  30. * feel free to help me out
  31. *
  32. * @deprecated Use PasswordableBehavior instead!
  33. * @author Mark Scherer
  34. * @link http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp
  35. * @license MIT
  36. * 2011-08-24 ms
  37. */
  38. class ChangePasswordBehavior extends ModelBehavior {
  39. public $settings = array();
  40. /**
  41. * @access protected
  42. */
  43. public $_defaultSettings = array(
  44. 'field' => 'password',
  45. 'confirm' => true, # set to false if in admin view and no confirmation (pwd_repeat) is required
  46. 'allowEmpty' => false, # if password must be provided or be changed (set to true for update sites)
  47. 'current' => false, # expect the current password for security purposes
  48. 'formField' => 'pwd',
  49. 'formFieldRepeat' => 'pwd_repeat',
  50. 'formFieldCurrent' => 'pwd_current',
  51. 'hashType' => null,
  52. 'hashSalt' => true,
  53. 'auth' => 'Auth', # which component,
  54. 'allowSame' => true, # dont allow the old password on change
  55. );
  56. public $_validationRules = array(
  57. 'formField' => array(
  58. 'between' => array(
  59. 'rule' => array('between', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  60. 'message' => array('valErrBetweenCharacters %s %s', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  61. 'allowEmpty' => null,
  62. 'last' => true,
  63. )
  64. ),
  65. 'formFieldRepeat' => 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. 'validateIdentical' => array(
  73. 'rule' => array('validateIdentical', 'formField'),
  74. 'message' => 'valErrPwdNotMatch',
  75. 'allowEmpty' => null,
  76. 'last' => true,
  77. ),
  78. ),
  79. 'formFieldCurrent' => array(
  80. 'notEmpty' => array(
  81. 'rule' => array('notEmpty'),
  82. 'message' => 'valErrProvideCurrentPwd',
  83. 'allowEmpty' => null,
  84. 'last' => true,
  85. ),
  86. 'validateCurrentPwd' => array(
  87. 'rule' => 'validateCurrentPwd',
  88. 'message' => 'valErrCurrentPwdIncorrect',
  89. 'allowEmpty' => null,
  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. trigger_error('Deprecated - use PasswordableBehavior instead');
  161. $defaults = $this->_defaultSettings;
  162. if ($configureDefaults = Configure::read('ChangePassword')) {
  163. $defaults = Set::merge($defaults, $configureDefaults);
  164. }
  165. $this->settings[$Model->alias] = Set::merge($defaults, $config);
  166. $formField = $this->settings[$Model->alias]['formField'];
  167. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  168. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  169. $rules = $this->_validationRules;
  170. # add the validation rules if not already attached
  171. if (!isset($Model->validate[$formField])) {
  172. $Model->validate[$formField] = $rules['formField'];
  173. }
  174. if (!isset($Model->validate[$formFieldRepeat])) {
  175. $Model->validate[$formFieldRepeat] = $rules['formFieldRepeat'];
  176. $Model->validate[$formFieldRepeat]['validateIdentical']['rule'][1] = $formField;
  177. }
  178. if ($this->settings[$Model->alias]['current'] && !isset($Model->validate[$formFieldCurrent])) {
  179. $Model->validate[$formFieldCurrent] = $rules['formFieldCurrent'];
  180. if (!$this->settings[$Model->alias]['allowSame']) {
  181. $Model->validate[$formField]['validateNotSame'] = array(
  182. 'rule' => array('validateNotSame', $formField, $formFieldCurrent),
  183. 'message' => 'valErrPwdSameAsBefore',
  184. 'allowEmpty' => $this->settings[$Model->alias]['allowEmpty'],
  185. 'last' => true,
  186. );
  187. }
  188. }
  189. }
  190. /**
  191. * whitelisting
  192. *
  193. * @todo currently there is a cake core bug that can break functionality here
  194. * (see http://cakephp.lighthouseapp.com/projects/42648/tickets/3071-behavior-validation-methods-broken for details)
  195. * 2011-07-22 ms
  196. */
  197. public function beforeValidate(Model $Model) {
  198. $formField = $this->settings[$Model->alias]['formField'];
  199. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  200. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  201. # make sure fields are set and validation rules are triggered - prevents tempering of form data
  202. if (!isset($Model->data[$Model->alias][$formField])) {
  203. $Model->data[$Model->alias][$formField] = '';
  204. }
  205. if ($this->settings[$Model->alias]['confirm'] && !isset($Model->data[$Model->alias][$formFieldRepeat])) {
  206. $Model->data[$Model->alias][$formFieldRepeat] = '';
  207. }
  208. if ($this->settings[$Model->alias]['current'] && !isset($Model->data[$Model->alias][$formFieldCurrent])) {
  209. $Model->data[$Model->alias][$formFieldCurrent] = '';
  210. }
  211. # check if we need to trigger any validation rules
  212. if ($this->settings[$Model->alias]['allowEmpty']) {
  213. $current = !empty($Model->data[$Model->alias][$formFieldCurrent]);
  214. $new = !empty($Model->data[$Model->alias][$formField]) || !empty($Model->data[$Model->alias][$formFieldRepeat]);
  215. if (!$new && !$current) {
  216. //$Model->validator()->remove($formField); // tmp only!
  217. //unset($Model->validate[$formField]);
  218. unset($Model->data[$Model->alias][$formField]);
  219. if ($this->settings[$Model->alias]['confirm']) {
  220. //$Model->validator()->remove($formFieldRepeat); // tmp only!
  221. //unset($Model->validate[$formFieldRepeat]);
  222. unset($Model->data[$Model->alias][$formFieldRepeat]);
  223. }
  224. if ($this->settings[$Model->alias]['current']) {
  225. //$Model->validator()->remove($formFieldCurrent); // tmp only!
  226. //unset($Model->validate[$formFieldCurrent]);
  227. unset($Model->data[$Model->alias][$formFieldCurrent]);
  228. }
  229. return true;
  230. }
  231. }
  232. # add fields to whitelist!
  233. $whitelist = array($this->settings[$Model->alias]['formField'], $this->settings[$Model->alias]['formFieldRepeat']);
  234. if ($this->settings[$Model->alias]['current']) {
  235. $whitelist[] = $this->settings[$Model->alias]['formFieldCurrent'];
  236. }
  237. if (!empty($Model->whitelist)) {
  238. $Model->whitelist = array_merge($Model->whitelist, $whitelist);
  239. }
  240. return true;
  241. }
  242. /**
  243. * hashing the password now
  244. * 2011-07-22 ms
  245. */
  246. public function beforeSave(Model $Model) {
  247. //debug($Model->data);
  248. $formField = $this->settings[$Model->alias]['formField'];
  249. $field = $this->settings[$Model->alias]['field'];
  250. $type = $this->settings[$Model->alias]['hashType'];
  251. $salt = $this->settings[$Model->alias]['hashSalt'];
  252. if (isset($Model->data[$Model->alias][$formField])) {
  253. $Model->data[$Model->alias][$field] = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  254. unset($Model->data[$Model->alias][$formField]);
  255. if ($this->settings[$Model->alias]['confirm']) {
  256. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  257. unset($Model->data[$Model->alias][$formFieldRepeat]);
  258. }
  259. if ($this->settings[$Model->alias]['current']) {
  260. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  261. unset($Model->data[$Model->alias][$formFieldCurrent]);
  262. }
  263. # update whitelist
  264. if (!empty($Model->whitelist)) {
  265. $Model->whitelist = array_merge($Model->whitelist, array($field));
  266. }
  267. }
  268. return true;
  269. }
  270. }