PasswordableBehavior.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. <?php
  2. App::uses('ModelBehavior', 'Model');
  3. App::uses('Router', 'Routing');
  4. App::uses('CakeRequest', 'Network');
  5. App::uses('CakeResponse', 'Network');
  6. App::uses('Security', 'Utility');
  7. // @deprecated Use Configure settings instead.
  8. if (!defined('PWD_MIN_LENGTH')) {
  9. define('PWD_MIN_LENGTH', 6);
  10. }
  11. if (!defined('PWD_MAX_LENGTH')) {
  12. define('PWD_MAX_LENGTH', 20);
  13. }
  14. /**
  15. * A CakePHP2 behavior to work with passwords the easy way
  16. * - complete validation
  17. * - hashing of password
  18. * - requires fields (no tempering even without security component)
  19. * - usable for edit forms (require=>false for optional password update)
  20. *
  21. * Usage: Do NOT add it via $actAs = array()
  22. * attach it dynamically in only those actions where you actually change the password like so:
  23. * $this->User->Behaviors->load('Tools.Passwordable', array(SETTINGSARRAY));
  24. * as first line in any action where you want to allow the user to change his password
  25. * also add the two form fields in the form (pwd, pwd_confirm)
  26. * the rest is cake automagic :)
  27. *
  28. * Also note that you can apply global settings via Configure key 'Passwordable', as well,
  29. * if you don't want to manually pass them along each time you use the behavior. This also
  30. * keeps the code clean and lean.
  31. *
  32. * Now also is capable of:
  33. * - require current password prior to altering it (current=>true)
  34. * - don't allow the same password it was before (allowSame=>false)
  35. * - supporting different auth types and password hashing algorythms
  36. *
  37. * @version 1.7 (Now CakePHP2.4/2.5 ready - with passwordHasher support)
  38. * @author Mark Scherer
  39. * @link http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp
  40. * @license MIT
  41. * 2012-08-18 ms
  42. */
  43. class PasswordableBehavior extends ModelBehavior {
  44. /**
  45. * @var array
  46. */
  47. protected $_defaults = array(
  48. 'field' => 'password',
  49. 'confirm' => true, // Set to false if in admin view and no confirmation (pwd_repeat) is required
  50. 'require' => true, // If a password change is required (set to false for edit forms, leave it true for pure password update forms)
  51. 'allowEmpty' => false, // Deprecated, do NOT use anymore! Use require instead!
  52. 'current' => false, // Enquire the current password for security purposes
  53. 'formField' => 'pwd',
  54. 'formFieldRepeat' => 'pwd_repeat',
  55. 'formFieldCurrent' => 'pwd_current',
  56. 'userModel' => null, // Defaults to User
  57. 'hashType' => null, // Only for authType Form [cake2.3]
  58. 'hashSalt' => true, // Only for authType Form [cake2.3]
  59. 'auth' => null, // Which component (defaults to AuthComponent),
  60. 'authType' => 'Form', // Which type of authenticate (Form, Blowfish, ...) [cake2.4]
  61. 'passwordHasher' => null, // If a custom pwd hasher is been used [cake2.4]
  62. 'allowSame' => true, // Don't allow the old password on change
  63. 'minLength' => PWD_MIN_LENGTH,
  64. 'maxLength' => PWD_MAX_LENGTH
  65. );
  66. /**
  67. * @var array
  68. */
  69. protected $_validationRules = array(
  70. 'formField' => array(
  71. 'between' => array(
  72. 'rule' => array('between', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  73. 'message' => array('valErrBetweenCharacters %s %s', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  74. 'allowEmpty' => null,
  75. 'last' => true,
  76. )
  77. ),
  78. 'formFieldRepeat' => array(
  79. 'between' => array(
  80. 'rule' => array('between', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  81. 'message' => array('valErrBetweenCharacters %s %s', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  82. 'allowEmpty' => null,
  83. 'last' => true,
  84. ),
  85. 'validateIdentical' => array(
  86. 'rule' => array('validateIdentical', 'formField'),
  87. 'message' => 'valErrPwdNotMatch',
  88. 'allowEmpty' => null,
  89. 'last' => true,
  90. ),
  91. ),
  92. 'formFieldCurrent' => array(
  93. 'notEmpty' => array(
  94. 'rule' => array('notEmpty'),
  95. 'message' => 'valErrProvideCurrentPwd',
  96. 'allowEmpty' => null,
  97. 'last' => true,
  98. ),
  99. 'validateCurrentPwd' => array(
  100. 'rule' => 'validateCurrentPwd',
  101. 'message' => 'valErrCurrentPwdIncorrect',
  102. 'allowEmpty' => null,
  103. 'last' => true,
  104. )
  105. ),
  106. );
  107. /**
  108. * If not implemented in AppModel
  109. *
  110. * Note: requires the used Auth component to be App::uses() loaded.
  111. * It also reqires the same Auth setup as in your AppController's beforeFilter().
  112. * So if you set up any special passwordHasher or auth type, you need to provide those
  113. * with the settings passed to the behavior:
  114. *
  115. * 'authType' => 'Blowfish', 'passwordHasher' => array(
  116. * 'className' => 'Simple',
  117. * 'hashType' => 'sha256'
  118. * )
  119. *
  120. * @throws CakeException
  121. * @param Model $Model
  122. * @param array $data
  123. * @return boolean Success
  124. * 2011-07-22 ms
  125. */
  126. public function validateCurrentPwd(Model $Model, $data) {
  127. if (is_array($data)) {
  128. $pwd = array_shift($data);
  129. } else {
  130. $pwd = $data;
  131. }
  132. $uid = null;
  133. if ($Model->id) {
  134. $uid = $Model->id;
  135. } elseif (!empty($Model->data[$Model->alias]['id'])) {
  136. $uid = $Model->data[$Model->alias]['id'];
  137. } else {
  138. trigger_error('No user id given');
  139. return false;
  140. }
  141. $auth = 'Auth';
  142. if (empty($this->settings[$Model->alias]['auth']) && class_exists('AuthExtComponent')) {
  143. $auth = 'AuthExt';
  144. } elseif ($this->settings[$Model->alias]['auth']) {
  145. $auth = $this->settings[$Model->alias]['auth'];
  146. }
  147. $authClass = $auth . 'Component';
  148. if (!class_exists($authClass)) {
  149. throw new CakeException('No Authentication class found (' . $authClass. ')');
  150. }
  151. $this->Auth = new $authClass(new ComponentCollection());
  152. # easiest authenticate method via form and (id + pwd)
  153. $authConfig = array(
  154. 'fields' => array('username' => 'id', 'password' => $this->settings[$Model->alias]['field']),
  155. 'userModel' => $this->settings[$Model->alias]['userModel'] ? $this->settings[$Model->alias]['userModel'] : $Model->alias
  156. );
  157. if (!empty($this->settings[$Model->alias]['passwordHasher'])) {
  158. $authConfig['passwordHasher'] = $this->settings[$Model->alias]['passwordHasher'];
  159. }
  160. $this->Auth->authenticate = array(
  161. $this->settings[$Model->alias]['authType'] => $authConfig
  162. );
  163. $request = Router::getRequest();
  164. $request->data[$Model->alias] = array('id' => $uid, 'password' => $pwd);
  165. $response = new CakeResponse();
  166. return (bool)$this->Auth->identify($request, $response);
  167. }
  168. /**
  169. * if not implemented in AppModel
  170. *
  171. * @param Model $Model
  172. * @param array $data
  173. * @param string $compareWith String to compare field value with
  174. * @return boolean Success
  175. * 2011-07-22 ms
  176. */
  177. public function validateIdentical(Model $Model, $data, $compareWith = null) {
  178. if (is_array($data)) {
  179. $value = array_shift($data);
  180. } else {
  181. $value = $data;
  182. }
  183. $compareValue = $Model->data[$Model->alias][$compareWith];
  184. return ($compareValue === $value);
  185. }
  186. /**
  187. * if not implemented in AppModel
  188. *
  189. * @return boolean Success
  190. * 2011-11-10 ms
  191. */
  192. public function validateNotSame(Model $Model, $data, $field1, $field2) {
  193. $value1 = $Model->data[$Model->alias][$field1];
  194. $value2 = $Model->data[$Model->alias][$field2];
  195. return ($value1 !== $value2);
  196. }
  197. /**
  198. * if not implemented in AppModel
  199. *
  200. * @return boolean Success
  201. * 2011-11-10 ms
  202. */
  203. public function validateNotSameHash(Model $Model, $data, $formField) {
  204. $field = $this->settings[$Model->alias]['field'];
  205. $type = $this->settings[$Model->alias]['hashType'];
  206. $salt = $this->settings[$Model->alias]['hashSalt'];
  207. if ($this->settings[$Model->alias]['authType'] === 'Blowfish') {
  208. $type = 'blowfish';
  209. $salt = false;
  210. }
  211. if (!isset($Model->data[$Model->alias][$Model->primaryKey])) {
  212. return true;
  213. }
  214. $primaryKey = $Model->data[$Model->alias][$Model->primaryKey];
  215. $value = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  216. $dbValue = $Model->field($field, array($Model->primaryKey => $primaryKey));
  217. if (!$dbValue) {
  218. return true;
  219. }
  220. return ($value !== $dbValue);
  221. }
  222. /**
  223. * Adding validation rules
  224. * also adds and merges config settings (direct + configure)
  225. *
  226. * @return void
  227. * 2011-08-24 ms
  228. */
  229. public function setup(Model $Model, $config = array()) {
  230. $defaults = $this->_defaults;
  231. if ($configureDefaults = Configure::read('Passwordable')) {
  232. $defaults = Set::merge($defaults, $configureDefaults);
  233. }
  234. $this->settings[$Model->alias] = Set::merge($defaults, $config);
  235. // BC comp
  236. if ($this->settings[$Model->alias]['allowEmpty']) {
  237. $this->settings[$Model->alias]['require'] = false;
  238. }
  239. $formField = $this->settings[$Model->alias]['formField'];
  240. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  241. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  242. $rules = $this->_validationRules;
  243. foreach ($rules as $field => $fieldRules) {
  244. foreach ($fieldRules as $key => $rule) {
  245. $rule['allowEmpty'] = !$this->settings[$Model->alias]['require'];
  246. if ($key === 'between') {
  247. $rule['rule'][1] = $this->settings[$Model->alias]['minLength'];
  248. $rule['message'][1] = $this->settings[$Model->alias]['minLength'];
  249. $rule['rule'][2] = $this->settings[$Model->alias]['maxLength'];
  250. $rule['message'][2] = $this->settings[$Model->alias]['maxLength'];
  251. }
  252. $fieldRules[$key] = $rule;
  253. }
  254. $rules[$field] = $fieldRules;
  255. }
  256. # add the validation rules if not already attached
  257. if (!isset($Model->validate[$formField])) {
  258. $Model->validator()->add($formField, $rules['formField']);
  259. }
  260. if (!isset($Model->validate[$formFieldRepeat])) {
  261. $ruleSet = $rules['formFieldRepeat'];
  262. $ruleSet['validateIdentical']['rule'][1] = $formField;
  263. $Model->validator()->add($formFieldRepeat, $ruleSet);
  264. }
  265. if ($this->settings[$Model->alias]['current'] && !isset($Model->validate[$formFieldCurrent])) {
  266. $Model->validator()->add($formFieldCurrent, $rules['formFieldCurrent']);
  267. if (!$this->settings[$Model->alias]['allowSame']) {
  268. $Model->validator()->add($formField, 'validateNotSame', array(
  269. 'rule' => array('validateNotSame', $formField, $formFieldCurrent),
  270. 'message' => 'valErrPwdSameAsBefore',
  271. 'allowEmpty' => !$this->settings[$Model->alias]['require'],
  272. 'last' => true,
  273. ));
  274. }
  275. } elseif (!isset($Model->validate[$formFieldCurrent])) {
  276. # try to match the password against the hash in the DB
  277. if (!$this->settings[$Model->alias]['allowSame']) {
  278. $Model->validator()->add($formField, 'validateNotSame', array(
  279. 'rule' => array('validateNotSameHash', $formField),
  280. 'message' => 'valErrPwdSameAsBefore',
  281. 'allowEmpty' => !$this->settings[$Model->alias]['require'],
  282. 'last' => true,
  283. ));
  284. }
  285. }
  286. }
  287. /**
  288. * Preparing the data
  289. *
  290. * @return boolean Success
  291. * 2011-07-22 ms
  292. */
  293. public function beforeValidate(Model $Model, $options = array()) {
  294. $formField = $this->settings[$Model->alias]['formField'];
  295. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  296. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  297. # make sure fields are set and validation rules are triggered - prevents tempering of form data
  298. if (!isset($Model->data[$Model->alias][$formField])) {
  299. $Model->data[$Model->alias][$formField] = '';
  300. }
  301. if ($this->settings[$Model->alias]['confirm'] && !isset($Model->data[$Model->alias][$formFieldRepeat])) {
  302. $Model->data[$Model->alias][$formFieldRepeat] = '';
  303. }
  304. if ($this->settings[$Model->alias]['current'] && !isset($Model->data[$Model->alias][$formFieldCurrent])) {
  305. $Model->data[$Model->alias][$formFieldCurrent] = '';
  306. }
  307. # check if we need to trigger any validation rules
  308. if (!$this->settings[$Model->alias]['require']) {
  309. $current = !empty($Model->data[$Model->alias][$formFieldCurrent]);
  310. $new = !empty($Model->data[$Model->alias][$formField]) || !empty($Model->data[$Model->alias][$formFieldRepeat]);
  311. if (!$new && !$current) {
  312. //$Model->validator()->remove($formField); // tmp only!
  313. //unset($Model->validate[$formField]);
  314. unset($Model->data[$Model->alias][$formField]);
  315. if ($this->settings[$Model->alias]['confirm']) {
  316. //$Model->validator()->remove($formFieldRepeat); // tmp only!
  317. //unset($Model->validate[$formFieldRepeat]);
  318. unset($Model->data[$Model->alias][$formFieldRepeat]);
  319. }
  320. if ($this->settings[$Model->alias]['current']) {
  321. //$Model->validator()->remove($formFieldCurrent); // tmp only!
  322. //unset($Model->validate[$formFieldCurrent]);
  323. unset($Model->data[$Model->alias][$formFieldCurrent]);
  324. }
  325. return true;
  326. }
  327. }
  328. # add fields to whitelist!
  329. $whitelist = array($this->settings[$Model->alias]['formField'], $this->settings[$Model->alias]['formFieldRepeat']);
  330. if ($this->settings[$Model->alias]['current']) {
  331. $whitelist[] = $this->settings[$Model->alias]['formFieldCurrent'];
  332. }
  333. if (!empty($Model->whitelist)) {
  334. $Model->whitelist = array_merge($Model->whitelist, $whitelist);
  335. }
  336. return true;
  337. }
  338. /**
  339. * Hashing the password and whitelisting
  340. *
  341. * @return boolean Success
  342. * 2011-07-22 ms
  343. */
  344. public function beforeSave(Model $Model, $options = array()) {
  345. $formField = $this->settings[$Model->alias]['formField'];
  346. $field = $this->settings[$Model->alias]['field'];
  347. $type = $this->settings[$Model->alias]['hashType'];
  348. $salt = $this->settings[$Model->alias]['hashSalt'];
  349. if ($this->settings[$Model->alias]['authType'] === 'Blowfish') {
  350. $type = 'blowfish';
  351. $salt = false;
  352. }
  353. if (isset($Model->data[$Model->alias][$formField])) {
  354. $Model->data[$Model->alias][$field] = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  355. unset($Model->data[$Model->alias][$formField]);
  356. if ($this->settings[$Model->alias]['confirm']) {
  357. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  358. unset($Model->data[$Model->alias][$formFieldRepeat]);
  359. }
  360. if ($this->settings[$Model->alias]['current']) {
  361. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  362. unset($Model->data[$Model->alias][$formFieldCurrent]);
  363. }
  364. # update whitelist
  365. if (!empty($Model->whitelist)) {
  366. $Model->whitelist = array_merge($Model->whitelist, array($field));
  367. }
  368. }
  369. return true;
  370. }
  371. }