PasswordableBehavior.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. <?php
  2. App::uses('ModelBehavior', 'Model');
  3. App::uses('Router', 'Routing');
  4. App::uses('CakeResponse', 'Network');
  5. App::uses('Security', 'Utility');
  6. if (!defined('PWD_MIN_LENGTH')) {
  7. define('PWD_MIN_LENGTH', 3);
  8. }
  9. if (!defined('PWD_MAX_LENGTH')) {
  10. define('PWD_MAX_LENGTH', 20);
  11. }
  12. /**
  13. * A cakephp2 behavior to work with passwords the easy way
  14. * - complete validation
  15. * - hashing of password
  16. * - requires fields (no tempering even without security component)
  17. * - usable for edit forms (allowEmpty=>true for optional password update)
  18. *
  19. * usage: do NOT add it via $actAs = array()
  20. * attach it dynamically in only those actions where you actually change the password like so:
  21. * $this->User->Behaviors->load('Tools.Passwordable', array(SETTINGSARRAY));
  22. * as first line in any action where you want to allow the user to change his password
  23. * also add the two form fields in the form (pwd, pwd_confirm)
  24. * the rest is cake automagic :)
  25. *
  26. * now also is capable of:
  27. * - require current password prior to altering it (current=>true)
  28. * - don't allow the same password it was before (allowSame=>false)
  29. *
  30. * TODO: allowEmpty and nonEmptyToEmpty - maybe with checkbox "set_new_pwd"
  31. * feel free to help me out
  32. *
  33. * @version 1.6 (renamed from ChangePassword to Passwordable)
  34. * @author Mark Scherer
  35. * @link http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp
  36. * @license MIT
  37. * 2012-08-18 ms
  38. */
  39. class PasswordableBehavior extends ModelBehavior {
  40. /**
  41. * @access public
  42. */
  43. public $settings = array();
  44. /**
  45. * @access protected
  46. */
  47. protected $_defaultSettings = array(
  48. 'field' => 'password',
  49. 'confirm' => true, # set to false if in admin view and no confirmation (pwd_repeat) is required
  50. 'allowEmpty' => false, # if password must be provided or be changed (set to true for update sites)
  51. 'current' => false, # expect the current password for security purposes
  52. 'formField' => 'pwd',
  53. 'formFieldRepeat' => 'pwd_repeat',
  54. 'formFieldCurrent' => 'pwd_current',
  55. 'hashType' => null,
  56. 'hashSalt' => true,
  57. 'auth' => null, # which component (defaults to AuthComponent),
  58. 'allowSame' => true, # dont allow the old password on change,
  59. 'minLength' => PWD_MIN_LENGTH,
  60. 'maxLength' => PWD_MAX_LENGTH
  61. );
  62. /**
  63. * @access protected
  64. */
  65. protected $_validationRules = array(
  66. 'formField' => array(
  67. 'between' => array(
  68. 'rule' => array('between', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  69. 'message' => array('valErrBetweenCharacters %s %s', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  70. 'allowEmpty' => null,
  71. 'last' => true,
  72. )
  73. ),
  74. 'formFieldRepeat' => array(
  75. 'between' => array(
  76. 'rule' => array('between', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  77. 'message' => array('valErrBetweenCharacters %s %s', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  78. 'allowEmpty' => null,
  79. 'last' => true,
  80. ),
  81. 'validateIdentical' => array(
  82. 'rule' => array('validateIdentical', 'formField'),
  83. 'message' => 'valErrPwdNotMatch',
  84. 'allowEmpty' => null,
  85. 'last' => true,
  86. ),
  87. ),
  88. 'formFieldCurrent' => array(
  89. 'notEmpty' => array(
  90. 'rule' => array('notEmpty'),
  91. 'message' => 'valErrProvideCurrentPwd',
  92. 'allowEmpty' => null,
  93. 'last' => true,
  94. ),
  95. 'validateCurrentPwd' => array(
  96. 'rule' => 'validateCurrentPwd',
  97. 'message' => 'valErrCurrentPwdIncorrect',
  98. 'allowEmpty' => null,
  99. 'last' => true,
  100. )
  101. ),
  102. );
  103. /**
  104. * if not implemented in AppModel
  105. * @throws CakeException
  106. * @return bool $success
  107. * 2011-07-22 ms
  108. */
  109. public function validateCurrentPwd(Model $Model, $data) {
  110. if (is_array($data)) {
  111. $pwd = array_shift($data);
  112. } else {
  113. $pwd = $data;
  114. }
  115. $uid = null;
  116. if ($Model->id) {
  117. $uid = $Model->id;
  118. } elseif (!empty($Model->data[$Model->alias]['id'])) {
  119. $uid = $Model->data[$Model->alias]['id'];
  120. } else {
  121. trigger_error('No user id given');
  122. return false;
  123. }
  124. if (empty($this->settings[$Model->alias]['auth']) && class_exists('AuthExtComponent')) {
  125. $this->Auth = new AuthExtComponent(new ComponentCollection());
  126. } elseif (class_exists(($this->settings[$Model->alias]['auth'] ? $this->settings[$Model->alias]['auth'] : 'Auth') . 'Component')) {
  127. $auth = $this->settings[$Model->alias]['auth'].'Component';
  128. $this->Auth = new $auth(new ComponentCollection());
  129. } else {
  130. throw new CakeException('No Authentication class found (' . $this->settings[$Model->alias]['auth'] . ')');
  131. }
  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->_defaultSettings;
  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. }