PasswordableBehavior.php 15 KB

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