PasswordableBehavior.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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 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. 'customValidationRule' => null,
  65. 'customValidationMessage' => null
  66. );
  67. function __construct() {
  68. parent::__construct();
  69. $this->_validationRules = array(
  70. 'formField' => array(
  71. 'between' => array(
  72. 'rule' => array('between', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  73. 'message' => __('Your password has to be between %s and %s characters long', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  74. 'allowEmpty' => null,
  75. 'last' => true,
  76. )
  77. ),
  78. 'formFieldRepeat' => array(
  79. 'validateNotEmpty' => array(
  80. 'rule' => array('notEmpty'),
  81. 'message' => __('Please repeat your password'),
  82. 'allowEmpty' => true,
  83. 'last' => true,
  84. ),
  85. 'validateIdentical' => array(
  86. 'rule' => array('validateIdentical', 'formField'),
  87. 'message' => __('These passwords do not match'),
  88. 'allowEmpty' => null,
  89. 'last' => true,
  90. ),
  91. ),
  92. 'formFieldCurrent' => array(
  93. 'notEmpty' => array(
  94. 'rule' => array('notEmpty'),
  95. 'message' => __('Please provide your current password'),
  96. 'allowEmpty' => null,
  97. 'last' => true,
  98. ),
  99. 'validateCurrentPwd' => array(
  100. 'rule' => 'validateCurrentPwd',
  101. 'message' => __('Your current password is not correct'),
  102. 'allowEmpty' => null,
  103. 'last' => true,
  104. )
  105. )
  106. );
  107. }
  108. /**
  109. * Adding validation rules
  110. * also adds and merges config settings (direct + configure)
  111. *
  112. * @return void
  113. */
  114. public function setup(Model $Model, $config = array()) {
  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'] = __('Your password has to be between %s and %s characters', $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' => __('Please use a different password than your previous one'),
  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' => __('Please use a different password than your previous one'),
  167. 'allowEmpty' => !$this->settings[$Model->alias]['require'],
  168. 'last' => true,
  169. ));
  170. }
  171. }
  172. // Add custom rule if configured
  173. if ($this->settings[$Model->alias]['customValidationRule']) {
  174. $Model->validator()->add($formField, 'validateCustom', array(
  175. 'rule' => array('custom', $this->settings[$Model->alias]['customValidationRule']),
  176. 'message' => $this->settings[$Model->alias]['customValidationMessage'],
  177. 'last' => true,
  178. ));
  179. }
  180. }
  181. /**
  182. * Preparing the data
  183. *
  184. * @return bool Success
  185. */
  186. public function beforeValidate(Model $Model, $options = array()) {
  187. $formField = $this->settings[$Model->alias]['formField'];
  188. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  189. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  190. // Make sure fields are set and validation rules are triggered - prevents tempering of form data
  191. if (!isset($Model->data[$Model->alias][$formField])) {
  192. $Model->data[$Model->alias][$formField] = '';
  193. }
  194. if ($this->settings[$Model->alias]['confirm'] && !isset($Model->data[$Model->alias][$formFieldRepeat])) {
  195. $Model->data[$Model->alias][$formFieldRepeat] = '';
  196. }
  197. if ($this->settings[$Model->alias]['current'] && !isset($Model->data[$Model->alias][$formFieldCurrent])) {
  198. $Model->data[$Model->alias][$formFieldCurrent] = '';
  199. }
  200. // Check if we need to trigger any validation rules
  201. if (!$this->settings[$Model->alias]['require']) {
  202. $current = !empty($Model->data[$Model->alias][$formFieldCurrent]);
  203. $new = !empty($Model->data[$Model->alias][$formField]) || !empty($Model->data[$Model->alias][$formFieldRepeat]);
  204. if (!$new && !$current) {
  205. //$Model->validator()->remove($formField); // tmp only!
  206. //unset($Model->validate[$formField]);
  207. unset($Model->data[$Model->alias][$formField]);
  208. if ($this->settings[$Model->alias]['confirm']) {
  209. //$Model->validator()->remove($formFieldRepeat); // tmp only!
  210. //unset($Model->validate[$formFieldRepeat]);
  211. unset($Model->data[$Model->alias][$formFieldRepeat]);
  212. }
  213. if ($this->settings[$Model->alias]['current']) {
  214. //$Model->validator()->remove($formFieldCurrent); // tmp only!
  215. //unset($Model->validate[$formFieldCurrent]);
  216. unset($Model->data[$Model->alias][$formFieldCurrent]);
  217. }
  218. return true;
  219. }
  220. // Make sure we trigger validation if allowEmpty is set but we have the password field set
  221. if ($new) {
  222. if ($this->settings[$Model->alias]['confirm'] && empty($Model->data[$Model->alias][$formFieldRepeat])) {
  223. $Model->invalidate($formFieldRepeat, __d('tools', 'valErrPwdNotMatch'));
  224. }
  225. }
  226. }
  227. // Update whitelist
  228. $this->_modifyWhitelist($Model);
  229. return true;
  230. }
  231. /**
  232. * Hashing the password and whitelisting
  233. *
  234. * @param Model $Model
  235. * @return bool Success
  236. */
  237. public function beforeSave(Model $Model, $options = array()) {
  238. $formField = $this->settings[$Model->alias]['formField'];
  239. $field = $this->settings[$Model->alias]['field'];
  240. $type = $this->settings[$Model->alias]['hashType'];
  241. $salt = $this->settings[$Model->alias]['hashSalt'];
  242. if ($this->settings[$Model->alias]['authType'] === 'Blowfish') {
  243. $type = 'blowfish';
  244. $salt = false;
  245. }
  246. if (isset($Model->data[$Model->alias][$formField])) {
  247. if ($type === 'blowfish' && function_exists('password_hash') && !empty($this->settings[$Model->alias]['passwordHasher'])) {
  248. $cost = !empty($this->settings[$Model->alias]['hashCost']) ? $this->settings[$Model->alias]['hashCost'] : 10;
  249. $options = array('cost' => $cost);
  250. $PasswordHasher = $this->_getPasswordHasher($this->settings[$Model->alias]['passwordHasher']);
  251. $Model->data[$Model->alias][$field] = $PasswordHasher->hash($Model->data[$Model->alias][$formField], $options);
  252. } else {
  253. $Model->data[$Model->alias][$field] = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  254. }
  255. if (!$Model->data[$Model->alias][$field]) {
  256. return false;
  257. }
  258. unset($Model->data[$Model->alias][$formField]);
  259. if ($this->settings[$Model->alias]['confirm']) {
  260. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  261. unset($Model->data[$Model->alias][$formFieldRepeat]);
  262. }
  263. if ($this->settings[$Model->alias]['current']) {
  264. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  265. unset($Model->data[$Model->alias][$formFieldCurrent]);
  266. }
  267. }
  268. // Update whitelist
  269. $this->_modifyWhitelist($Model, true);
  270. return true;
  271. }
  272. /**
  273. * Checks if the PasswordHasher class supports this and if so, whether the
  274. * password needs to be rehashed or not.
  275. * This is mainly supported by Tools.Modern (using Bcrypt) yet.
  276. *
  277. * @param Model $Model
  278. * @param string $hash Currently hashed password.
  279. * @return bool Success
  280. */
  281. public function needsPasswordRehash(Model $Model, $hash) {
  282. if (empty($this->settings[$Model->alias]['passwordHasher'])) {
  283. return false;
  284. }
  285. $PasswordHasher = $this->_getPasswordHasher($this->settings[$Model->alias]['passwordHasher']);
  286. if (!method_exists($PasswordHasher, 'needsRehash')) {
  287. return false;
  288. }
  289. return $PasswordHasher->needsRehash($hash);
  290. }
  291. /**
  292. * If not implemented in AppModel
  293. *
  294. * Note: requires the used Auth component to be App::uses() loaded.
  295. * It also reqires the same Auth setup as in your AppController's beforeFilter().
  296. * So if you set up any special passwordHasher or auth type, you need to provide those
  297. * with the settings passed to the behavior:
  298. *
  299. * 'authType' => 'Blowfish', 'passwordHasher' => array(
  300. * 'className' => 'Simple',
  301. * 'hashType' => 'sha256'
  302. * )
  303. *
  304. * @throws CakeException
  305. * @param Model $Model
  306. * @param array $data
  307. * @return bool Success
  308. */
  309. public function validateCurrentPwd(Model $Model, $data) {
  310. if (is_array($data)) {
  311. $pwd = array_shift($data);
  312. } else {
  313. $pwd = $data;
  314. }
  315. $uid = null;
  316. if ($Model->id) {
  317. $uid = $Model->id;
  318. } elseif (!empty($Model->data[$Model->alias]['id'])) {
  319. $uid = $Model->data[$Model->alias]['id'];
  320. } else {
  321. trigger_error('No user id given');
  322. return false;
  323. }
  324. return $this->_validateSameHash($Model, $pwd);
  325. }
  326. /**
  327. * If not implemented in AppModel
  328. *
  329. * @param Model $Model
  330. * @param array $data
  331. * @param string $compareWith String to compare field value with
  332. * @return bool Success
  333. */
  334. public function validateIdentical(Model $Model, $data, $compareWith = null) {
  335. if (is_array($data)) {
  336. $value = array_shift($data);
  337. } else {
  338. $value = $data;
  339. }
  340. $compareValue = $Model->data[$Model->alias][$compareWith];
  341. return ($compareValue === $value);
  342. }
  343. /**
  344. * If not implemented in AppModel
  345. *
  346. * @return bool Success
  347. */
  348. public function validateNotSame(Model $Model, $data, $field1, $field2) {
  349. $value1 = $Model->data[$Model->alias][$field1];
  350. $value2 = $Model->data[$Model->alias][$field2];
  351. return ($value1 !== $value2);
  352. }
  353. /**
  354. * If not implemented in AppModel
  355. *
  356. * @return bool Success
  357. */
  358. public function validateNotSameHash(Model $Model, $data, $formField) {
  359. $field = $this->settings[$Model->alias]['field'];
  360. $type = $this->settings[$Model->alias]['hashType'];
  361. $salt = $this->settings[$Model->alias]['hashSalt'];
  362. if ($this->settings[$Model->alias]['authType'] === 'Blowfish') {
  363. $type = 'blowfish';
  364. $salt = false;
  365. }
  366. if (!isset($Model->data[$Model->alias][$Model->primaryKey])) {
  367. return true;
  368. }
  369. $primaryKey = $Model->data[$Model->alias][$Model->primaryKey];
  370. if ($type === 'blowfish' && function_exists('password_hash') && !empty($this->settings[$Model->alias]['passwordHasher'])) {
  371. $value = $Model->data[$Model->alias][$formField];
  372. } else {
  373. $value = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  374. }
  375. $dbValue = $Model->field($field, array($Model->primaryKey => $primaryKey));
  376. if (!$dbValue) {
  377. return true;
  378. }
  379. if ($type === 'blowfish' && function_exists('password_hash') && !empty($this->settings[$Model->alias]['passwordHasher'])) {
  380. $PasswordHasher = $this->_getPasswordHasher($this->settings[$Model->alias]['passwordHasher']);
  381. return !$PasswordHasher->check($value, $dbValue);
  382. }
  383. return ($value !== $dbValue);
  384. }
  385. /**
  386. * PasswordableBehavior::_validateSameHash()
  387. *
  388. * @param Model $Model
  389. * @param string $pwd
  390. * @return bool Success
  391. */
  392. protected function _validateSameHash(Model $Model, $pwd) {
  393. $field = $this->settings[$Model->alias]['field'];
  394. $type = $this->settings[$Model->alias]['hashType'];
  395. $salt = $this->settings[$Model->alias]['hashSalt'];
  396. if ($this->settings[$Model->alias]['authType'] === 'Blowfish') {
  397. $type = 'blowfish';
  398. $salt = false;
  399. }
  400. $primaryKey = $Model->data[$Model->alias][$Model->primaryKey];
  401. $dbValue = $Model->field($field, array($Model->primaryKey => $primaryKey));
  402. if (!$dbValue && $pwd) {
  403. return false;
  404. }
  405. if ($type === 'blowfish' && function_exists('password_hash') && !empty($this->settings[$Model->alias]['passwordHasher'])) {
  406. $value = $pwd;
  407. } else {
  408. if ($type === 'blowfish') {
  409. $salt = $dbValue;
  410. }
  411. $value = Security::hash($pwd, $type, $salt);
  412. }
  413. if ($type === 'blowfish' && function_exists('password_hash') && !empty($this->settings[$Model->alias]['passwordHasher'])) {
  414. $PasswordHasher = $this->_getPasswordHasher($this->settings[$Model->alias]['passwordHasher']);
  415. return $PasswordHasher->check($value, $dbValue);
  416. }
  417. return $value === $dbValue;
  418. }
  419. /**
  420. * PasswordableBehavior::_getPasswordHasher()
  421. *
  422. * @param mixed $hasher Name or options array.
  423. * @return PasswordHasher
  424. */
  425. protected function _getPasswordHasher($hasher) {
  426. $class = $hasher;
  427. $config = array();
  428. if (is_array($hasher)) {
  429. $class = $hasher['className'];
  430. unset($hasher['className']);
  431. $config = $hasher;
  432. }
  433. list($plugin, $class) = pluginSplit($class, true);
  434. $className = $class . 'PasswordHasher';
  435. App::uses($className, $plugin . 'Controller/Component/Auth');
  436. if (!class_exists($className)) {
  437. throw new CakeException(sprintf('Password hasher class "%s" was not found.', $class));
  438. }
  439. if (!is_subclass_of($className, 'AbstractPasswordHasher')) {
  440. throw new CakeException('Password hasher must extend AbstractPasswordHasher class.');
  441. }
  442. return new $className($config);
  443. }
  444. /**
  445. * Modify the model's whitelist.
  446. *
  447. * Since 2.5 behaviors can also modify the whitelist for validate, thus this behavior can now
  448. * (>= CakePHP 2.5) add the form fields automatically, as well (not just the password field itself).
  449. *
  450. * @param Model $Model
  451. * @return void
  452. */
  453. protected function _modifyWhitelist(Model $Model, $onSave = false) {
  454. $fields = array();
  455. if ($onSave) {
  456. $fields[] = $this->settings[$Model->alias]['field'];
  457. } else {
  458. $fields[] = $this->settings[$Model->alias]['formField'];
  459. if ($this->settings[$Model->alias]['confirm']) {
  460. $fields[] = $this->settings[$Model->alias]['formFieldRepeat'];
  461. }
  462. if ($this->settings[$Model->alias]['current']) {
  463. $fields[] = $this->settings[$Model->alias]['formFieldCurrent'];
  464. }
  465. }
  466. foreach ($fields as $field) {
  467. if (!empty($Model->whitelist) && !in_array($field, $Model->whitelist)) {
  468. $Model->whitelist = array_merge($Model->whitelist, array($field));
  469. }
  470. }
  471. }
  472. }