PasswordableBehavior.php 11 KB

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