PasswordableBehavior.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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. '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. * @var array
  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. * @param Model $Model
  119. * @param array $data
  120. * @return bool Success
  121. * 2011-07-22 ms
  122. */
  123. public function validateCurrentPwd(Model $Model, $data) {
  124. if (is_array($data)) {
  125. $pwd = array_shift($data);
  126. } else {
  127. $pwd = $data;
  128. }
  129. $uid = null;
  130. if ($Model->id) {
  131. $uid = $Model->id;
  132. } elseif (!empty($Model->data[$Model->alias]['id'])) {
  133. $uid = $Model->data[$Model->alias]['id'];
  134. } else {
  135. trigger_error('No user id given');
  136. return false;
  137. }
  138. $auth = 'Auth';
  139. if (empty($this->settings[$Model->alias]['auth']) && class_exists('AuthExtComponent')) {
  140. $auth = 'AuthExt';
  141. } elseif ($this->settings[$Model->alias]['auth']) {
  142. $auth = $this->settings[$Model->alias]['auth'];
  143. }
  144. $authClass = $auth . 'Component';
  145. if (!class_exists($authClass)) {
  146. throw new CakeException('No Authentication class found (' . $authClass. ')');
  147. }
  148. $this->Auth = new $authClass(new ComponentCollection());
  149. # easiest authenticate method via form and (id + pwd)
  150. $authConfig = array(
  151. 'fields' => array('username' => 'id', 'password' => $this->settings[$Model->alias]['field']),
  152. 'userModel' => $this->settings[$Model->alias]['userModel'] ? $this->settings[$Model->alias]['userModel'] : $Model->alias
  153. );
  154. if (!empty($this->settings[$Model->alias]['passwordHasher'])) {
  155. $authConfig['passwordHasher'] = $this->settings[$Model->alias]['passwordHasher'];
  156. }
  157. $this->Auth->authenticate = array(
  158. $this->settings[$Model->alias]['authType'] => $authConfig
  159. );
  160. $request = Router::getRequest();
  161. $request->data[$Model->alias] = array('id' => $uid, 'password' => $pwd);
  162. $response = new CakeResponse();
  163. return (bool)$this->Auth->identify($request, $response);
  164. }
  165. /**
  166. * if not implemented in AppModel
  167. *
  168. * @param Model $Model
  169. * @param array $data
  170. * @param string $compareWith String to compare field value with
  171. * @return bool Success
  172. * 2011-07-22 ms
  173. */
  174. public function validateIdentical(Model $Model, $data, $compareWith = null) {
  175. if (is_array($data)) {
  176. $value = array_shift($data);
  177. } else {
  178. $value = $data;
  179. }
  180. $compareValue = $Model->data[$Model->alias][$compareWith];
  181. return ($compareValue === $value);
  182. }
  183. /**
  184. * if not implemented in AppModel
  185. *
  186. * @return bool Success
  187. * 2011-11-10 ms
  188. */
  189. public function validateNotSame(Model $Model, $data, $field1, $field2) {
  190. $value1 = $Model->data[$Model->alias][$field1];
  191. $value2 = $Model->data[$Model->alias][$field2];
  192. return ($value1 !== $value2);
  193. }
  194. /**
  195. * if not implemented in AppModel
  196. *
  197. * @return bool Success
  198. * 2011-11-10 ms
  199. */
  200. public function validateNotSameHash(Model $Model, $data, $formField) {
  201. $field = $this->settings[$Model->alias]['field'];
  202. $type = $this->settings[$Model->alias]['hashType'];
  203. $salt = $this->settings[$Model->alias]['hashSalt'];
  204. if ($this->settings[$Model->alias]['authType'] === 'Blowfish') {
  205. $type = 'blowfish';
  206. $salt = false;
  207. }
  208. if (!isset($Model->data[$Model->alias][$Model->primaryKey])) {
  209. return true;
  210. }
  211. $primaryKey = $Model->data[$Model->alias][$Model->primaryKey];
  212. $value = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  213. $dbValue = $Model->field($field, array($Model->primaryKey => $primaryKey));
  214. if (!$dbValue) {
  215. return true;
  216. }
  217. return ($value !== $dbValue);
  218. }
  219. /**
  220. * Adding validation rules
  221. * also adds and merges config settings (direct + configure)
  222. *
  223. * @return void
  224. * 2011-08-24 ms
  225. */
  226. public function setup(Model $Model, $config = array()) {
  227. $defaults = $this->_defaults;
  228. if ($configureDefaults = Configure::read('Passwordable')) {
  229. $defaults = Set::merge($defaults, $configureDefaults);
  230. }
  231. $this->settings[$Model->alias] = Set::merge($defaults, $config);
  232. $formField = $this->settings[$Model->alias]['formField'];
  233. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  234. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  235. $rules = $this->_validationRules;
  236. # add the validation rules if not already attached
  237. if (!isset($Model->validate[$formField])) {
  238. $Model->validator()->add($formField, $rules['formField']);
  239. }
  240. if (!isset($Model->validate[$formFieldRepeat])) {
  241. $ruleSet = $rules['formFieldRepeat'];
  242. $ruleSet['validateIdentical']['rule'][1] = $formField;
  243. $Model->validator()->add($formFieldRepeat, $ruleSet);
  244. }
  245. if ($this->settings[$Model->alias]['current'] && !isset($Model->validate[$formFieldCurrent])) {
  246. $Model->validator()->add($formFieldCurrent, $rules['formFieldCurrent']);
  247. if (!$this->settings[$Model->alias]['allowSame']) {
  248. $Model->validator()->add($formField, 'validateNotSame', array(
  249. 'rule' => array('validateNotSame', $formField, $formFieldCurrent),
  250. 'message' => 'valErrPwdSameAsBefore',
  251. 'allowEmpty' => $this->settings[$Model->alias]['allowEmpty'],
  252. 'last' => true,
  253. ));
  254. }
  255. } elseif (!isset($Model->validate[$formFieldCurrent])) {
  256. # try to match the password against the hash in the DB
  257. if (!$this->settings[$Model->alias]['allowSame']) {
  258. $Model->validator()->add($formField, 'validateNotSame', array(
  259. 'rule' => array('validateNotSameHash', $formField),
  260. 'message' => 'valErrPwdSameAsBefore',
  261. 'allowEmpty' => $this->settings[$Model->alias]['allowEmpty'],
  262. 'last' => true,
  263. ));
  264. }
  265. }
  266. }
  267. /**
  268. * Preparing the data
  269. *
  270. * @return bool Success
  271. * 2011-07-22 ms
  272. */
  273. public function beforeValidate(Model $Model) {
  274. $formField = $this->settings[$Model->alias]['formField'];
  275. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  276. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  277. # make sure fields are set and validation rules are triggered - prevents tempering of form data
  278. if (!isset($Model->data[$Model->alias][$formField])) {
  279. $Model->data[$Model->alias][$formField] = '';
  280. }
  281. if ($this->settings[$Model->alias]['confirm'] && !isset($Model->data[$Model->alias][$formFieldRepeat])) {
  282. $Model->data[$Model->alias][$formFieldRepeat] = '';
  283. }
  284. if ($this->settings[$Model->alias]['current'] && !isset($Model->data[$Model->alias][$formFieldCurrent])) {
  285. $Model->data[$Model->alias][$formFieldCurrent] = '';
  286. }
  287. # check if we need to trigger any validation rules
  288. if ($this->settings[$Model->alias]['allowEmpty']) {
  289. $current = !empty($Model->data[$Model->alias][$formFieldCurrent]);
  290. $new = !empty($Model->data[$Model->alias][$formField]) || !empty($Model->data[$Model->alias][$formFieldRepeat]);
  291. if (!$new && !$current) {
  292. //$Model->validator()->remove($formField); // tmp only!
  293. //unset($Model->validate[$formField]);
  294. unset($Model->data[$Model->alias][$formField]);
  295. if ($this->settings[$Model->alias]['confirm']) {
  296. //$Model->validator()->remove($formFieldRepeat); // tmp only!
  297. //unset($Model->validate[$formFieldRepeat]);
  298. unset($Model->data[$Model->alias][$formFieldRepeat]);
  299. }
  300. if ($this->settings[$Model->alias]['current']) {
  301. //$Model->validator()->remove($formFieldCurrent); // tmp only!
  302. //unset($Model->validate[$formFieldCurrent]);
  303. unset($Model->data[$Model->alias][$formFieldCurrent]);
  304. }
  305. return true;
  306. }
  307. }
  308. # add fields to whitelist!
  309. $whitelist = array($this->settings[$Model->alias]['formField'], $this->settings[$Model->alias]['formFieldRepeat']);
  310. if ($this->settings[$Model->alias]['current']) {
  311. $whitelist[] = $this->settings[$Model->alias]['formFieldCurrent'];
  312. }
  313. if (!empty($Model->whitelist)) {
  314. $Model->whitelist = array_merge($Model->whitelist, $whitelist);
  315. }
  316. return true;
  317. }
  318. /**
  319. * Hashing the password and whitelisting
  320. *
  321. * @return bool Success
  322. * 2011-07-22 ms
  323. */
  324. public function beforeSave(Model $Model) {
  325. $formField = $this->settings[$Model->alias]['formField'];
  326. $field = $this->settings[$Model->alias]['field'];
  327. $type = $this->settings[$Model->alias]['hashType'];
  328. $salt = $this->settings[$Model->alias]['hashSalt'];
  329. if ($this->settings[$Model->alias]['authType'] === 'Blowfish') {
  330. $type = 'blowfish';
  331. $salt = false;
  332. }
  333. if (isset($Model->data[$Model->alias][$formField])) {
  334. $Model->data[$Model->alias][$field] = Security::hash($Model->data[$Model->alias][$formField], $type, $salt);
  335. unset($Model->data[$Model->alias][$formField]);
  336. if ($this->settings[$Model->alias]['confirm']) {
  337. $formFieldRepeat = $this->settings[$Model->alias]['formFieldRepeat'];
  338. unset($Model->data[$Model->alias][$formFieldRepeat]);
  339. }
  340. if ($this->settings[$Model->alias]['current']) {
  341. $formFieldCurrent = $this->settings[$Model->alias]['formFieldCurrent'];
  342. unset($Model->data[$Model->alias][$formFieldCurrent]);
  343. }
  344. # update whitelist
  345. if (!empty($Model->whitelist)) {
  346. $Model->whitelist = array_merge($Model->whitelist, array($field));
  347. }
  348. }
  349. return true;
  350. }
  351. }