PasswordableBehavior.php 18 KB

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