PasswordableBehavior.php 17 KB

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