PasswordableBehavior.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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->load('Tools.Passwordable', 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. * @version 1.6 (renamed from ChangePassword to Passwordable)
  33. * @author Mark Scherer
  34. * @link http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp
  35. * @license MIT
  36. * 2012-08-18 ms
  37. */
  38. class PasswordableBehavior extends ModelBehavior {
  39. /**
  40. * @access public
  41. */
  42. public $settings = array();
  43. /**
  44. * @access protected
  45. */
  46. protected $_defaultSettings = array(
  47. 'field' => 'password',
  48. 'confirm' => true, # set to false if in admin view and no confirmation (pwd_repeat) is required
  49. 'allowEmpty' => false, # if password must be provided or be changed (set to true for update sites)
  50. 'current' => false, # expect the current password for security purposes
  51. 'formField' => 'pwd',
  52. 'formFieldRepeat' => 'pwd_repeat',
  53. 'formFieldCurrent' => 'pwd_current',
  54. 'hashType' => null,
  55. 'hashSalt' => true,
  56. 'auth' => null, # which component (defaults to AuthComponent),
  57. 'allowSame' => true, # dont allow the old password on change,
  58. 'minLength' => PWD_MIN_LENGTH,
  59. 'maxLength' => PWD_MAX_LENGTH
  60. );
  61. /**
  62. * @access protected
  63. */
  64. protected $_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 (empty($this->settings[$Model->alias]['auth']) && class_exists('AuthExtComponent')) {
  124. $this->Auth = new AuthExtComponent(new ComponentCollection());
  125. } elseif (class_exists(($this->settings[$Model->alias]['auth'] ? $this->settings[$Model->alias]['auth'] : '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(
  133. 'Form' => array(
  134. 'fields'=>array('username' => 'id', 'password'=>$this->settings[$Model->alias]['field'])
  135. )
  136. );
  137. $request = new CakeRequest(null, false);
  138. $request->data['User'] = array('id'=>$uid, 'password'=>$pwd);
  139. $response = new CakeResponse();
  140. return (bool)$this->Auth->identify($request, $response);
  141. }
  142. /**
  143. * if not implemented in AppModel
  144. * @return bool $success
  145. * 2011-07-22 ms
  146. */
  147. public function validateIdentical(Model $Model, $data, $compareWith = null) {
  148. if (is_array($data)) {
  149. $value = array_shift($data);
  150. } else {
  151. $value = $data;
  152. }
  153. $compareValue = $Model->data[$Model->alias][$compareWith];
  154. return ($compareValue === $value);
  155. }
  156. /**
  157. * if not implemented in AppModel
  158. * @return bool $success
  159. * 2011-11-10 ms
  160. */
  161. public function validateNotSame(Model $Model, $data, $field1, $field2) {
  162. $value1 = $Model->data[$Model->alias][$field1];
  163. $value2 = $Model->data[$Model->alias][$field2];
  164. return ($value1 !== $value2);
  165. }
  166. /**
  167. * if not implemented in AppModel
  168. * @return bool $success
  169. * 2011-11-10 ms
  170. */
  171. public function validateNotSameHash(Model $Model, $data, $formField) {
  172. $field = $this->settings[$Model->alias]['field'];
  173. $type = $this->settings[$Model->alias]['hashType'];
  174. $salt = $this->settings[$Model->alias]['hashSalt'];
  175. if (!isset($Model->data[$Model->alias][$Model->primaryKey])) {
  176. return true;
  177. }
  178. $primaryKey = $Model->data[$Model->alias][$Model->primaryKey];
  179. $value = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  180. $dbValue = $Model->field($field, array($Model->primaryKey => $primaryKey));
  181. if (!$dbValue) {
  182. return true;
  183. }
  184. return ($value !== $dbValue);
  185. }
  186. /**
  187. * adding validation rules
  188. * also adds and merges config settings (direct + configure)
  189. * @return void
  190. * 2011-08-24 ms
  191. */
  192. public function setup(Model $Model, $config = array()) {
  193. $defaults = $this->_defaultSettings;
  194. if ($configureDefaults = Configure::read('Passwordable')) {
  195. $defaults = Set::merge($defaults, $configureDefaults);
  196. }
  197. $this->settings[$Model->alias] = Set::merge($defaults, $config);
  198. $formField = $this->settings[$Model->alias]['formField'];
  199. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  200. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  201. $rules = $this->_validationRules;
  202. # add the validation rules if not already attached
  203. if (!isset($Model->validate[$formField])) {
  204. $Model->validate[$formField] = $rules['formField'];
  205. }
  206. if (!isset($Model->validate[$formFieldRepeat])) {
  207. $Model->validate[$formFieldRepeat] = $rules['formFieldRepeat'];
  208. $Model->validate[$formFieldRepeat]['validateIdentical']['rule'][1] = $formField;
  209. }
  210. if ($this->settings[$Model->alias]['current'] && !isset($Model->validate[$formFieldCurrent])) {
  211. $Model->validate[$formFieldCurrent] = $rules['formFieldCurrent'];
  212. if (!$this->settings[$Model->alias]['allowSame']) {
  213. $Model->validate[$formField]['validateNotSame'] = array(
  214. 'rule' => array('validateNotSame', $formField, $formFieldCurrent),
  215. 'message' => 'valErrPwdSameAsBefore',
  216. 'allowEmpty' => $this->settings[$Model->alias]['allowEmpty'],
  217. 'last' => true,
  218. );
  219. }
  220. } elseif (!isset($Model->validate[$formFieldCurrent])) {
  221. # try to match the password against the hash in the DB
  222. if (!$this->settings[$Model->alias]['allowSame']) {
  223. $Model->validate[$formField]['validateNotSame'] = array(
  224. 'rule' => array('validateNotSameHash', $formField),
  225. 'message' => 'valErrPwdSameAsBefore',
  226. 'allowEmpty' => $this->settings[$Model->alias]['allowEmpty'],
  227. 'last' => true,
  228. );
  229. }
  230. }
  231. }
  232. /**
  233. * whitelisting
  234. *
  235. * @todo currently there is a cake core bug that can break functionality here
  236. * (see http://cakephp.lighthouseapp.com/projects/42648/tickets/3071-behavior-validation-methods-broken for details)
  237. * @return bool $success
  238. * 2011-07-22 ms
  239. */
  240. public function beforeValidate(Model $Model) {
  241. $formField = $this->settings[$Model->alias]['formField'];
  242. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  243. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  244. # make sure fields are set and validation rules are triggered - prevents tempering of form data
  245. if (!isset($Model->data[$Model->alias][$formField])) {
  246. $Model->data[$Model->alias][$formField] = '';
  247. }
  248. if ($this->settings[$Model->alias]['confirm'] && !isset($Model->data[$Model->alias][$formFieldRepeat])) {
  249. $Model->data[$Model->alias][$formFieldRepeat] = '';
  250. }
  251. if ($this->settings[$Model->alias]['current'] && !isset($Model->data[$Model->alias][$formFieldCurrent])) {
  252. $Model->data[$Model->alias][$formFieldCurrent] = '';
  253. }
  254. # check if we need to trigger any validation rules
  255. if ($this->settings[$Model->alias]['allowEmpty']) {
  256. $current = !empty($Model->data[$Model->alias][$formFieldCurrent]);
  257. $new = !empty($Model->data[$Model->alias][$formField]) || !empty($Model->data[$Model->alias][$formFieldRepeat]);
  258. if (!$new && !$current) {
  259. //$Model->validator()->remove($formField); // tmp only!
  260. //unset($Model->validate[$formField]);
  261. unset($Model->data[$Model->alias][$formField]);
  262. if ($this->settings[$Model->alias]['confirm']) {
  263. //$Model->validator()->remove($formFieldRepeat); // tmp only!
  264. //unset($Model->validate[$formFieldRepeat]);
  265. unset($Model->data[$Model->alias][$formFieldRepeat]);
  266. }
  267. if ($this->settings[$Model->alias]['current']) {
  268. //$Model->validator()->remove($formFieldCurrent); // tmp only!
  269. //unset($Model->validate[$formFieldCurrent]);
  270. unset($Model->data[$Model->alias][$formFieldCurrent]);
  271. }
  272. return true;
  273. }
  274. }
  275. # add fields to whitelist!
  276. $whitelist = array($this->settings[$Model->alias]['formField'], $this->settings[$Model->alias]['formFieldRepeat']);
  277. if ($this->settings[$Model->alias]['current']) {
  278. $whitelist[] = $this->settings[$Model->alias]['formFieldCurrent'];
  279. }
  280. if (!empty($Model->whitelist)) {
  281. $Model->whitelist = array_merge($Model->whitelist, $whitelist);
  282. }
  283. return true;
  284. }
  285. /**
  286. * hashing the password now
  287. * @return bool $success
  288. * 2011-07-22 ms
  289. */
  290. public function beforeSave(Model $Model) {
  291. $formField = $this->settings[$Model->alias]['formField'];
  292. $field = $this->settings[$Model->alias]['field'];
  293. $type = $this->settings[$Model->alias]['hashType'];
  294. $salt = $this->settings[$Model->alias]['hashSalt'];
  295. if (isset($Model->data[$Model->alias][$formField])) {
  296. $Model->data[$Model->alias][$field] = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  297. unset($Model->data[$Model->alias][$formField]);
  298. if ($this->settings[$Model->alias]['confirm']) {
  299. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  300. unset($Model->data[$Model->alias][$formFieldRepeat]);
  301. }
  302. if ($this->settings[$Model->alias]['current']) {
  303. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  304. unset($Model->data[$Model->alias][$formFieldCurrent]);
  305. }
  306. # update whitelist
  307. if (!empty($Model->whitelist)) {
  308. $Model->whitelist = array_merge($Model->whitelist, array($field));
  309. }
  310. }
  311. return true;
  312. }
  313. }