PasswordableBehavior.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. <?php
  2. App::uses('ModelBehavior', 'Model');
  3. App::uses('Router', 'Routing');
  4. App::uses('CakeRequest', 'Network');
  5. App::uses('CakeResponse', 'Network');
  6. App::uses('Security', 'Utility');
  7. if (!defined('PWD_MIN_LENGTH')) {
  8. define('PWD_MIN_LENGTH', 3);
  9. }
  10. if (!defined('PWD_MAX_LENGTH')) {
  11. define('PWD_MAX_LENGTH', 20);
  12. }
  13. /**
  14. * A cakephp2 behavior to work with passwords the easy way
  15. * - complete validation
  16. * - hashing of password
  17. * - requires fields (no tempering even without security component)
  18. * - usable for edit forms (allowEmpty=>true for optional password update)
  19. *
  20. * usage: do NOT add it via $actAs = array()
  21. * attach it dynamically in only those actions where you actually change the password like so:
  22. * $this->User->Behaviors->load('Tools.Passwordable', array(SETTINGSARRAY));
  23. * as first line in any action where you want to allow the user to change his password
  24. * also add the two form fields in the form (pwd, pwd_confirm)
  25. * the rest is cake automagic :)
  26. *
  27. * now also is capable of:
  28. * - require current password prior to altering it (current=>true)
  29. * - don't allow the same password it was before (allowSame=>false)
  30. *
  31. * TODO: allowEmpty and nonEmptyToEmpty - maybe with checkbox "set_new_pwd"
  32. * feel free to help me out
  33. *
  34. * @version 1.6 (renamed from ChangePassword to Passwordable)
  35. * @author Mark Scherer
  36. * @link http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp
  37. * @license MIT
  38. * 2012-08-18 ms
  39. */
  40. class PasswordableBehavior extends ModelBehavior {
  41. /**
  42. * @access protected
  43. */
  44. protected $_defaults = array(
  45. 'field' => 'password',
  46. 'confirm' => true, # set to false if in admin view and no confirmation (pwd_repeat) is required
  47. 'allowEmpty' => false, # if password must be provided or be changed (set to true for update sites)
  48. 'current' => false, # expect the current password for security purposes
  49. 'formField' => 'pwd',
  50. 'formFieldRepeat' => 'pwd_repeat',
  51. 'formFieldCurrent' => 'pwd_current',
  52. 'hashType' => null,
  53. 'hashSalt' => true,
  54. 'auth' => null, # which component (defaults to AuthComponent),
  55. 'allowSame' => true, # dont allow the old password on change,
  56. 'minLength' => PWD_MIN_LENGTH,
  57. 'maxLength' => PWD_MAX_LENGTH
  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. $auth = 'Auth';
  122. if (empty($this->settings[$Model->alias]['auth']) && class_exists('AuthExtComponent')) {
  123. $auth = 'AuthExt';
  124. } elseif ($this->settings[$Model->alias]['auth']) {
  125. $auth = $this->settings[$Model->alias]['auth'];
  126. }
  127. $authClass = $auth . 'Component';
  128. if (!class_exists($authClass)) {
  129. throw new CakeException('No Authentication class found (' . $authClass. ')');
  130. }
  131. $this->Auth = new $authClass(new ComponentCollection());
  132. # easiest authenticate method via form and (id + pwd)
  133. $this->Auth->authenticate = array(
  134. 'Form' => array(
  135. 'fields'=>array('username' => 'id', 'password'=>$this->settings[$Model->alias]['field'])
  136. )
  137. );
  138. $request = Router::getRequest();
  139. $request->data['User'] = array('id'=>$uid, 'password'=>$pwd);
  140. $response = new CakeResponse();
  141. return (bool)$this->Auth->identify($request, $response);
  142. }
  143. /**
  144. * if not implemented in AppModel
  145. * @return bool $success
  146. * 2011-07-22 ms
  147. */
  148. public function validateIdentical(Model $Model, $data, $compareWith = null) {
  149. if (is_array($data)) {
  150. $value = array_shift($data);
  151. } else {
  152. $value = $data;
  153. }
  154. $compareValue = $Model->data[$Model->alias][$compareWith];
  155. return ($compareValue === $value);
  156. }
  157. /**
  158. * if not implemented in AppModel
  159. * @return bool $success
  160. * 2011-11-10 ms
  161. */
  162. public function validateNotSame(Model $Model, $data, $field1, $field2) {
  163. $value1 = $Model->data[$Model->alias][$field1];
  164. $value2 = $Model->data[$Model->alias][$field2];
  165. return ($value1 !== $value2);
  166. }
  167. /**
  168. * if not implemented in AppModel
  169. * @return bool $success
  170. * 2011-11-10 ms
  171. */
  172. public function validateNotSameHash(Model $Model, $data, $formField) {
  173. $field = $this->settings[$Model->alias]['field'];
  174. $type = $this->settings[$Model->alias]['hashType'];
  175. $salt = $this->settings[$Model->alias]['hashSalt'];
  176. if (!isset($Model->data[$Model->alias][$Model->primaryKey])) {
  177. return true;
  178. }
  179. $primaryKey = $Model->data[$Model->alias][$Model->primaryKey];
  180. $value = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  181. $dbValue = $Model->field($field, array($Model->primaryKey => $primaryKey));
  182. if (!$dbValue) {
  183. return true;
  184. }
  185. return ($value !== $dbValue);
  186. }
  187. /**
  188. * adding validation rules
  189. * also adds and merges config settings (direct + configure)
  190. * @return void
  191. * 2011-08-24 ms
  192. */
  193. public function setup(Model $Model, $config = array()) {
  194. $defaults = $this->_defaults;
  195. if ($configureDefaults = Configure::read('Passwordable')) {
  196. $defaults = Set::merge($defaults, $configureDefaults);
  197. }
  198. $this->settings[$Model->alias] = Set::merge($defaults, $config);
  199. $formField = $this->settings[$Model->alias]['formField'];
  200. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  201. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  202. $rules = $this->_validationRules;
  203. # add the validation rules if not already attached
  204. if (!isset($Model->validate[$formField])) {
  205. $Model->validator()->add($formField, $rules['formField']);
  206. }
  207. if (!isset($Model->validate[$formFieldRepeat])) {
  208. $ruleSet = $rules['formFieldRepeat'];
  209. $ruleSet['validateIdentical']['rule'][1] = $formField;
  210. $Model->validator()->add($formFieldRepeat, $ruleSet);
  211. }
  212. if ($this->settings[$Model->alias]['current'] && !isset($Model->validate[$formFieldCurrent])) {
  213. $Model->validator()->add($formFieldCurrent, $rules['formFieldCurrent']);
  214. if (!$this->settings[$Model->alias]['allowSame']) {
  215. $Model->validator()->add($formField, 'validateNotSame', array(
  216. 'rule' => array('validateNotSame', $formField, $formFieldCurrent),
  217. 'message' => 'valErrPwdSameAsBefore',
  218. 'allowEmpty' => $this->settings[$Model->alias]['allowEmpty'],
  219. 'last' => true,
  220. ));
  221. }
  222. } elseif (!isset($Model->validate[$formFieldCurrent])) {
  223. # try to match the password against the hash in the DB
  224. if (!$this->settings[$Model->alias]['allowSame']) {
  225. $Model->validator()->add($formField, 'validateNotSame', array(
  226. 'rule' => array('validateNotSameHash', $formField),
  227. 'message' => 'valErrPwdSameAsBefore',
  228. 'allowEmpty' => $this->settings[$Model->alias]['allowEmpty'],
  229. 'last' => true,
  230. ));
  231. }
  232. }
  233. }
  234. /**
  235. * whitelisting
  236. *
  237. * @todo currently there is a cake core bug that can break functionality here
  238. * (see http://cakephp.lighthouseapp.com/projects/42648/tickets/3071-behavior-validation-methods-broken for details)
  239. * @return bool $success
  240. * 2011-07-22 ms
  241. */
  242. public function beforeValidate(Model $Model) {
  243. $formField = $this->settings[$Model->alias]['formField'];
  244. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  245. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  246. # make sure fields are set and validation rules are triggered - prevents tempering of form data
  247. if (!isset($Model->data[$Model->alias][$formField])) {
  248. $Model->data[$Model->alias][$formField] = '';
  249. }
  250. if ($this->settings[$Model->alias]['confirm'] && !isset($Model->data[$Model->alias][$formFieldRepeat])) {
  251. $Model->data[$Model->alias][$formFieldRepeat] = '';
  252. }
  253. if ($this->settings[$Model->alias]['current'] && !isset($Model->data[$Model->alias][$formFieldCurrent])) {
  254. $Model->data[$Model->alias][$formFieldCurrent] = '';
  255. }
  256. # check if we need to trigger any validation rules
  257. if ($this->settings[$Model->alias]['allowEmpty']) {
  258. $current = !empty($Model->data[$Model->alias][$formFieldCurrent]);
  259. $new = !empty($Model->data[$Model->alias][$formField]) || !empty($Model->data[$Model->alias][$formFieldRepeat]);
  260. if (!$new && !$current) {
  261. //$Model->validator()->remove($formField); // tmp only!
  262. //unset($Model->validate[$formField]);
  263. unset($Model->data[$Model->alias][$formField]);
  264. if ($this->settings[$Model->alias]['confirm']) {
  265. //$Model->validator()->remove($formFieldRepeat); // tmp only!
  266. //unset($Model->validate[$formFieldRepeat]);
  267. unset($Model->data[$Model->alias][$formFieldRepeat]);
  268. }
  269. if ($this->settings[$Model->alias]['current']) {
  270. //$Model->validator()->remove($formFieldCurrent); // tmp only!
  271. //unset($Model->validate[$formFieldCurrent]);
  272. unset($Model->data[$Model->alias][$formFieldCurrent]);
  273. }
  274. return true;
  275. }
  276. }
  277. # add fields to whitelist!
  278. $whitelist = array($this->settings[$Model->alias]['formField'], $this->settings[$Model->alias]['formFieldRepeat']);
  279. if ($this->settings[$Model->alias]['current']) {
  280. $whitelist[] = $this->settings[$Model->alias]['formFieldCurrent'];
  281. }
  282. if (!empty($Model->whitelist)) {
  283. $Model->whitelist = array_merge($Model->whitelist, $whitelist);
  284. }
  285. return true;
  286. }
  287. /**
  288. * hashing the password now
  289. * @return bool $success
  290. * 2011-07-22 ms
  291. */
  292. public function beforeSave(Model $Model) {
  293. $formField = $this->settings[$Model->alias]['formField'];
  294. $field = $this->settings[$Model->alias]['field'];
  295. $type = $this->settings[$Model->alias]['hashType'];
  296. $salt = $this->settings[$Model->alias]['hashSalt'];
  297. if (isset($Model->data[$Model->alias][$formField])) {
  298. $Model->data[$Model->alias][$field] = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  299. unset($Model->data[$Model->alias][$formField]);
  300. if ($this->settings[$Model->alias]['confirm']) {
  301. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  302. unset($Model->data[$Model->alias][$formFieldRepeat]);
  303. }
  304. if ($this->settings[$Model->alias]['current']) {
  305. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  306. unset($Model->data[$Model->alias][$formFieldCurrent]);
  307. }
  308. # update whitelist
  309. if (!empty($Model->whitelist)) {
  310. $Model->whitelist = array_merge($Model->whitelist, array($field));
  311. }
  312. }
  313. return true;
  314. }
  315. }