PasswordableBehavior.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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 public
  43. */
  44. public $settings = array();
  45. /**
  46. * @access protected
  47. */
  48. protected $_defaultSettings = array(
  49. 'field' => 'password',
  50. 'confirm' => true, # set to false if in admin view and no confirmation (pwd_repeat) is required
  51. 'allowEmpty' => false, # if password must be provided or be changed (set to true for update sites)
  52. 'current' => false, # expect the current password for security purposes
  53. 'formField' => 'pwd',
  54. 'formFieldRepeat' => 'pwd_repeat',
  55. 'formFieldCurrent' => 'pwd_current',
  56. 'hashType' => null,
  57. 'hashSalt' => true,
  58. 'auth' => null, # which component (defaults to AuthComponent),
  59. 'allowSame' => true, # dont allow the old password on change,
  60. 'minLength' => PWD_MIN_LENGTH,
  61. 'maxLength' => PWD_MAX_LENGTH
  62. );
  63. /**
  64. * @access protected
  65. */
  66. protected $_validationRules = array(
  67. 'formField' => array(
  68. 'between' => array(
  69. 'rule' => array('between', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  70. 'message' => array('valErrBetweenCharacters %s %s', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  71. 'allowEmpty' => null,
  72. 'last' => true,
  73. )
  74. ),
  75. 'formFieldRepeat' => array(
  76. 'between' => array(
  77. 'rule' => array('between', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  78. 'message' => array('valErrBetweenCharacters %s %s', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  79. 'allowEmpty' => null,
  80. 'last' => true,
  81. ),
  82. 'validateIdentical' => array(
  83. 'rule' => array('validateIdentical', 'formField'),
  84. 'message' => 'valErrPwdNotMatch',
  85. 'allowEmpty' => null,
  86. 'last' => true,
  87. ),
  88. ),
  89. 'formFieldCurrent' => array(
  90. 'notEmpty' => array(
  91. 'rule' => array('notEmpty'),
  92. 'message' => 'valErrProvideCurrentPwd',
  93. 'allowEmpty' => null,
  94. 'last' => true,
  95. ),
  96. 'validateCurrentPwd' => array(
  97. 'rule' => 'validateCurrentPwd',
  98. 'message' => 'valErrCurrentPwdIncorrect',
  99. 'allowEmpty' => null,
  100. 'last' => true,
  101. )
  102. ),
  103. );
  104. /**
  105. * if not implemented in AppModel
  106. * @throws CakeException
  107. * @return bool $success
  108. * 2011-07-22 ms
  109. */
  110. public function validateCurrentPwd(Model $Model, $data) {
  111. if (is_array($data)) {
  112. $pwd = array_shift($data);
  113. } else {
  114. $pwd = $data;
  115. }
  116. $uid = null;
  117. if ($Model->id) {
  118. $uid = $Model->id;
  119. } elseif (!empty($Model->data[$Model->alias]['id'])) {
  120. $uid = $Model->data[$Model->alias]['id'];
  121. } else {
  122. trigger_error('No user id given');
  123. return false;
  124. }
  125. if (empty($this->settings[$Model->alias]['auth']) && class_exists('AuthExtComponent')) {
  126. $this->Auth = new AuthExtComponent(new ComponentCollection());
  127. } elseif (class_exists(($this->settings[$Model->alias]['auth'] ? $this->settings[$Model->alias]['auth'] : 'Auth') . 'Component')) {
  128. $auth = $this->settings[$Model->alias]['auth'].'Component';
  129. $this->Auth = new $auth(new ComponentCollection());
  130. } else {
  131. throw new CakeException('No Authentication class found (' . $this->settings[$Model->alias]['auth'] . ')');
  132. }
  133. # easiest authenticate method via form and (id + pwd)
  134. $this->Auth->authenticate = array(
  135. 'Form' => array(
  136. 'fields'=>array('username' => 'id', 'password'=>$this->settings[$Model->alias]['field'])
  137. )
  138. );
  139. $request = Router::getRequest();
  140. $request->data['User'] = array('id'=>$uid, 'password'=>$pwd);
  141. $response = new CakeResponse();
  142. return (bool)$this->Auth->identify($request, $response);
  143. }
  144. /**
  145. * if not implemented in AppModel
  146. * @return bool $success
  147. * 2011-07-22 ms
  148. */
  149. public function validateIdentical(Model $Model, $data, $compareWith = null) {
  150. if (is_array($data)) {
  151. $value = array_shift($data);
  152. } else {
  153. $value = $data;
  154. }
  155. $compareValue = $Model->data[$Model->alias][$compareWith];
  156. return ($compareValue === $value);
  157. }
  158. /**
  159. * if not implemented in AppModel
  160. * @return bool $success
  161. * 2011-11-10 ms
  162. */
  163. public function validateNotSame(Model $Model, $data, $field1, $field2) {
  164. $value1 = $Model->data[$Model->alias][$field1];
  165. $value2 = $Model->data[$Model->alias][$field2];
  166. return ($value1 !== $value2);
  167. }
  168. /**
  169. * if not implemented in AppModel
  170. * @return bool $success
  171. * 2011-11-10 ms
  172. */
  173. public function validateNotSameHash(Model $Model, $data, $formField) {
  174. $field = $this->settings[$Model->alias]['field'];
  175. $type = $this->settings[$Model->alias]['hashType'];
  176. $salt = $this->settings[$Model->alias]['hashSalt'];
  177. if (!isset($Model->data[$Model->alias][$Model->primaryKey])) {
  178. return true;
  179. }
  180. $primaryKey = $Model->data[$Model->alias][$Model->primaryKey];
  181. $value = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  182. $dbValue = $Model->field($field, array($Model->primaryKey => $primaryKey));
  183. if (!$dbValue) {
  184. return true;
  185. }
  186. return ($value !== $dbValue);
  187. }
  188. /**
  189. * adding validation rules
  190. * also adds and merges config settings (direct + configure)
  191. * @return void
  192. * 2011-08-24 ms
  193. */
  194. public function setup(Model $Model, $config = array()) {
  195. $defaults = $this->_defaultSettings;
  196. if ($configureDefaults = Configure::read('Passwordable')) {
  197. $defaults = Set::merge($defaults, $configureDefaults);
  198. }
  199. $this->settings[$Model->alias] = Set::merge($defaults, $config);
  200. $formField = $this->settings[$Model->alias]['formField'];
  201. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  202. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  203. $rules = $this->_validationRules;
  204. # add the validation rules if not already attached
  205. if (!isset($Model->validate[$formField])) {
  206. $Model->validator()->add($formField, $rules['formField']);
  207. }
  208. if (!isset($Model->validate[$formFieldRepeat])) {
  209. $ruleSet = $rules['formFieldRepeat'];
  210. $ruleSet['validateIdentical']['rule'][1] = $formField;
  211. $Model->validator()->add($formFieldRepeat, $ruleSet);
  212. }
  213. if ($this->settings[$Model->alias]['current'] && !isset($Model->validate[$formFieldCurrent])) {
  214. $Model->validator()->add($formFieldCurrent, $rules['formFieldCurrent']);
  215. if (!$this->settings[$Model->alias]['allowSame']) {
  216. $Model->validator()->add($formField, 'validateNotSame', array(
  217. 'rule' => array('validateNotSame', $formField, $formFieldCurrent),
  218. 'message' => 'valErrPwdSameAsBefore',
  219. 'allowEmpty' => $this->settings[$Model->alias]['allowEmpty'],
  220. 'last' => true,
  221. ));
  222. }
  223. } elseif (!isset($Model->validate[$formFieldCurrent])) {
  224. # try to match the password against the hash in the DB
  225. if (!$this->settings[$Model->alias]['allowSame']) {
  226. $Model->validator()->add($formField, 'validateNotSame', array(
  227. 'rule' => array('validateNotSameHash', $formField),
  228. 'message' => 'valErrPwdSameAsBefore',
  229. 'allowEmpty' => $this->settings[$Model->alias]['allowEmpty'],
  230. 'last' => true,
  231. ));
  232. }
  233. }
  234. }
  235. /**
  236. * whitelisting
  237. *
  238. * @todo currently there is a cake core bug that can break functionality here
  239. * (see http://cakephp.lighthouseapp.com/projects/42648/tickets/3071-behavior-validation-methods-broken for details)
  240. * @return bool $success
  241. * 2011-07-22 ms
  242. */
  243. public function beforeValidate(Model $Model) {
  244. $formField = $this->settings[$Model->alias]['formField'];
  245. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  246. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  247. # make sure fields are set and validation rules are triggered - prevents tempering of form data
  248. if (!isset($Model->data[$Model->alias][$formField])) {
  249. $Model->data[$Model->alias][$formField] = '';
  250. }
  251. if ($this->settings[$Model->alias]['confirm'] && !isset($Model->data[$Model->alias][$formFieldRepeat])) {
  252. $Model->data[$Model->alias][$formFieldRepeat] = '';
  253. }
  254. if ($this->settings[$Model->alias]['current'] && !isset($Model->data[$Model->alias][$formFieldCurrent])) {
  255. $Model->data[$Model->alias][$formFieldCurrent] = '';
  256. }
  257. # check if we need to trigger any validation rules
  258. if ($this->settings[$Model->alias]['allowEmpty']) {
  259. $current = !empty($Model->data[$Model->alias][$formFieldCurrent]);
  260. $new = !empty($Model->data[$Model->alias][$formField]) || !empty($Model->data[$Model->alias][$formFieldRepeat]);
  261. if (!$new && !$current) {
  262. //$Model->validator()->remove($formField); // tmp only!
  263. //unset($Model->validate[$formField]);
  264. unset($Model->data[$Model->alias][$formField]);
  265. if ($this->settings[$Model->alias]['confirm']) {
  266. //$Model->validator()->remove($formFieldRepeat); // tmp only!
  267. //unset($Model->validate[$formFieldRepeat]);
  268. unset($Model->data[$Model->alias][$formFieldRepeat]);
  269. }
  270. if ($this->settings[$Model->alias]['current']) {
  271. //$Model->validator()->remove($formFieldCurrent); // tmp only!
  272. //unset($Model->validate[$formFieldCurrent]);
  273. unset($Model->data[$Model->alias][$formFieldCurrent]);
  274. }
  275. return true;
  276. }
  277. }
  278. # add fields to whitelist!
  279. $whitelist = array($this->settings[$Model->alias]['formField'], $this->settings[$Model->alias]['formFieldRepeat']);
  280. if ($this->settings[$Model->alias]['current']) {
  281. $whitelist[] = $this->settings[$Model->alias]['formFieldCurrent'];
  282. }
  283. if (!empty($Model->whitelist)) {
  284. $Model->whitelist = array_merge($Model->whitelist, $whitelist);
  285. }
  286. return true;
  287. }
  288. /**
  289. * hashing the password now
  290. * @return bool $success
  291. * 2011-07-22 ms
  292. */
  293. public function beforeSave(Model $Model) {
  294. $formField = $this->settings[$Model->alias]['formField'];
  295. $field = $this->settings[$Model->alias]['field'];
  296. $type = $this->settings[$Model->alias]['hashType'];
  297. $salt = $this->settings[$Model->alias]['hashSalt'];
  298. if (isset($Model->data[$Model->alias][$formField])) {
  299. $Model->data[$Model->alias][$field] = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  300. unset($Model->data[$Model->alias][$formField]);
  301. if ($this->settings[$Model->alias]['confirm']) {
  302. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  303. unset($Model->data[$Model->alias][$formFieldRepeat]);
  304. }
  305. if ($this->settings[$Model->alias]['current']) {
  306. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  307. unset($Model->data[$Model->alias][$formFieldCurrent]);
  308. }
  309. # update whitelist
  310. if (!empty($Model->whitelist)) {
  311. $Model->whitelist = array_merge($Model->whitelist, array($field));
  312. }
  313. }
  314. return true;
  315. }
  316. }