PasswordableBehavior.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. <?php
  2. App::uses('ModelBehavior', 'Model');
  3. App::uses('Security', 'Utility');
  4. // @deprecated Use Configure settings instead.
  5. if (!defined('PWD_MIN_LENGTH')) {
  6. define('PWD_MIN_LENGTH', 6);
  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 (require=>false 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. * Also note that you can apply global settings via Configure key 'Passwordable', as well,
  26. * if you don't want to manually pass them along each time you use the behavior. This also
  27. * keeps the code clean and lean.
  28. *
  29. * Now also is capable of:
  30. * - Require current password prior to altering it (current=>true)
  31. * - Don't allow the same password it was before (allowSame=>false)
  32. * - Support different auth types and password hashing algorythms
  33. * - PasswordHasher support
  34. * - Tools.Modern PasswordHasher and password_hash()/password_verify() support
  35. *
  36. * @version 1.8 (Now supports Tools.Modern PasswordHasher and password_hash() method)
  37. * @author Mark Scherer
  38. * @link http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp
  39. * @license MIT
  40. */
  41. class PasswordableBehavior extends ModelBehavior {
  42. /**
  43. * @var array
  44. */
  45. protected $_defaultConfig = array(
  46. 'field' => 'password',
  47. 'confirm' => true, // Set to false if in admin view and no confirmation (pwd_repeat) is required
  48. 'require' => true, // If a password change is required (set to false for edit forms, leave it true for pure password update forms)
  49. 'allowEmpty' => false, // Deprecated, do NOT use anymore! Use require instead!
  50. 'current' => false, // Enquire the current password for security purposes
  51. 'formField' => 'pwd',
  52. 'formFieldRepeat' => 'pwd_repeat',
  53. 'formFieldCurrent' => 'pwd_current',
  54. 'userModel' => null, // Defaults to User
  55. 'hashType' => null, // Only for authType Form [Cake2.3]
  56. 'hashSalt' => true, // Only for authType Form [Cake2.3]
  57. 'auth' => null, // Which component (defaults to AuthComponent),
  58. 'authType' => 'Form', // Which type of authenticate (Form, Blowfish, ...) [Cake2.4+]
  59. 'passwordHasher' => null, // If a custom pwd hasher is been used [Cake2.4+]
  60. 'allowSame' => true, // Don't allow the old password on change
  61. 'minLength' => PWD_MIN_LENGTH,
  62. 'maxLength' => PWD_MAX_LENGTH
  63. );
  64. /**
  65. * @var array
  66. */
  67. protected $_validationRules = array(
  68. 'formField' => array(
  69. 'between' => array(
  70. 'rule' => array('between', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  71. 'message' => array('valErrBetweenCharacters %s %s', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  72. 'allowEmpty' => null,
  73. 'last' => true,
  74. )
  75. ),
  76. 'formFieldRepeat' => array(
  77. 'between' => array(
  78. 'rule' => array('between', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  79. 'message' => array('valErrBetweenCharacters %s %s', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  80. 'allowEmpty' => null,
  81. 'last' => true,
  82. ),
  83. 'validateIdentical' => array(
  84. 'rule' => array('validateIdentical', 'formField'),
  85. 'message' => 'valErrPwdNotMatch',
  86. 'allowEmpty' => null,
  87. 'last' => true,
  88. ),
  89. ),
  90. 'formFieldCurrent' => array(
  91. 'notEmpty' => array(
  92. 'rule' => array('notEmpty'),
  93. 'message' => 'valErrProvideCurrentPwd',
  94. 'allowEmpty' => null,
  95. 'last' => true,
  96. ),
  97. 'validateCurrentPwd' => array(
  98. 'rule' => 'validateCurrentPwd',
  99. 'message' => 'valErrCurrentPwdIncorrect',
  100. 'allowEmpty' => null,
  101. 'last' => true,
  102. )
  103. ),
  104. );
  105. /**
  106. * If not implemented in AppModel
  107. *
  108. * Note: requires the used Auth component to be App::uses() loaded.
  109. * It also reqires the same Auth setup as in your AppController's beforeFilter().
  110. * So if you set up any special passwordHasher or auth type, you need to provide those
  111. * with the settings passed to the behavior:
  112. *
  113. * 'authType' => 'Blowfish', 'passwordHasher' => array(
  114. * 'className' => 'Simple',
  115. * 'hashType' => 'sha256'
  116. * )
  117. *
  118. * @throws CakeException
  119. * @param Model $Model
  120. * @param array $data
  121. * @return bool Success
  122. */
  123. public function validateCurrentPwd(Model $Model, $data) {
  124. if (is_array($data)) {
  125. $pwd = array_shift($data);
  126. } else {
  127. $pwd = $data;
  128. }
  129. $uid = null;
  130. if ($Model->id) {
  131. $uid = $Model->id;
  132. } elseif (!empty($Model->data[$Model->alias]['id'])) {
  133. $uid = $Model->data[$Model->alias]['id'];
  134. } else {
  135. trigger_error('No user id given');
  136. return false;
  137. }
  138. return $this->_validateSameHash($Model, $pwd);
  139. if (!empty($this->settings[$Model->alias]['passwordHasher'])) {
  140. $authConfig['passwordHasher'] = $this->settings[$Model->alias]['passwordHasher'];
  141. }
  142. $this->Auth->authenticate = array(
  143. $this->settings[$Model->alias]['authType'] => $authConfig
  144. );
  145. }
  146. /**
  147. * If not implemented in AppModel
  148. *
  149. * @param Model $Model
  150. * @param array $data
  151. * @param string $compareWith String to compare field value with
  152. * @return bool Success
  153. */
  154. public function validateIdentical(Model $Model, $data, $compareWith = null) {
  155. if (is_array($data)) {
  156. $value = array_shift($data);
  157. } else {
  158. $value = $data;
  159. }
  160. $compareValue = $Model->data[$Model->alias][$compareWith];
  161. return ($compareValue === $value);
  162. }
  163. /**
  164. * If not implemented in AppModel
  165. *
  166. * @return bool Success
  167. */
  168. public function validateNotSame(Model $Model, $data, $field1, $field2) {
  169. $value1 = $Model->data[$Model->alias][$field1];
  170. $value2 = $Model->data[$Model->alias][$field2];
  171. return ($value1 !== $value2);
  172. }
  173. /**
  174. * If not implemented in AppModel
  175. *
  176. * @return bool Success
  177. */
  178. public function validateNotSameHash(Model $Model, $data, $formField) {
  179. $field = $this->settings[$Model->alias]['field'];
  180. $type = $this->settings[$Model->alias]['hashType'];
  181. $salt = $this->settings[$Model->alias]['hashSalt'];
  182. if ($this->settings[$Model->alias]['authType'] === 'Blowfish') {
  183. $type = 'blowfish';
  184. $salt = false;
  185. }
  186. if (!isset($Model->data[$Model->alias][$Model->primaryKey])) {
  187. return true;
  188. }
  189. $primaryKey = $Model->data[$Model->alias][$Model->primaryKey];
  190. if ($type === 'blowfish' && function_exists('password_hash') && !empty($this->settings[$Model->alias]['passwordHasher'])) {
  191. $value = $Model->data[$Model->alias][$formField];
  192. } else {
  193. $value = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  194. }
  195. $dbValue = $Model->field($field, array($Model->primaryKey => $primaryKey));
  196. if (!$dbValue) {
  197. return true;
  198. }
  199. if ($type === 'blowfish' && function_exists('password_hash') && !empty($this->settings[$Model->alias]['passwordHasher'])) {
  200. $PasswordHasher = $this->_getPasswordHasher($this->settings[$Model->alias]['passwordHasher']);
  201. return !$PasswordHasher->check($value, $dbValue);
  202. }
  203. return ($value !== $dbValue);
  204. }
  205. /**
  206. * PasswordableBehavior::_validateSameHash()
  207. *
  208. * @param Model $Model
  209. * @param string $pwd
  210. * @return bool Success
  211. */
  212. protected function _validateSameHash(Model $Model, $pwd) {
  213. $field = $this->settings[$Model->alias]['field'];
  214. $type = $this->settings[$Model->alias]['hashType'];
  215. $salt = $this->settings[$Model->alias]['hashSalt'];
  216. if ($this->settings[$Model->alias]['authType'] === 'Blowfish') {
  217. $type = 'blowfish';
  218. $salt = false;
  219. }
  220. $primaryKey = $Model->data[$Model->alias][$Model->primaryKey];
  221. $dbValue = $Model->field($field, array($Model->primaryKey => $primaryKey));
  222. if (!$dbValue && $pwd) {
  223. return false;
  224. }
  225. if ($type === 'blowfish' && function_exists('password_hash') && !empty($this->settings[$Model->alias]['passwordHasher'])) {
  226. $value = $pwd;
  227. } else {
  228. if ($type === 'blowfish') {
  229. $salt = $dbValue;
  230. }
  231. $value = Security::hash($pwd, $type, $salt);
  232. }
  233. if ($type === 'blowfish' && function_exists('password_hash') && !empty($this->settings[$Model->alias]['passwordHasher'])) {
  234. $PasswordHasher = $this->_getPasswordHasher($this->settings[$Model->alias]['passwordHasher']);
  235. return $PasswordHasher->check($value, $dbValue);
  236. }
  237. return $value === $dbValue;
  238. }
  239. /**
  240. * PasswordableBehavior::_getPasswordHasher()
  241. *
  242. * @param mixed $hasher Name or options array.
  243. * @return PasswordHasher
  244. */
  245. protected function _getPasswordHasher($hasher) {
  246. $class = $hasher;
  247. $config = array();
  248. if (is_array($hasher)) {
  249. $class = $hasher['className'];
  250. unset($hasher['className']);
  251. $config = $hasher;
  252. }
  253. list($plugin, $class) = pluginSplit($class, true);
  254. $className = $class . 'PasswordHasher';
  255. App::uses($className, $plugin . 'Controller/Component/Auth');
  256. if (!class_exists($className)) {
  257. throw new CakeException(__d('cake_dev', 'Password hasher class "%s" was not found.', $class));
  258. }
  259. if (!is_subclass_of($className, 'AbstractPasswordHasher')) {
  260. throw new CakeException(__d('cake_dev', 'Password hasher must extend AbstractPasswordHasher class.'));
  261. }
  262. return new $className($config);
  263. }
  264. /**
  265. * Adding validation rules
  266. * also adds and merges config settings (direct + configure)
  267. *
  268. * @return void
  269. */
  270. public function setup(Model $Model, $config = array()) {
  271. $defaults = $this->_defaultConfig;
  272. if ($configureDefaults = Configure::read('Passwordable')) {
  273. $defaults = $configureDefaults + $defaults;
  274. }
  275. $this->settings[$Model->alias] = $config + $defaults;
  276. // BC comp
  277. if ($this->settings[$Model->alias]['allowEmpty']) {
  278. $this->settings[$Model->alias]['require'] = false;
  279. }
  280. $formField = $this->settings[$Model->alias]['formField'];
  281. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  282. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  283. if ($formField === $this->settings[$Model->alias]['field']) {
  284. throw new CakeException('Invalid setup - the form field must to be different from the model field (' . $this->settings[$Model->alias]['field'] . ').');
  285. }
  286. $rules = $this->_validationRules;
  287. foreach ($rules as $field => $fieldRules) {
  288. foreach ($fieldRules as $key => $rule) {
  289. $rule['allowEmpty'] = !$this->settings[$Model->alias]['require'];
  290. if ($key === 'between') {
  291. $rule['rule'][1] = $this->settings[$Model->alias]['minLength'];
  292. $rule['message'][1] = $this->settings[$Model->alias]['minLength'];
  293. $rule['rule'][2] = $this->settings[$Model->alias]['maxLength'];
  294. $rule['message'][2] = $this->settings[$Model->alias]['maxLength'];
  295. }
  296. $fieldRules[$key] = $rule;
  297. }
  298. $rules[$field] = $fieldRules;
  299. }
  300. // Add the validation rules if not already attached
  301. if (!isset($Model->validate[$formField])) {
  302. $Model->validator()->add($formField, $rules['formField']);
  303. }
  304. if (!isset($Model->validate[$formFieldRepeat])) {
  305. $ruleSet = $rules['formFieldRepeat'];
  306. $ruleSet['validateIdentical']['rule'][1] = $formField;
  307. $Model->validator()->add($formFieldRepeat, $ruleSet);
  308. }
  309. if ($this->settings[$Model->alias]['current'] && !isset($Model->validate[$formFieldCurrent])) {
  310. $Model->validator()->add($formFieldCurrent, $rules['formFieldCurrent']);
  311. if (!$this->settings[$Model->alias]['allowSame']) {
  312. $Model->validator()->add($formField, 'validateNotSame', array(
  313. 'rule' => array('validateNotSame', $formField, $formFieldCurrent),
  314. 'message' => 'valErrPwdSameAsBefore',
  315. 'allowEmpty' => !$this->settings[$Model->alias]['require'],
  316. 'last' => true,
  317. ));
  318. }
  319. } elseif (!isset($Model->validate[$formFieldCurrent])) {
  320. // Try to match the password against the hash in the DB
  321. if (!$this->settings[$Model->alias]['allowSame']) {
  322. $Model->validator()->add($formField, 'validateNotSame', array(
  323. 'rule' => array('validateNotSameHash', $formField),
  324. 'message' => 'valErrPwdSameAsBefore',
  325. 'allowEmpty' => !$this->settings[$Model->alias]['require'],
  326. 'last' => true,
  327. ));
  328. }
  329. }
  330. }
  331. /**
  332. * Preparing the data
  333. *
  334. * @return bool Success
  335. */
  336. public function beforeValidate(Model $Model, $options = array()) {
  337. $formField = $this->settings[$Model->alias]['formField'];
  338. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  339. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  340. // Make sure fields are set and validation rules are triggered - prevents tempering of form data
  341. if (!isset($Model->data[$Model->alias][$formField])) {
  342. $Model->data[$Model->alias][$formField] = '';
  343. }
  344. if ($this->settings[$Model->alias]['confirm'] && !isset($Model->data[$Model->alias][$formFieldRepeat])) {
  345. $Model->data[$Model->alias][$formFieldRepeat] = '';
  346. }
  347. if ($this->settings[$Model->alias]['current'] && !isset($Model->data[$Model->alias][$formFieldCurrent])) {
  348. $Model->data[$Model->alias][$formFieldCurrent] = '';
  349. }
  350. // Check if we need to trigger any validation rules
  351. if (!$this->settings[$Model->alias]['require']) {
  352. $current = !empty($Model->data[$Model->alias][$formFieldCurrent]);
  353. $new = !empty($Model->data[$Model->alias][$formField]) || !empty($Model->data[$Model->alias][$formFieldRepeat]);
  354. if (!$new && !$current) {
  355. //$Model->validator()->remove($formField); // tmp only!
  356. //unset($Model->validate[$formField]);
  357. unset($Model->data[$Model->alias][$formField]);
  358. if ($this->settings[$Model->alias]['confirm']) {
  359. //$Model->validator()->remove($formFieldRepeat); // tmp only!
  360. //unset($Model->validate[$formFieldRepeat]);
  361. unset($Model->data[$Model->alias][$formFieldRepeat]);
  362. }
  363. if ($this->settings[$Model->alias]['current']) {
  364. //$Model->validator()->remove($formFieldCurrent); // tmp only!
  365. //unset($Model->validate[$formFieldCurrent]);
  366. unset($Model->data[$Model->alias][$formFieldCurrent]);
  367. }
  368. return true;
  369. }
  370. // Make sure we trigger validation if allowEmpty is set but we have the password field set
  371. if ($new) {
  372. if ($this->settings[$Model->alias]['confirm'] && empty($Model->data[$Model->alias][$formFieldRepeat])) {
  373. $Model->invalidate($formFieldRepeat, __('valErrPwdNotMatch'));
  374. }
  375. }
  376. }
  377. // Update whitelist
  378. $this->_modifyWhitelist($Model);
  379. return true;
  380. }
  381. /**
  382. * Hashing the password and whitelisting
  383. *
  384. * @param Model $Model
  385. * @return bool Success
  386. */
  387. public function beforeSave(Model $Model, $options = array()) {
  388. $formField = $this->settings[$Model->alias]['formField'];
  389. $field = $this->settings[$Model->alias]['field'];
  390. $type = $this->settings[$Model->alias]['hashType'];
  391. $salt = $this->settings[$Model->alias]['hashSalt'];
  392. if ($this->settings[$Model->alias]['authType'] === 'Blowfish') {
  393. $type = 'blowfish';
  394. $salt = false;
  395. }
  396. if (isset($Model->data[$Model->alias][$formField])) {
  397. if ($type === 'blowfish' && function_exists('password_hash') && !empty($this->settings[$Model->alias]['passwordHasher'])) {
  398. $cost = !empty($this->settings[$Model->alias]['hashCost']) ? $this->settings[$Model->alias]['hashCost'] : 10;
  399. $options = array('cost' => $cost);
  400. $PasswordHasher = $this->_getPasswordHasher($this->settings[$Model->alias]['passwordHasher']);
  401. $Model->data[$Model->alias][$field] = $PasswordHasher->hash($Model->data[$Model->alias][$formField], $options);
  402. } else {
  403. $Model->data[$Model->alias][$field] = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  404. }
  405. if (!$Model->data[$Model->alias][$field]) {
  406. return false;
  407. }
  408. unset($Model->data[$Model->alias][$formField]);
  409. if ($this->settings[$Model->alias]['confirm']) {
  410. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  411. unset($Model->data[$Model->alias][$formFieldRepeat]);
  412. }
  413. if ($this->settings[$Model->alias]['current']) {
  414. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  415. unset($Model->data[$Model->alias][$formFieldCurrent]);
  416. }
  417. }
  418. // Update whitelist
  419. $this->_modifyWhitelist($Model, true);
  420. return true;
  421. }
  422. /**
  423. * Modify the model's whitelist.
  424. *
  425. * Since 2.5 behaviors can also modify the whitelist for validate, thus this behavior can now
  426. * (>= CakePHP 2.5) add the form fields automatically, as well (not just the password field itself).
  427. *
  428. * @param Model $Model
  429. * @return void
  430. */
  431. protected function _modifyWhitelist(Model $Model, $onSave = false) {
  432. $fields = array();
  433. if ($onSave) {
  434. $fields[] = $this->settings[$Model->alias]['field'];
  435. } else {
  436. $fields[] = $this->settings[$Model->alias]['formField'];
  437. if ($this->settings[$Model->alias]['confirm']) {
  438. $fields[] = $this->settings[$Model->alias]['formFieldRepeat'];
  439. }
  440. if ($this->settings[$Model->alias]['current']) {
  441. $fields[] = $this->settings[$Model->alias]['formFieldCurrent'];
  442. }
  443. }
  444. foreach ($fields as $field) {
  445. if (!empty($Model->whitelist) && !in_array($field, $Model->whitelist)) {
  446. $Model->whitelist = array_merge($Model->whitelist, array($field));
  447. }
  448. }
  449. }
  450. }