PasswordableBehavior.php 18 KB

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