PasswordableBehavior.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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. * @access protected
  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. 'allowEmpty' => false, # if password must be provided or be changed (set to true for update sites)
  49. 'current' => false, # expect the current password for security purposes
  50. 'formField' => 'pwd',
  51. 'formFieldRepeat' => 'pwd_repeat',
  52. 'formFieldCurrent' => 'pwd_current',
  53. 'userModel' => null,
  54. 'hashType' => null, # only for authType Form [cake2.3]
  55. 'hashSalt' => true, # only for authType Form [cake2.3]
  56. 'auth' => null, # which component (defaults to AuthComponent),
  57. 'authType' => 'Form', # which type of authenticate (Form, Blowfish, ...) [cake2.4]
  58. 'passwordHasher' => null, # if a custom pwd hasher is been used [cake2.4]
  59. 'allowSame' => true, # dont allow the old password on change,
  60. 'minLength' => PWD_MIN_LENGTH,
  61. 'maxLength' => PWD_MAX_LENGTH
  62. );
  63. /**
  64. * @access protected
  65. */
  66. protected $_validationRules = array(
  67. 'formField' => array(
  68. 'between' => array(
  69. 'rule' => array('between', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  70. 'message' => array('valErrBetweenCharacters %s %s', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  71. 'allowEmpty' => null,
  72. 'last' => true,
  73. )
  74. ),
  75. 'formFieldRepeat' => array(
  76. 'between' => array(
  77. 'rule' => array('between', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  78. 'message' => array('valErrBetweenCharacters %s %s', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  79. 'allowEmpty' => null,
  80. 'last' => true,
  81. ),
  82. 'validateIdentical' => array(
  83. 'rule' => array('validateIdentical', 'formField'),
  84. 'message' => 'valErrPwdNotMatch',
  85. 'allowEmpty' => null,
  86. 'last' => true,
  87. ),
  88. ),
  89. 'formFieldCurrent' => array(
  90. 'notEmpty' => array(
  91. 'rule' => array('notEmpty'),
  92. 'message' => 'valErrProvideCurrentPwd',
  93. 'allowEmpty' => null,
  94. 'last' => true,
  95. ),
  96. 'validateCurrentPwd' => array(
  97. 'rule' => 'validateCurrentPwd',
  98. 'message' => 'valErrCurrentPwdIncorrect',
  99. 'allowEmpty' => null,
  100. 'last' => true,
  101. )
  102. ),
  103. );
  104. /**
  105. * If not implemented in AppModel
  106. *
  107. * Note: requires the used Auth component to be App::uses() loaded.
  108. * It also reqires the same Auth setup as in your AppController's beforeFilter().
  109. * So if you set up any special passwordHasher or auth type, you need to provide those
  110. * with the settings passed to the behavior:
  111. *
  112. * 'authType' => 'Blowfish', 'passwordHasher' => array(
  113. * 'className' => 'Simple',
  114. * 'hashType' => 'sha256'
  115. * )
  116. *
  117. * @throws CakeException
  118. * @return bool $success
  119. * 2011-07-22 ms
  120. */
  121. public function validateCurrentPwd(Model $Model, $data) {
  122. if (is_array($data)) {
  123. $pwd = array_shift($data);
  124. } else {
  125. $pwd = $data;
  126. }
  127. $uid = null;
  128. if ($Model->id) {
  129. $uid = $Model->id;
  130. } elseif (!empty($Model->data[$Model->alias]['id'])) {
  131. $uid = $Model->data[$Model->alias]['id'];
  132. } else {
  133. trigger_error('No user id given');
  134. return false;
  135. }
  136. $auth = 'Auth';
  137. if (empty($this->settings[$Model->alias]['auth']) && class_exists('AuthExtComponent')) {
  138. $auth = 'AuthExt';
  139. } elseif ($this->settings[$Model->alias]['auth']) {
  140. $auth = $this->settings[$Model->alias]['auth'];
  141. }
  142. $authClass = $auth . 'Component';
  143. if (!class_exists($authClass)) {
  144. throw new CakeException('No Authentication class found (' . $authClass. ')');
  145. }
  146. $this->Auth = new $authClass(new ComponentCollection());
  147. # easiest authenticate method via form and (id + pwd)
  148. $authConfig = array(
  149. 'fields' => array('username' => 'id', 'password' => $this->settings[$Model->alias]['field']),
  150. 'userModel' => $this->settings[$Model->alias]['userModel'] ? $this->settings[$Model->alias]['userModel'] : $Model->alias
  151. );
  152. if (!empty($this->settings[$Model->alias]['passwordHasher'])) {
  153. $authConfig['passwordHasher'] = $this->settings[$Model->alias]['passwordHasher'];
  154. }
  155. $this->Auth->authenticate = array(
  156. $this->settings[$Model->alias]['authType'] => $authConfig
  157. );
  158. $request = Router::getRequest();
  159. $request->data[$Model->alias] = array('id' => $uid, 'password' => $pwd);
  160. $response = new CakeResponse();
  161. return (bool)$this->Auth->identify($request, $response);
  162. }
  163. /**
  164. * if not implemented in AppModel
  165. * @return bool $success
  166. * 2011-07-22 ms
  167. */
  168. public function validateIdentical(Model $Model, $data, $compareWith = null) {
  169. if (is_array($data)) {
  170. $value = array_shift($data);
  171. } else {
  172. $value = $data;
  173. }
  174. $compareValue = $Model->data[$Model->alias][$compareWith];
  175. return ($compareValue === $value);
  176. }
  177. /**
  178. * if not implemented in AppModel
  179. * @return bool $success
  180. * 2011-11-10 ms
  181. */
  182. public function validateNotSame(Model $Model, $data, $field1, $field2) {
  183. $value1 = $Model->data[$Model->alias][$field1];
  184. $value2 = $Model->data[$Model->alias][$field2];
  185. return ($value1 !== $value2);
  186. }
  187. /**
  188. * if not implemented in AppModel
  189. * @return bool $success
  190. * 2011-11-10 ms
  191. */
  192. public function validateNotSameHash(Model $Model, $data, $formField) {
  193. $field = $this->settings[$Model->alias]['field'];
  194. $type = $this->settings[$Model->alias]['hashType'];
  195. $salt = $this->settings[$Model->alias]['hashSalt'];
  196. if ($this->settings[$Model->alias]['authType'] === 'Blowfish') {
  197. $type = 'blowfish';
  198. $salt = false;
  199. }
  200. if (!isset($Model->data[$Model->alias][$Model->primaryKey])) {
  201. return true;
  202. }
  203. $primaryKey = $Model->data[$Model->alias][$Model->primaryKey];
  204. $value = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  205. $dbValue = $Model->field($field, array($Model->primaryKey => $primaryKey));
  206. if (!$dbValue) {
  207. return true;
  208. }
  209. return ($value !== $dbValue);
  210. }
  211. /**
  212. * Adding validation rules
  213. * also adds and merges config settings (direct + configure)
  214. *
  215. * @return void
  216. * 2011-08-24 ms
  217. */
  218. public function setup(Model $Model, $config = array()) {
  219. $defaults = $this->_defaults;
  220. if ($configureDefaults = Configure::read('Passwordable')) {
  221. $defaults = Set::merge($defaults, $configureDefaults);
  222. }
  223. $this->settings[$Model->alias] = Set::merge($defaults, $config);
  224. $formField = $this->settings[$Model->alias]['formField'];
  225. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  226. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  227. $rules = $this->_validationRules;
  228. # add the validation rules if not already attached
  229. if (!isset($Model->validate[$formField])) {
  230. $Model->validator()->add($formField, $rules['formField']);
  231. }
  232. if (!isset($Model->validate[$formFieldRepeat])) {
  233. $ruleSet = $rules['formFieldRepeat'];
  234. $ruleSet['validateIdentical']['rule'][1] = $formField;
  235. $Model->validator()->add($formFieldRepeat, $ruleSet);
  236. }
  237. if ($this->settings[$Model->alias]['current'] && !isset($Model->validate[$formFieldCurrent])) {
  238. $Model->validator()->add($formFieldCurrent, $rules['formFieldCurrent']);
  239. if (!$this->settings[$Model->alias]['allowSame']) {
  240. $Model->validator()->add($formField, 'validateNotSame', array(
  241. 'rule' => array('validateNotSame', $formField, $formFieldCurrent),
  242. 'message' => 'valErrPwdSameAsBefore',
  243. 'allowEmpty' => $this->settings[$Model->alias]['allowEmpty'],
  244. 'last' => true,
  245. ));
  246. }
  247. } elseif (!isset($Model->validate[$formFieldCurrent])) {
  248. # try to match the password against the hash in the DB
  249. if (!$this->settings[$Model->alias]['allowSame']) {
  250. $Model->validator()->add($formField, 'validateNotSame', array(
  251. 'rule' => array('validateNotSameHash', $formField),
  252. 'message' => 'valErrPwdSameAsBefore',
  253. 'allowEmpty' => $this->settings[$Model->alias]['allowEmpty'],
  254. 'last' => true,
  255. ));
  256. }
  257. }
  258. }
  259. /**
  260. * Preparing the data
  261. *
  262. * @return bool $success
  263. * 2011-07-22 ms
  264. */
  265. public function beforeValidate(Model $Model) {
  266. $formField = $this->settings[$Model->alias]['formField'];
  267. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  268. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  269. # make sure fields are set and validation rules are triggered - prevents tempering of form data
  270. if (!isset($Model->data[$Model->alias][$formField])) {
  271. $Model->data[$Model->alias][$formField] = '';
  272. }
  273. if ($this->settings[$Model->alias]['confirm'] && !isset($Model->data[$Model->alias][$formFieldRepeat])) {
  274. $Model->data[$Model->alias][$formFieldRepeat] = '';
  275. }
  276. if ($this->settings[$Model->alias]['current'] && !isset($Model->data[$Model->alias][$formFieldCurrent])) {
  277. $Model->data[$Model->alias][$formFieldCurrent] = '';
  278. }
  279. # check if we need to trigger any validation rules
  280. if ($this->settings[$Model->alias]['allowEmpty']) {
  281. $current = !empty($Model->data[$Model->alias][$formFieldCurrent]);
  282. $new = !empty($Model->data[$Model->alias][$formField]) || !empty($Model->data[$Model->alias][$formFieldRepeat]);
  283. if (!$new && !$current) {
  284. //$Model->validator()->remove($formField); // tmp only!
  285. //unset($Model->validate[$formField]);
  286. unset($Model->data[$Model->alias][$formField]);
  287. if ($this->settings[$Model->alias]['confirm']) {
  288. //$Model->validator()->remove($formFieldRepeat); // tmp only!
  289. //unset($Model->validate[$formFieldRepeat]);
  290. unset($Model->data[$Model->alias][$formFieldRepeat]);
  291. }
  292. if ($this->settings[$Model->alias]['current']) {
  293. //$Model->validator()->remove($formFieldCurrent); // tmp only!
  294. //unset($Model->validate[$formFieldCurrent]);
  295. unset($Model->data[$Model->alias][$formFieldCurrent]);
  296. }
  297. return true;
  298. }
  299. }
  300. # add fields to whitelist!
  301. $whitelist = array($this->settings[$Model->alias]['formField'], $this->settings[$Model->alias]['formFieldRepeat']);
  302. if ($this->settings[$Model->alias]['current']) {
  303. $whitelist[] = $this->settings[$Model->alias]['formFieldCurrent'];
  304. }
  305. if (!empty($Model->whitelist)) {
  306. $Model->whitelist = array_merge($Model->whitelist, $whitelist);
  307. }
  308. return true;
  309. }
  310. /**
  311. * Hashing the password and whitelisting
  312. *
  313. * @return bool $success
  314. * 2011-07-22 ms
  315. */
  316. public function beforeSave(Model $Model) {
  317. $formField = $this->settings[$Model->alias]['formField'];
  318. $field = $this->settings[$Model->alias]['field'];
  319. $type = $this->settings[$Model->alias]['hashType'];
  320. $salt = $this->settings[$Model->alias]['hashSalt'];
  321. if ($this->settings[$Model->alias]['authType'] === 'Blowfish') {
  322. $type = 'blowfish';
  323. $salt = false;
  324. }
  325. if (isset($Model->data[$Model->alias][$formField])) {
  326. $Model->data[$Model->alias][$field] = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  327. unset($Model->data[$Model->alias][$formField]);
  328. if ($this->settings[$Model->alias]['confirm']) {
  329. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  330. unset($Model->data[$Model->alias][$formFieldRepeat]);
  331. }
  332. if ($this->settings[$Model->alias]['current']) {
  333. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  334. unset($Model->data[$Model->alias][$formFieldCurrent]);
  335. }
  336. # update whitelist
  337. if (!empty($Model->whitelist)) {
  338. $Model->whitelist = array_merge($Model->whitelist, array($field));
  339. }
  340. }
  341. return true;
  342. }
  343. }