PasswordableBehavior.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. 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 Authentication class found (' . $this->settings[$Model->alias]['auth'] . ')');
  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 = Router::getRequest();
  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->_defaults;
  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->validator()->add($formField, $rules['formField']);
  203. }
  204. if (!isset($Model->validate[$formFieldRepeat])) {
  205. $ruleSet = $rules['formFieldRepeat'];
  206. $ruleSet['validateIdentical']['rule'][1] = $formField;
  207. $Model->validator()->add($formFieldRepeat, $ruleSet);
  208. }
  209. if ($this->settings[$Model->alias]['current'] && !isset($Model->validate[$formFieldCurrent])) {
  210. $Model->validator()->add($formFieldCurrent, $rules['formFieldCurrent']);
  211. if (!$this->settings[$Model->alias]['allowSame']) {
  212. $Model->validator()->add($formField, 'validateNotSame', array(
  213. 'rule' => array('validateNotSame', $formField, $formFieldCurrent),
  214. 'message' => 'valErrPwdSameAsBefore',
  215. 'allowEmpty' => $this->settings[$Model->alias]['allowEmpty'],
  216. 'last' => true,
  217. ));
  218. }
  219. } elseif (!isset($Model->validate[$formFieldCurrent])) {
  220. # try to match the password against the hash in the DB
  221. if (!$this->settings[$Model->alias]['allowSame']) {
  222. $Model->validator()->add($formField, 'validateNotSame', array(
  223. 'rule' => array('validateNotSameHash', $formField),
  224. 'message' => 'valErrPwdSameAsBefore',
  225. 'allowEmpty' => $this->settings[$Model->alias]['allowEmpty'],
  226. 'last' => true,
  227. ));
  228. }
  229. }
  230. }
  231. /**
  232. * whitelisting
  233. *
  234. * @todo currently there is a cake core bug that can break functionality here
  235. * (see http://cakephp.lighthouseapp.com/projects/42648/tickets/3071-behavior-validation-methods-broken for details)
  236. * @return bool $success
  237. * 2011-07-22 ms
  238. */
  239. public function beforeValidate(Model $Model) {
  240. $formField = $this->settings[$Model->alias]['formField'];
  241. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  242. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  243. # make sure fields are set and validation rules are triggered - prevents tempering of form data
  244. if (!isset($Model->data[$Model->alias][$formField])) {
  245. $Model->data[$Model->alias][$formField] = '';
  246. }
  247. if ($this->settings[$Model->alias]['confirm'] && !isset($Model->data[$Model->alias][$formFieldRepeat])) {
  248. $Model->data[$Model->alias][$formFieldRepeat] = '';
  249. }
  250. if ($this->settings[$Model->alias]['current'] && !isset($Model->data[$Model->alias][$formFieldCurrent])) {
  251. $Model->data[$Model->alias][$formFieldCurrent] = '';
  252. }
  253. # check if we need to trigger any validation rules
  254. if ($this->settings[$Model->alias]['allowEmpty']) {
  255. $current = !empty($Model->data[$Model->alias][$formFieldCurrent]);
  256. $new = !empty($Model->data[$Model->alias][$formField]) || !empty($Model->data[$Model->alias][$formFieldRepeat]);
  257. if (!$new && !$current) {
  258. //$Model->validator()->remove($formField); // tmp only!
  259. //unset($Model->validate[$formField]);
  260. unset($Model->data[$Model->alias][$formField]);
  261. if ($this->settings[$Model->alias]['confirm']) {
  262. //$Model->validator()->remove($formFieldRepeat); // tmp only!
  263. //unset($Model->validate[$formFieldRepeat]);
  264. unset($Model->data[$Model->alias][$formFieldRepeat]);
  265. }
  266. if ($this->settings[$Model->alias]['current']) {
  267. //$Model->validator()->remove($formFieldCurrent); // tmp only!
  268. //unset($Model->validate[$formFieldCurrent]);
  269. unset($Model->data[$Model->alias][$formFieldCurrent]);
  270. }
  271. return true;
  272. }
  273. }
  274. # add fields to whitelist!
  275. $whitelist = array($this->settings[$Model->alias]['formField'], $this->settings[$Model->alias]['formFieldRepeat']);
  276. if ($this->settings[$Model->alias]['current']) {
  277. $whitelist[] = $this->settings[$Model->alias]['formFieldCurrent'];
  278. }
  279. if (!empty($Model->whitelist)) {
  280. $Model->whitelist = array_merge($Model->whitelist, $whitelist);
  281. }
  282. return true;
  283. }
  284. /**
  285. * hashing the password now
  286. * @return bool $success
  287. * 2011-07-22 ms
  288. */
  289. public function beforeSave(Model $Model) {
  290. $formField = $this->settings[$Model->alias]['formField'];
  291. $field = $this->settings[$Model->alias]['field'];
  292. $type = $this->settings[$Model->alias]['hashType'];
  293. $salt = $this->settings[$Model->alias]['hashSalt'];
  294. if (isset($Model->data[$Model->alias][$formField])) {
  295. $Model->data[$Model->alias][$field] = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  296. unset($Model->data[$Model->alias][$formField]);
  297. if ($this->settings[$Model->alias]['confirm']) {
  298. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  299. unset($Model->data[$Model->alias][$formFieldRepeat]);
  300. }
  301. if ($this->settings[$Model->alias]['current']) {
  302. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  303. unset($Model->data[$Model->alias][$formFieldCurrent]);
  304. }
  305. # update whitelist
  306. if (!empty($Model->whitelist)) {
  307. $Model->whitelist = array_merge($Model->whitelist, array($field));
  308. }
  309. }
  310. return true;
  311. }
  312. }