PasswordableBehavior.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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 (require=>false 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. * @version 1.7 (Now CakePHP2.4/2.5 ready - with passwordHasher support)
  33. * @author Mark Scherer
  34. * @link http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp
  35. * @license MIT
  36. * 2012-08-18 ms
  37. */
  38. class PasswordableBehavior extends ModelBehavior {
  39. /**
  40. * @var array
  41. */
  42. protected $_defaults = array(
  43. 'field' => 'password',
  44. 'confirm' => true, // Set to false if in admin view and no confirmation (pwd_repeat) is required
  45. 'require' => true, // If a password change is required (set to false for edit forms, leave it true for pure password update forms)
  46. 'allowEmpty' => false, // Deprecated, do NOT use anymore! Use require instead!
  47. 'current' => false, // Enquire the current password for security purposes
  48. 'formField' => 'pwd',
  49. 'formFieldRepeat' => 'pwd_repeat',
  50. 'formFieldCurrent' => 'pwd_current',
  51. 'userModel' => null, // Defaults to User
  52. 'hashType' => null, // Only for authType Form [cake2.3]
  53. 'hashSalt' => true, // Only for authType Form [cake2.3]
  54. 'auth' => null, // Which component (defaults to AuthComponent),
  55. 'authType' => 'Form', // Which type of authenticate (Form, Blowfish, ...) [cake2.4]
  56. 'passwordHasher' => null, // If a custom pwd hasher is been used [cake2.4]
  57. 'allowSame' => true, // Don't allow the old password on change
  58. 'minLength' => PWD_MIN_LENGTH,
  59. 'maxLength' => PWD_MAX_LENGTH
  60. );
  61. /**
  62. * @var array
  63. */
  64. protected $_validationRules = array(
  65. 'formField' => array(
  66. 'between' => array(
  67. 'rule' => array('between', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  68. 'message' => array('valErrBetweenCharacters %s %s', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  69. 'allowEmpty' => null,
  70. 'last' => true,
  71. )
  72. ),
  73. 'formFieldRepeat' => array(
  74. 'between' => array(
  75. 'rule' => array('between', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  76. 'message' => array('valErrBetweenCharacters %s %s', PWD_MIN_LENGTH, PWD_MAX_LENGTH),
  77. 'allowEmpty' => null,
  78. 'last' => true,
  79. ),
  80. 'validateIdentical' => array(
  81. 'rule' => array('validateIdentical', 'formField'),
  82. 'message' => 'valErrPwdNotMatch',
  83. 'allowEmpty' => null,
  84. 'last' => true,
  85. ),
  86. ),
  87. 'formFieldCurrent' => array(
  88. 'notEmpty' => array(
  89. 'rule' => array('notEmpty'),
  90. 'message' => 'valErrProvideCurrentPwd',
  91. 'allowEmpty' => null,
  92. 'last' => true,
  93. ),
  94. 'validateCurrentPwd' => array(
  95. 'rule' => 'validateCurrentPwd',
  96. 'message' => 'valErrCurrentPwdIncorrect',
  97. 'allowEmpty' => null,
  98. 'last' => true,
  99. )
  100. ),
  101. );
  102. /**
  103. * If not implemented in AppModel
  104. *
  105. * Note: requires the used Auth component to be App::uses() loaded.
  106. * It also reqires the same Auth setup as in your AppController's beforeFilter().
  107. * So if you set up any special passwordHasher or auth type, you need to provide those
  108. * with the settings passed to the behavior:
  109. *
  110. * 'authType' => 'Blowfish', 'passwordHasher' => array(
  111. * 'className' => 'Simple',
  112. * 'hashType' => 'sha256'
  113. * )
  114. *
  115. * @throws CakeException
  116. * @param Model $Model
  117. * @param array $data
  118. * @return boolean 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. *
  166. * @param Model $Model
  167. * @param array $data
  168. * @param string $compareWith String to compare field value with
  169. * @return boolean Success
  170. * 2011-07-22 ms
  171. */
  172. public function validateIdentical(Model $Model, $data, $compareWith = null) {
  173. if (is_array($data)) {
  174. $value = array_shift($data);
  175. } else {
  176. $value = $data;
  177. }
  178. $compareValue = $Model->data[$Model->alias][$compareWith];
  179. return ($compareValue === $value);
  180. }
  181. /**
  182. * if not implemented in AppModel
  183. *
  184. * @return boolean Success
  185. * 2011-11-10 ms
  186. */
  187. public function validateNotSame(Model $Model, $data, $field1, $field2) {
  188. $value1 = $Model->data[$Model->alias][$field1];
  189. $value2 = $Model->data[$Model->alias][$field2];
  190. return ($value1 !== $value2);
  191. }
  192. /**
  193. * if not implemented in AppModel
  194. *
  195. * @return boolean Success
  196. * 2011-11-10 ms
  197. */
  198. public function validateNotSameHash(Model $Model, $data, $formField) {
  199. $field = $this->settings[$Model->alias]['field'];
  200. $type = $this->settings[$Model->alias]['hashType'];
  201. $salt = $this->settings[$Model->alias]['hashSalt'];
  202. if ($this->settings[$Model->alias]['authType'] === 'Blowfish') {
  203. $type = 'blowfish';
  204. $salt = false;
  205. }
  206. if (!isset($Model->data[$Model->alias][$Model->primaryKey])) {
  207. return true;
  208. }
  209. $primaryKey = $Model->data[$Model->alias][$Model->primaryKey];
  210. $value = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  211. $dbValue = $Model->field($field, array($Model->primaryKey => $primaryKey));
  212. if (!$dbValue) {
  213. return true;
  214. }
  215. return ($value !== $dbValue);
  216. }
  217. /**
  218. * Adding validation rules
  219. * also adds and merges config settings (direct + configure)
  220. *
  221. * @return void
  222. * 2011-08-24 ms
  223. */
  224. public function setup(Model $Model, $config = array()) {
  225. $defaults = $this->_defaults;
  226. if ($configureDefaults = Configure::read('Passwordable')) {
  227. $defaults = Set::merge($defaults, $configureDefaults);
  228. }
  229. $this->settings[$Model->alias] = Set::merge($defaults, $config);
  230. // BC comp
  231. if ($this->settings[$Model->alias]['allowEmpty']) {
  232. $this->settings[$Model->alias]['require'] = false;
  233. }
  234. $formField = $this->settings[$Model->alias]['formField'];
  235. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  236. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  237. $rules = $this->_validationRules;
  238. foreach ($rules as $key => $rule) {
  239. foreach ($rule as $rK => $rR) {
  240. $rR['allowEmpty'] = !$this->settings[$Model->alias]['require'];
  241. $rules[$key][$rK] = $rR;
  242. }
  243. }
  244. # add the validation rules if not already attached
  245. if (!isset($Model->validate[$formField])) {
  246. $Model->validator()->add($formField, $rules['formField']);
  247. }
  248. if (!isset($Model->validate[$formFieldRepeat])) {
  249. $ruleSet = $rules['formFieldRepeat'];
  250. $ruleSet['validateIdentical']['rule'][1] = $formField;
  251. $Model->validator()->add($formFieldRepeat, $ruleSet);
  252. }
  253. if ($this->settings[$Model->alias]['current'] && !isset($Model->validate[$formFieldCurrent])) {
  254. $Model->validator()->add($formFieldCurrent, $rules['formFieldCurrent']);
  255. if (!$this->settings[$Model->alias]['allowSame']) {
  256. $Model->validator()->add($formField, 'validateNotSame', array(
  257. 'rule' => array('validateNotSame', $formField, $formFieldCurrent),
  258. 'message' => 'valErrPwdSameAsBefore',
  259. 'allowEmpty' => !$this->settings[$Model->alias]['require'],
  260. 'last' => true,
  261. ));
  262. }
  263. } elseif (!isset($Model->validate[$formFieldCurrent])) {
  264. # try to match the password against the hash in the DB
  265. if (!$this->settings[$Model->alias]['allowSame']) {
  266. $Model->validator()->add($formField, 'validateNotSame', array(
  267. 'rule' => array('validateNotSameHash', $formField),
  268. 'message' => 'valErrPwdSameAsBefore',
  269. 'allowEmpty' => !$this->settings[$Model->alias]['require'],
  270. 'last' => true,
  271. ));
  272. }
  273. }
  274. }
  275. /**
  276. * Preparing the data
  277. *
  278. * @return boolean Success
  279. * 2011-07-22 ms
  280. */
  281. public function beforeValidate(Model $Model, $options = array()) {
  282. $formField = $this->settings[$Model->alias]['formField'];
  283. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  284. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  285. # make sure fields are set and validation rules are triggered - prevents tempering of form data
  286. if (!isset($Model->data[$Model->alias][$formField])) {
  287. $Model->data[$Model->alias][$formField] = '';
  288. }
  289. if ($this->settings[$Model->alias]['confirm'] && !isset($Model->data[$Model->alias][$formFieldRepeat])) {
  290. $Model->data[$Model->alias][$formFieldRepeat] = '';
  291. }
  292. if ($this->settings[$Model->alias]['current'] && !isset($Model->data[$Model->alias][$formFieldCurrent])) {
  293. $Model->data[$Model->alias][$formFieldCurrent] = '';
  294. }
  295. # check if we need to trigger any validation rules
  296. if (!$this->settings[$Model->alias]['require']) {
  297. $current = !empty($Model->data[$Model->alias][$formFieldCurrent]);
  298. $new = !empty($Model->data[$Model->alias][$formField]) || !empty($Model->data[$Model->alias][$formFieldRepeat]);
  299. if (!$new && !$current) {
  300. //$Model->validator()->remove($formField); // tmp only!
  301. //unset($Model->validate[$formField]);
  302. unset($Model->data[$Model->alias][$formField]);
  303. if ($this->settings[$Model->alias]['confirm']) {
  304. //$Model->validator()->remove($formFieldRepeat); // tmp only!
  305. //unset($Model->validate[$formFieldRepeat]);
  306. unset($Model->data[$Model->alias][$formFieldRepeat]);
  307. }
  308. if ($this->settings[$Model->alias]['current']) {
  309. //$Model->validator()->remove($formFieldCurrent); // tmp only!
  310. //unset($Model->validate[$formFieldCurrent]);
  311. unset($Model->data[$Model->alias][$formFieldCurrent]);
  312. }
  313. return true;
  314. }
  315. }
  316. # add fields to whitelist!
  317. $whitelist = array($this->settings[$Model->alias]['formField'], $this->settings[$Model->alias]['formFieldRepeat']);
  318. if ($this->settings[$Model->alias]['current']) {
  319. $whitelist[] = $this->settings[$Model->alias]['formFieldCurrent'];
  320. }
  321. if (!empty($Model->whitelist)) {
  322. $Model->whitelist = array_merge($Model->whitelist, $whitelist);
  323. }
  324. return true;
  325. }
  326. /**
  327. * Hashing the password and whitelisting
  328. *
  329. * @return boolean Success
  330. * 2011-07-22 ms
  331. */
  332. public function beforeSave(Model $Model, $options = array()) {
  333. $formField = $this->settings[$Model->alias]['formField'];
  334. $field = $this->settings[$Model->alias]['field'];
  335. $type = $this->settings[$Model->alias]['hashType'];
  336. $salt = $this->settings[$Model->alias]['hashSalt'];
  337. if ($this->settings[$Model->alias]['authType'] === 'Blowfish') {
  338. $type = 'blowfish';
  339. $salt = false;
  340. }
  341. if (isset($Model->data[$Model->alias][$formField])) {
  342. $Model->data[$Model->alias][$field] = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  343. unset($Model->data[$Model->alias][$formField]);
  344. if ($this->settings[$Model->alias]['confirm']) {
  345. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  346. unset($Model->data[$Model->alias][$formFieldRepeat]);
  347. }
  348. if ($this->settings[$Model->alias]['current']) {
  349. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  350. unset($Model->data[$Model->alias][$formFieldCurrent]);
  351. }
  352. # update whitelist
  353. if (!empty($Model->whitelist)) {
  354. $Model->whitelist = array_merge($Model->whitelist, array($field));
  355. }
  356. }
  357. return true;
  358. }
  359. }