PasswordableBehavior.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. if (!defined('PWD_MIN_LENGTH')) {
  8. define('PWD_MIN_LENGTH', 3);
  9. }
  10. if (!defined('PWD_MAX_LENGTH')) {
  11. define('PWD_MAX_LENGTH', 20);
  12. }
  13. /**
  14. * A CakePHP2 behavior to work with passwords the easy way
  15. * - complete validation
  16. * - hashing of password
  17. * - requires fields (no tempering even without security component)
  18. * - usable for edit forms (allowEmpty=>true for optional password update)
  19. *
  20. * usage: do NOT add it via $actAs = array()
  21. * attach it dynamically in only those actions where you actually change the password like so:
  22. * $this->User->Behaviors->load('Tools.Passwordable', array(SETTINGSARRAY));
  23. * as first line in any action where you want to allow the user to change his password
  24. * also add the two form fields in the form (pwd, pwd_confirm)
  25. * the rest is cake automagic :)
  26. *
  27. * now also is capable of:
  28. * - require current password prior to altering it (current=>true)
  29. * - don't allow the same password it was before (allowSame=>false)
  30. * - supporting different auth types and password hashing algorythms
  31. *
  32. * TODO: allowEmpty and nonEmptyToEmpty - maybe with checkbox "set_new_pwd"
  33. * feel free to help me out
  34. *
  35. * @version 1.7 (Now 2.4 ready - with passwordHasher support)
  36. * @author Mark Scherer
  37. * @link http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp
  38. * @license MIT
  39. * 2012-08-18 ms
  40. */
  41. class PasswordableBehavior extends ModelBehavior {
  42. /**
  43. * @var array
  44. */
  45. protected $_defaults = 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, // Expect 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, // dont 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. * If not implemented in AppModel
  107. *
  108. * Note: requires the used Auth component to be App::uses() loaded.
  109. * It also reqires the same Auth setup as in your AppController's beforeFilter().
  110. * So if you set up any special passwordHasher or auth type, you need to provide those
  111. * with the settings passed to the behavior:
  112. *
  113. * 'authType' => 'Blowfish', 'passwordHasher' => array(
  114. * 'className' => 'Simple',
  115. * 'hashType' => 'sha256'
  116. * )
  117. *
  118. * @throws CakeException
  119. * @param Model $Model
  120. * @param array $data
  121. * @return bool Success
  122. * 2011-07-22 ms
  123. */
  124. public function validateCurrentPwd(Model $Model, $data) {
  125. if (is_array($data)) {
  126. $pwd = array_shift($data);
  127. } else {
  128. $pwd = $data;
  129. }
  130. $uid = null;
  131. if ($Model->id) {
  132. $uid = $Model->id;
  133. } elseif (!empty($Model->data[$Model->alias]['id'])) {
  134. $uid = $Model->data[$Model->alias]['id'];
  135. } else {
  136. trigger_error('No user id given');
  137. return false;
  138. }
  139. $auth = 'Auth';
  140. if (empty($this->settings[$Model->alias]['auth']) && class_exists('AuthExtComponent')) {
  141. $auth = 'AuthExt';
  142. } elseif ($this->settings[$Model->alias]['auth']) {
  143. $auth = $this->settings[$Model->alias]['auth'];
  144. }
  145. $authClass = $auth . 'Component';
  146. if (!class_exists($authClass)) {
  147. throw new CakeException('No Authentication class found (' . $authClass. ')');
  148. }
  149. $this->Auth = new $authClass(new ComponentCollection());
  150. # easiest authenticate method via form and (id + pwd)
  151. $authConfig = array(
  152. 'fields' => array('username' => 'id', 'password' => $this->settings[$Model->alias]['field']),
  153. 'userModel' => $this->settings[$Model->alias]['userModel'] ? $this->settings[$Model->alias]['userModel'] : $Model->alias
  154. );
  155. if (!empty($this->settings[$Model->alias]['passwordHasher'])) {
  156. $authConfig['passwordHasher'] = $this->settings[$Model->alias]['passwordHasher'];
  157. }
  158. $this->Auth->authenticate = array(
  159. $this->settings[$Model->alias]['authType'] => $authConfig
  160. );
  161. $request = Router::getRequest();
  162. $request->data[$Model->alias] = array('id' => $uid, 'password' => $pwd);
  163. $response = new CakeResponse();
  164. return (bool)$this->Auth->identify($request, $response);
  165. }
  166. /**
  167. * if not implemented in AppModel
  168. *
  169. * @param Model $Model
  170. * @param array $data
  171. * @param string $compareWith String to compare field value with
  172. * @return bool Success
  173. * 2011-07-22 ms
  174. */
  175. public function validateIdentical(Model $Model, $data, $compareWith = null) {
  176. if (is_array($data)) {
  177. $value = array_shift($data);
  178. } else {
  179. $value = $data;
  180. }
  181. $compareValue = $Model->data[$Model->alias][$compareWith];
  182. return ($compareValue === $value);
  183. }
  184. /**
  185. * if not implemented in AppModel
  186. *
  187. * @return bool Success
  188. * 2011-11-10 ms
  189. */
  190. public function validateNotSame(Model $Model, $data, $field1, $field2) {
  191. $value1 = $Model->data[$Model->alias][$field1];
  192. $value2 = $Model->data[$Model->alias][$field2];
  193. return ($value1 !== $value2);
  194. }
  195. /**
  196. * if not implemented in AppModel
  197. *
  198. * @return bool Success
  199. * 2011-11-10 ms
  200. */
  201. public function validateNotSameHash(Model $Model, $data, $formField) {
  202. $field = $this->settings[$Model->alias]['field'];
  203. $type = $this->settings[$Model->alias]['hashType'];
  204. $salt = $this->settings[$Model->alias]['hashSalt'];
  205. if ($this->settings[$Model->alias]['authType'] === 'Blowfish') {
  206. $type = 'blowfish';
  207. $salt = false;
  208. }
  209. if (!isset($Model->data[$Model->alias][$Model->primaryKey])) {
  210. return true;
  211. }
  212. $primaryKey = $Model->data[$Model->alias][$Model->primaryKey];
  213. $value = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  214. $dbValue = $Model->field($field, array($Model->primaryKey => $primaryKey));
  215. if (!$dbValue) {
  216. return true;
  217. }
  218. return ($value !== $dbValue);
  219. }
  220. /**
  221. * Adding validation rules
  222. * also adds and merges config settings (direct + configure)
  223. *
  224. * @return void
  225. * 2011-08-24 ms
  226. */
  227. public function setup(Model $Model, $config = array()) {
  228. $defaults = $this->_defaults;
  229. if ($configureDefaults = Configure::read('Passwordable')) {
  230. $defaults = Set::merge($defaults, $configureDefaults);
  231. }
  232. $this->settings[$Model->alias] = Set::merge($defaults, $config);
  233. // BC comp
  234. if ($this->settings[$Model->alias]['allowEmpty']) {
  235. $this->settings[$Model->alias]['require'] = false;
  236. }
  237. $formField = $this->settings[$Model->alias]['formField'];
  238. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  239. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  240. $rules = $this->_validationRules;
  241. foreach ($rules as $key => $rule) {
  242. foreach ($rule as $rK => $rR) {
  243. $rR['allowEmpty'] = !$this->settings[$Model->alias]['require'];
  244. $rules[$key][$rK] = $rR;
  245. }
  246. }
  247. # add the validation rules if not already attached
  248. if (!isset($Model->validate[$formField])) {
  249. $Model->validator()->add($formField, $rules['formField']);
  250. }
  251. if (!isset($Model->validate[$formFieldRepeat])) {
  252. $ruleSet = $rules['formFieldRepeat'];
  253. $ruleSet['validateIdentical']['rule'][1] = $formField;
  254. $Model->validator()->add($formFieldRepeat, $ruleSet);
  255. }
  256. if ($this->settings[$Model->alias]['current'] && !isset($Model->validate[$formFieldCurrent])) {
  257. $Model->validator()->add($formFieldCurrent, $rules['formFieldCurrent']);
  258. if (!$this->settings[$Model->alias]['allowSame']) {
  259. $Model->validator()->add($formField, 'validateNotSame', array(
  260. 'rule' => array('validateNotSame', $formField, $formFieldCurrent),
  261. 'message' => 'valErrPwdSameAsBefore',
  262. 'allowEmpty' => !$this->settings[$Model->alias]['require'],
  263. 'last' => true,
  264. ));
  265. }
  266. } elseif (!isset($Model->validate[$formFieldCurrent])) {
  267. # try to match the password against the hash in the DB
  268. if (!$this->settings[$Model->alias]['allowSame']) {
  269. $Model->validator()->add($formField, 'validateNotSame', array(
  270. 'rule' => array('validateNotSameHash', $formField),
  271. 'message' => 'valErrPwdSameAsBefore',
  272. 'allowEmpty' => !$this->settings[$Model->alias]['require'],
  273. 'last' => true,
  274. ));
  275. }
  276. }
  277. }
  278. /**
  279. * Preparing the data
  280. *
  281. * @return bool Success
  282. * 2011-07-22 ms
  283. */
  284. public function beforeValidate(Model $Model, $options = array()) {
  285. $formField = $this->settings[$Model->alias]['formField'];
  286. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  287. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  288. # make sure fields are set and validation rules are triggered - prevents tempering of form data
  289. if (!isset($Model->data[$Model->alias][$formField])) {
  290. $Model->data[$Model->alias][$formField] = '';
  291. }
  292. if ($this->settings[$Model->alias]['confirm'] && !isset($Model->data[$Model->alias][$formFieldRepeat])) {
  293. $Model->data[$Model->alias][$formFieldRepeat] = '';
  294. }
  295. if ($this->settings[$Model->alias]['current'] && !isset($Model->data[$Model->alias][$formFieldCurrent])) {
  296. $Model->data[$Model->alias][$formFieldCurrent] = '';
  297. }
  298. # check if we need to trigger any validation rules
  299. if (!$this->settings[$Model->alias]['require']) {
  300. $current = !empty($Model->data[$Model->alias][$formFieldCurrent]);
  301. $new = !empty($Model->data[$Model->alias][$formField]) || !empty($Model->data[$Model->alias][$formFieldRepeat]);
  302. if (!$new && !$current) {
  303. //$Model->validator()->remove($formField); // tmp only!
  304. //unset($Model->validate[$formField]);
  305. unset($Model->data[$Model->alias][$formField]);
  306. if ($this->settings[$Model->alias]['confirm']) {
  307. //$Model->validator()->remove($formFieldRepeat); // tmp only!
  308. //unset($Model->validate[$formFieldRepeat]);
  309. unset($Model->data[$Model->alias][$formFieldRepeat]);
  310. }
  311. if ($this->settings[$Model->alias]['current']) {
  312. //$Model->validator()->remove($formFieldCurrent); // tmp only!
  313. //unset($Model->validate[$formFieldCurrent]);
  314. unset($Model->data[$Model->alias][$formFieldCurrent]);
  315. }
  316. return true;
  317. }
  318. }
  319. # add fields to whitelist!
  320. $whitelist = array($this->settings[$Model->alias]['formField'], $this->settings[$Model->alias]['formFieldRepeat']);
  321. if ($this->settings[$Model->alias]['current']) {
  322. $whitelist[] = $this->settings[$Model->alias]['formFieldCurrent'];
  323. }
  324. if (!empty($Model->whitelist)) {
  325. $Model->whitelist = array_merge($Model->whitelist, $whitelist);
  326. }
  327. return true;
  328. }
  329. /**
  330. * Hashing the password and whitelisting
  331. *
  332. * @return bool Success
  333. * 2011-07-22 ms
  334. */
  335. public function beforeSave(Model $Model, $options = array()) {
  336. $formField = $this->settings[$Model->alias]['formField'];
  337. $field = $this->settings[$Model->alias]['field'];
  338. $type = $this->settings[$Model->alias]['hashType'];
  339. $salt = $this->settings[$Model->alias]['hashSalt'];
  340. if ($this->settings[$Model->alias]['authType'] === 'Blowfish') {
  341. $type = 'blowfish';
  342. $salt = false;
  343. }
  344. if (isset($Model->data[$Model->alias][$formField])) {
  345. $Model->data[$Model->alias][$field] = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  346. unset($Model->data[$Model->alias][$formField]);
  347. if ($this->settings[$Model->alias]['confirm']) {
  348. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  349. unset($Model->data[$Model->alias][$formFieldRepeat]);
  350. }
  351. if ($this->settings[$Model->alias]['current']) {
  352. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  353. unset($Model->data[$Model->alias][$formFieldCurrent]);
  354. }
  355. # update whitelist
  356. if (!empty($Model->whitelist)) {
  357. $Model->whitelist = array_merge($Model->whitelist, array($field));
  358. }
  359. }
  360. return true;
  361. }
  362. }