PasswordableBehavior.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. <?php
  2. namespace Tools\Model\Behavior;
  3. use Cake\Auth\PasswordHasherFactory;
  4. use Cake\Core\Configure;
  5. use Cake\Event\Event;
  6. use Cake\ORM\Behavior;
  7. use Cake\ORM\Entity;
  8. use Cake\ORM\Table;
  9. if (!defined('PWD_MIN_LENGTH')) {
  10. define('PWD_MIN_LENGTH', 6);
  11. }
  12. if (!defined('PWD_MAX_LENGTH')) {
  13. define('PWD_MAX_LENGTH', 20);
  14. }
  15. /**
  16. * A CakePHP behavior to work with passwords the easy way
  17. * - complete validation
  18. * - hashing of password
  19. * - requires fields (no tempering even without security component)
  20. * - usable for edit forms (require=>false for optional password update)
  21. *
  22. * Also capable of:
  23. * - Require current password prior to altering it (current=>true)
  24. * - Don't allow the same password it was before (allowSame=>false)
  25. *
  26. * Usage: See docs
  27. *
  28. * @author Mark Scherer
  29. * @link http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp
  30. * @license MIT
  31. */
  32. class PasswordableBehavior extends Behavior {
  33. /**
  34. * @var array
  35. */
  36. protected $_defaultConfig = array(
  37. 'field' => 'password',
  38. 'confirm' => true, // Set to false if in admin view and no confirmation (pwd_repeat) is required
  39. 'require' => true, // If a password change is required (set to false for edit forms, leave it true for pure password update forms)
  40. 'current' => false, // Enquire the current password for security purposes
  41. 'formField' => 'pwd',
  42. 'formFieldRepeat' => 'pwd_repeat',
  43. 'formFieldCurrent' => 'pwd_current',
  44. 'passwordHasher' => 'Default', // If a custom pwd hasher is been used
  45. 'allowSame' => true, // Don't allow the old password on change
  46. 'minLength' => PWD_MIN_LENGTH,
  47. 'maxLength' => PWD_MAX_LENGTH,
  48. 'validator' => 'default'
  49. );
  50. /**
  51. * @var array
  52. */
  53. protected $_validationRules = array(
  54. 'formField' => array(
  55. 'between' => array(
  56. 'rule' => array('lengthBetween', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  57. 'message' => array('valErrBetweenCharacters {0} {1}', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  58. 'last' => true,
  59. //'provider' => 'table'
  60. )
  61. ),
  62. 'formFieldRepeat' => array(
  63. 'between' => array(
  64. 'rule' => array('lengthBetween', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  65. 'message' => array('valErrBetweenCharacters {0} {1}', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  66. 'last' => true,
  67. //'provider' => 'table'
  68. ),
  69. 'validateIdentical' => array(
  70. 'rule' => array('validateIdentical', ['compare' => 'formField']),
  71. 'message' => 'valErrPwdNotMatch',
  72. 'last' => true,
  73. 'provider' => 'table'
  74. ),
  75. ),
  76. 'formFieldCurrent' => array(
  77. 'notEmpty' => array(
  78. 'rule' => array('notEmpty'),
  79. 'message' => 'valErrProvideCurrentPwd',
  80. 'last' => true,
  81. ),
  82. 'validateCurrentPwd' => array(
  83. 'rule' => 'validateCurrentPwd',
  84. 'message' => 'valErrCurrentPwdIncorrect',
  85. 'last' => true,
  86. 'provider' => 'table'
  87. )
  88. ),
  89. );
  90. /**
  91. * Password hasher instance.
  92. *
  93. * @var AbstractPasswordHasher
  94. */
  95. protected $_passwordHasher;
  96. /**
  97. * Adding validation rules
  98. * also adds and merges config settings (direct + configure)
  99. *
  100. * @return void
  101. */
  102. public function __construct(Table $table, array $config = []) {
  103. $defaults = $this->_defaultConfig;
  104. if ($configureDefaults = Configure::read('Passwordable')) {
  105. $defaults = $configureDefaults + $defaults;
  106. }
  107. $config += $defaults;
  108. parent::__construct($table, $config);
  109. }
  110. /**
  111. * Constructor hook method.
  112. *
  113. * Implement this method to avoid having to overwrite
  114. * the constructor and call parent.
  115. *
  116. * @param array $config The configuration array this behavior is using.
  117. * @return void
  118. */
  119. public function initialize(array $config) {
  120. $formField = $this->_config['formField'];
  121. $formFieldRepeat = $this->_config['formFieldRepeat'];
  122. $formFieldCurrent = $this->_config['formFieldCurrent'];
  123. if ($formField === $this->_config['field']) {
  124. throw new \Exception('Invalid setup - the form field must to be different from the model field (' . $this->_config['field'] . ').');
  125. }
  126. $rules = $this->_validationRules;
  127. foreach ($rules as $field => $fieldRules) {
  128. foreach ($fieldRules as $key => $rule) {
  129. //$rule['allowEmpty'] = !$this->_config['require'];
  130. if ($key === 'between') {
  131. $rule['rule'][1] = $this->_config['minLength'];
  132. $rule['message'][1] = $this->_config['minLength'];
  133. $rule['rule'][2] = $this->_config['maxLength'];
  134. $rule['message'][2] = $this->_config['maxLength'];
  135. }
  136. if (is_array($rule['message'])) {
  137. $message = array_shift($rule['message']);
  138. $rule['message'] = __d('tools', $message, $rule['message']);
  139. } else {
  140. $rule['message'] = __d('tools', $rule['message']);
  141. }
  142. $fieldRules[$key] = $rule;
  143. }
  144. $rules[$field] = $fieldRules;
  145. }
  146. $validator = $this->_table->validator($this->_config['validator']);
  147. // Add the validation rules if not already attached
  148. if (!count($validator->field($formField))) {
  149. $validator->add($formField, $rules['formField']);
  150. $validator->allowEmpty($formField, !$this->_config['require']);
  151. }
  152. if (!count($validator->field($formFieldRepeat))) {
  153. $ruleSet = $rules['formFieldRepeat'];
  154. $ruleSet['validateIdentical']['rule'][1] = $formField;
  155. $validator->add($formFieldRepeat, $ruleSet);
  156. $validator->allowEmpty($formFieldRepeat, !$this->_config['require']);
  157. }
  158. if ($this->_config['current'] && !count($validator->field($formFieldCurrent))) {
  159. $validator->add($formFieldCurrent, $rules['formFieldCurrent']);
  160. $validator->allowEmpty($formFieldCurrent, !$this->_config['require']);
  161. if (!$this->_config['allowSame']) {
  162. $validator->add($formField, 'validateNotSame', array(
  163. 'rule' => array('validateNotSame', ['compare' => $formFieldCurrent]),
  164. 'message' => __d('tools', 'valErrPwdSameAsBefore'),
  165. 'last' => true,
  166. 'provider' => 'table'
  167. ));
  168. }
  169. } elseif (!count($validator->field($formFieldCurrent))) {
  170. // Try to match the password against the hash in the DB
  171. if (!$this->_config['allowSame']) {
  172. $validator->add($formField, 'validateNotSame', array(
  173. 'rule' => array('validateNotSameHash'),
  174. 'message' => __d('tools', 'valErrPwdSameAsBefore'),
  175. //'allowEmpty' => !$this->_config['require'],
  176. 'last' => true,
  177. 'provider' => 'table'
  178. ));
  179. $validator->allowEmpty($formField, !$this->_config['require']);
  180. }
  181. }
  182. }
  183. /**
  184. * Preparing the data
  185. *
  186. * @return void
  187. */
  188. public function beforeValidate(Event $event, Entity $entity) {
  189. $formField = $this->_config['formField'];
  190. $formFieldRepeat = $this->_config['formFieldRepeat'];
  191. $formFieldCurrent = $this->_config['formFieldCurrent'];
  192. // Make sure fields are set and validation rules are triggered - prevents tempering of form data
  193. if ($entity->get($formField) === null) {
  194. $entity->set($formField, '');
  195. }
  196. if ($this->_config['confirm'] && $entity->get($formFieldRepeat) === null) {
  197. $entity->set($formFieldRepeat, '');
  198. }
  199. if ($this->_config['current'] && $entity->get($formFieldCurrent) === null) {
  200. $entity->set($formFieldCurrent, '');
  201. }
  202. // Check if we need to trigger any validation rules
  203. if (!$this->_config['require']) {
  204. $current = $entity->get($formFieldCurrent);
  205. $new = $entity->get($formField) || $entity->get($formFieldRepeat);
  206. if (!$new && !$current) {
  207. //$validator->remove($formField); // tmp only!
  208. //unset($Model->validate[$formField]);
  209. $entity->unsetProperty($formField);
  210. if ($this->_config['confirm']) {
  211. //$validator->remove($formFieldRepeat); // tmp only!
  212. //unset($Model->validate[$formFieldRepeat]);
  213. $entity->unsetProperty($formFieldRepeat);
  214. }
  215. if ($this->_config['current']) {
  216. //$validator->remove($formFieldCurrent); // tmp only!
  217. //unset($Model->validate[$formFieldCurrent]);
  218. $entity->unsetProperty($formFieldCurrent);
  219. }
  220. return true;
  221. }
  222. // Make sure we trigger validation if allowEmpty is set but we have the password field set
  223. if ($new) {
  224. if ($this->_config['confirm'] && !$entity->get($formFieldRepeat)) {
  225. $entity->errors($formFieldRepeat, __d('tools', 'valErrPwdNotMatch'));
  226. }
  227. }
  228. }
  229. // Update whitelist
  230. $this->_modifyWhitelist($entity);
  231. return true;
  232. }
  233. /**
  234. * Hashing the password and whitelisting
  235. *
  236. * @param Event $event
  237. * @return void
  238. */
  239. public function beforeSave(Event $event, Entity $entity) {
  240. $formField = $this->_config['formField'];
  241. $field = $this->_config['field'];
  242. if ($entity->get($formField) !== null) {
  243. $cost = !empty($this->_config['hashCost']) ? $this->_config['hashCost'] : 10;
  244. $options = array('cost' => $cost);
  245. $PasswordHasher = $this->_getPasswordHasher($this->_config['passwordHasher']);
  246. $entity->set($field, $PasswordHasher->hash($entity->get($formField), $options));
  247. if (!$entity->get($field)) {
  248. throw new \Exception('Empty field');
  249. }
  250. $entity->unsetProperty($formField);
  251. //$entity->set($formField, null);
  252. if ($this->_config['confirm']) {
  253. $formFieldRepeat = $this->_config['formFieldRepeat'];
  254. $entity->unsetProperty($formFieldRepeat);
  255. //unset($Model->data[$table->alias()][$formFieldRepeat]);
  256. }
  257. if ($this->_config['current']) {
  258. $formFieldCurrent = $this->_config['formFieldCurrent'];
  259. $entity->unsetProperty($formFieldCurrent);
  260. //unset($Model->data[$table->alias()][$formFieldCurrent]);
  261. }
  262. }
  263. // Update whitelist
  264. $this->_modifyWhitelist($entity, true);
  265. return true;
  266. }
  267. /**
  268. * Checks if the PasswordHasher class supports this and if so, whether the
  269. * password needs to be rehashed or not.
  270. * This is mainly supported by Tools.Modern (using Bcrypt) yet.
  271. *
  272. * @param string $hash Currently hashed password.
  273. * @return bool Success
  274. */
  275. public function needsPasswordRehash($hash) {
  276. $PasswordHasher = $this->_getPasswordHasher($this->_config['passwordHasher']);
  277. if (!method_exists($PasswordHasher, 'needsRehash')) {
  278. return false;
  279. }
  280. return $PasswordHasher->needsRehash($hash);
  281. }
  282. /**
  283. * If not implemented in Table class
  284. *
  285. * Note: requires the used Auth component to be App::uses() loaded.
  286. * It also reqires the same Auth setup as in your AppController's beforeFilter().
  287. * So if you set up any special passwordHasher or auth type, you need to provide those
  288. * with the settings passed to the behavior:
  289. *
  290. * 'passwordHasher' => array(
  291. * 'className' => 'Simple',
  292. * 'hashType' => 'sha256'
  293. * )
  294. *
  295. * @throws CakeException
  296. * @param Model $Model
  297. * @param array $data
  298. * @return bool Success
  299. */
  300. public function validateCurrentPwd($pwd, $context) {
  301. $uid = null;
  302. if (!empty($context['data'][$this->_table->primaryKey()])) {
  303. $uid = $context['data'][$this->_table->primaryKey()];
  304. } else {
  305. trigger_error('No user id given');
  306. return false;
  307. }
  308. return $this->_validateSameHash($pwd, $context);
  309. }
  310. /**
  311. * If not implemented in Table class
  312. *
  313. * @param Model $Model
  314. * @param array $data
  315. * @param string $compareWith String to compare field value with
  316. * @return bool Success
  317. */
  318. public function validateIdentical($value, $options, $context) {
  319. if (!is_array($options)) {
  320. $options = array('compare' => $options);
  321. }
  322. $compareValue = $context['providers']['entity']->get($options['compare']);
  323. return ($compareValue === $value);
  324. }
  325. /**
  326. * If not implemented in Table class
  327. *
  328. * @return bool Success
  329. */
  330. public function validateNotSame($data, $options, $context) {
  331. if (!is_array($options)) {
  332. $options = array('compare' => $options);
  333. }
  334. $value1 = $context['providers']['entity']->get($context['field']);
  335. $value2 = $context['providers']['entity']->get($options['compare']);
  336. return ($value1 !== $value2);
  337. }
  338. /**
  339. * If not implemented in Table class
  340. *
  341. * @return bool Success
  342. */
  343. public function validateNotSameHash($data, $context) {
  344. $field = $this->_config['field'];
  345. if (!$context['providers']['entity']->get($this->_table->primaryKey())) {
  346. return true;
  347. }
  348. $primaryKey = $context['providers']['entity']->get($this->_table->primaryKey());
  349. $value = $context['providers']['entity']->get($context['field']);
  350. $dbValue = $this->_table->find()->where(array($this->_table->primaryKey() => $primaryKey))->first();
  351. if (!$dbValue) {
  352. return true;
  353. }
  354. $dbValue = $dbValue[$field];
  355. if (!$dbValue) {
  356. return true;
  357. }
  358. $PasswordHasher = $this->_getPasswordHasher($this->_config['passwordHasher']);
  359. return !$PasswordHasher->check($value, $dbValue);
  360. }
  361. /**
  362. * PasswordableBehavior::_validateSameHash()
  363. *
  364. * @param Model $Model
  365. * @param string $pwd
  366. * @return bool Success
  367. */
  368. protected function _validateSameHash($pwd, $context) {
  369. $field = $this->_config['field'];
  370. $primaryKey = $context['providers']['entity']->get($this->_table->primaryKey());
  371. $dbValue = $this->_table->find()->where(array($this->_table->primaryKey() => $primaryKey))->first();
  372. if (!$dbValue) {
  373. return false;
  374. }
  375. $dbValue = $dbValue[$field];
  376. if (!$dbValue && $pwd) {
  377. return false;
  378. }
  379. $PasswordHasher = $this->_getPasswordHasher($this->_config['passwordHasher']);
  380. return $PasswordHasher->check($pwd, $dbValue);
  381. }
  382. /**
  383. * PasswordableBehavior::_getPasswordHasher()
  384. *
  385. * @param mixed $hasher Name or options array.
  386. * @return PasswordHasher
  387. */
  388. protected function _getPasswordHasher($hasher) {
  389. if ($this->_passwordHasher) {
  390. return $this->_passwordHasher;
  391. }
  392. return $this->_passwordHasher = PasswordHasherFactory::build($hasher);
  393. }
  394. /**
  395. * Modify the model's whitelist.
  396. *
  397. * Since 2.5 behaviors can also modify the whitelist for validate, thus this behavior can now
  398. * (>= CakePHP 2.5) add the form fields automatically, as well (not just the password field itself).
  399. *
  400. * @param Model $Model
  401. * @return void
  402. * @deprecated 3.0
  403. */
  404. protected function _modifyWhitelist(Entity $entity, $onSave = false) {
  405. $fields = array();
  406. if ($onSave) {
  407. $fields[] = $this->_config['field'];
  408. } else {
  409. $fields[] = $this->_config['formField'];
  410. if ($this->_config['confirm']) {
  411. $fields[] = $this->_config['formFieldRepeat'];
  412. }
  413. if ($this->_config['current']) {
  414. $fields[] = $this->_config['formFieldCurrent'];
  415. }
  416. }
  417. foreach ($fields as $field) {
  418. if (!empty($Model->whitelist) && !in_array($field, $Model->whitelist)) {
  419. $Model->whitelist = array_merge($Model->whitelist, array($field));
  420. }
  421. }
  422. }
  423. }