PasswordableBehavior.php 14 KB

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