Auth.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. <?php
  2. /**
  3. * This file is part of the ForkBB <https://github.com/forkbb>.
  4. *
  5. * @copyright (c) Visman <mio.visman@yandex.ru, https://github.com/MioVisman>
  6. * @license The MIT License (MIT)
  7. */
  8. declare(strict_types=1);
  9. namespace ForkBB\Models\Pages;
  10. use ForkBB\Core\Validator;
  11. use ForkBB\Core\Exceptions\MailException;
  12. use ForkBB\Models\Page;
  13. use ForkBB\Models\User\Model as User;
  14. use function \ForkBB\__;
  15. class Auth extends Page
  16. {
  17. /**
  18. * Выход пользователя
  19. */
  20. public function logout(array $args): Page
  21. {
  22. if (! $this->c->Csrf->verify($args['token'], 'Logout', $args)) {
  23. $this->c->Log->warning('Logout: fail', [
  24. 'user' => $this->user->fLog(),
  25. ]);
  26. return $this->c->Redirect->page('Index')->message($this->c->Csrf->getError());
  27. }
  28. $this->c->Cookie->deleteUser();
  29. $this->c->Online->delete($this->user);
  30. $this->c->users->updateLastVisit($this->user);
  31. $this->c->Log->info('Logout: ok', [
  32. 'user' => $this->user->fLog(),
  33. ]);
  34. $this->c->Lang->load('auth');
  35. return $this->c->Redirect->page('Index')->message('Logout redirect');
  36. }
  37. /**
  38. * Вход на форум
  39. */
  40. public function login(array $args, string $method, string $username = ''): Page
  41. {
  42. $this->c->Lang->load('validator');
  43. $this->c->Lang->load('auth');
  44. $v = null;
  45. if ('POST' === $method) {
  46. $v = $this->c->Validator->reset()
  47. ->addValidators([
  48. 'login_check' => [$this, 'vLoginCheck'],
  49. ])->addRules([
  50. 'token' => 'token:Login',
  51. 'redirect' => 'required|referer:Index',
  52. 'username' => 'required|string',
  53. 'password' => 'required|string|login_check',
  54. 'save' => 'checkbox',
  55. 'login' => 'required|string',
  56. ])->addAliases([
  57. 'username' => 'Username',
  58. 'password' => 'Passphrase',
  59. ]);
  60. $v = $this->c->Test->beforeValidation($v);
  61. if ($v->validation($_POST, true)) {
  62. $this->loginEnd($v);
  63. return $this->c->Redirect->url($v->redirect)->message('Login redirect');
  64. }
  65. $this->fIswev = $v->getErrors();
  66. $this->c->Log->warning('Login: fail', [
  67. 'user' => $this->user->fLog(),
  68. 'errors' => $v->getErrorsWithoutType(),
  69. 'form' => $v->getData(false, ['token', 'password']),
  70. ]);
  71. $this->httpStatus = 400;
  72. }
  73. $ref = $this->c->Secury->replInvalidChars($_SERVER['HTTP_REFERER'] ?? '');
  74. $this->hhsLevel = 'secure';
  75. $this->fIndex = 'login';
  76. $this->nameTpl = 'login';
  77. $this->onlinePos = 'login';
  78. $this->robots = 'noindex';
  79. $this->titles = __('Login');
  80. $this->regLink = '1' == $this->c->config->o_regs_allow ? $this->c->Router->link('Register') : null;
  81. $username = $v ? $v->username : $username;
  82. $save = $v ? $v->save : 1;
  83. $redirect = $v ? $v->redirect : $this->c->Router->validate($ref, 'Index');
  84. $this->form = $this->formLogin($username, $save, $redirect);
  85. return $this;
  86. }
  87. /**
  88. * Обрабатывает вход пользователя
  89. */
  90. protected function loginEnd(Validator $v): void
  91. {
  92. $this->c->users->updateLoginIpCache($this->userAfterLogin, true); // ????
  93. // сбросить запрос на смену кодовой фразы
  94. if (32 === \strlen($this->userAfterLogin->activate_string)) {
  95. $this->userAfterLogin->activate_string = '';
  96. }
  97. // изменения юзера в базе
  98. $this->c->users->update($this->userAfterLogin);
  99. $this->c->Online->delete($this->user);
  100. $this->c->Cookie->setUser($this->userAfterLogin, (bool) $v->save);
  101. $this->c->Log->info('Login: ok', [
  102. 'user' => $this->userAfterLogin->fLog(),
  103. 'form' => $v->getData(false, ['token', 'password']),
  104. 'headers' => true,
  105. ]);
  106. }
  107. /**
  108. * Подготавливает массив данных для формы
  109. */
  110. protected function formLogin(string $username, /* mixed */ $save, string $redirect): array
  111. {
  112. return [
  113. 'action' => $this->c->Router->link('Login'),
  114. 'hidden' => [
  115. 'token' => $this->c->Csrf->create('Login'),
  116. 'redirect' => $redirect,
  117. ],
  118. 'sets' => [
  119. 'login' => [
  120. 'fields' => [
  121. 'username' => [
  122. 'autofocus' => true,
  123. 'type' => 'text',
  124. 'value' => $username,
  125. 'caption' => __('Username'),
  126. 'required' => true,
  127. ],
  128. 'password' => [
  129. 'id' => 'passinlogin',
  130. 'type' => 'password',
  131. 'caption' => __('Passphrase'),
  132. 'help' => ['<a href="%s">Forgotten?</a>', $this->c->Router->link('Forget')],
  133. 'required' => true,
  134. ],
  135. 'save' => [
  136. 'type' => 'checkbox',
  137. 'label' => __('Remember me'),
  138. 'value' => '1',
  139. 'checked' => $save,
  140. ],
  141. ],
  142. ],
  143. ],
  144. 'btns' => [
  145. 'login' => [
  146. 'type' => 'submit',
  147. 'value' => __('Sign in'),
  148. ],
  149. ],
  150. ];
  151. }
  152. /**
  153. * Проверка пользователя по базе
  154. */
  155. public function vLoginCheck(Validator $v, $password)
  156. {
  157. if (empty($v->getErrors())) {
  158. $this->userAfterLogin = $this->c->users->loadByName($v->username);
  159. if (
  160. ! $this->userAfterLogin instanceof User
  161. || $this->userAfterLogin->isGuest
  162. ) {
  163. $v->addError('Wrong user/pass');
  164. } elseif ($this->userAfterLogin->isUnverified) {
  165. $v->addError('Account is not activated', 'w');
  166. } elseif (! \password_verify($password, $this->userAfterLogin->password)) {
  167. $v->addError('Wrong user/pass');
  168. }
  169. }
  170. if (! empty($v->getErrors())) {
  171. $this->userAfterLogin = null;
  172. }
  173. return $password;
  174. }
  175. /**
  176. * Запрос на смену кодовой фразы
  177. */
  178. public function forget(array $args, string $method, string $email = ''): Page
  179. {
  180. $this->c->Lang->load('validator');
  181. $this->c->Lang->load('auth');
  182. $v = null;
  183. if ('POST' === $method) {
  184. $v = $this->c->Validator->reset()
  185. ->addValidators([
  186. ])->addRules([
  187. 'token' => 'token:Forget',
  188. 'email' => 'required|string:trim|email',
  189. 'submit' => 'required|string',
  190. ])->addAliases([
  191. ])->addMessages([
  192. 'email.email' => 'Invalid email',
  193. ])->addArguments([
  194. ]);
  195. $v = $this->c->Test->beforeValidation($v);
  196. $isValid = $v->validation($_POST, true);
  197. $context = [
  198. 'user' => $this->user->fLog(), // ???? Guest only?
  199. 'errors' => $v->getErrorsWithoutType(),
  200. 'form' => $v->getData(false, ['token']),
  201. 'headers' => true,
  202. ];
  203. if ($isValid) {
  204. $tmpUser = $this->c->users->create();
  205. $isSent = false;
  206. $v = $v->reset()
  207. ->addRules([
  208. 'email' => 'required|string:trim|email:nosoloban,exists,flood',
  209. ])->addArguments([
  210. 'email.email' => $tmpUser, // сюда идет возрат данных по найденному пользователю
  211. ]);
  212. if (
  213. $v->validation($_POST)
  214. && 0 === $this->c->bans->banFromName($tmpUser->username)
  215. ) {
  216. $this->c->Csrf->setHashExpiration(259200); // ???? хэш действует 72 часа
  217. $key = $this->c->Secury->randomPass(32);
  218. $link = $this->c->Router->link(
  219. 'ChangePassword',
  220. [
  221. 'id' => $tmpUser->id,
  222. 'key' => $key,
  223. ]
  224. );
  225. $tplData = [
  226. 'fRootLink' => $this->c->Router->link('Index'),
  227. 'fMailer' => __(['Mailer', $this->c->config->o_board_title]),
  228. 'username' => $tmpUser->username,
  229. 'link' => $link,
  230. ];
  231. try {
  232. $isSent = $this->c->Mail
  233. ->reset()
  234. ->setMaxRecipients(1)
  235. ->setFolder($this->c->DIR_LANG)
  236. ->setLanguage($tmpUser->language)
  237. ->setTo($tmpUser->email, $tmpUser->username)
  238. ->setFrom($this->c->config->o_webmaster_email, $tplData['fMailer'])
  239. ->setTpl('passphrase_reset.tpl', $tplData)
  240. ->send();
  241. } catch (MailException $e) {
  242. $this->c->Log->error('Passphrase reset: email form, MailException', [
  243. 'exception' => $e,
  244. 'headers' => false,
  245. ]);
  246. }
  247. if ($isSent) {
  248. $tmpUser->activate_string = $key;
  249. $tmpUser->last_email_sent = \time();
  250. $this->c->users->update($tmpUser);
  251. $this->c->Log->info('Passphrase reset: email form, ok', $context);
  252. }
  253. }
  254. if (! $isSent) {
  255. $context['errors'] = $v->getErrorsWithoutType();
  256. $this->c->Log->warning('Passphrase reset: email form, fail', $context);
  257. }
  258. return $this->c->Message->message(['Forget mail', $this->c->config->o_admin_email], false, 0);
  259. }
  260. $this->fIswev = $v->getErrors();
  261. $this->c->Log->warning('Passphrase reset: email form, fail', $context);
  262. $this->httpStatus = 400;
  263. }
  264. $this->hhsLevel = 'secure';
  265. $this->fIndex = 'login';
  266. $this->nameTpl = 'passphrase_reset';
  267. $this->onlinePos = 'passphrase_reset';
  268. $this->robots = 'noindex';
  269. $this->titles = __('Passphrase reset');
  270. $this->form = $this->formForget($v ? $v->email : $email);
  271. return $this;
  272. }
  273. /**
  274. * Подготавливает массив данных для формы
  275. */
  276. protected function formForget(string $email): array
  277. {
  278. return [
  279. 'action' => $this->c->Router->link('Forget'),
  280. 'hidden' => [
  281. 'token' => $this->c->Csrf->create('Forget'),
  282. ],
  283. 'sets' => [
  284. 'forget' => [
  285. 'fields' => [
  286. 'email' => [
  287. 'autofocus' => true,
  288. 'type' => 'text',
  289. 'maxlength' => '80',
  290. 'value' => $email,
  291. 'caption' => __('Email'),
  292. 'help' => 'Passphrase reset info',
  293. 'required' => true,
  294. 'pattern' => '.+@.+',
  295. ],
  296. ],
  297. ],
  298. ],
  299. 'btns' => [
  300. 'submit' => [
  301. 'type' => 'submit',
  302. 'value' => __('Send email'),
  303. ],
  304. ],
  305. ];
  306. }
  307. /**
  308. * Смена кодовой фразы
  309. */
  310. public function changePass(array $args, string $method): Page
  311. {
  312. if (
  313. ! $this->c->Csrf->verify($args['hash'], 'ChangePassword', $args)
  314. || ! ($user = $this->c->users->load($args['id'])) instanceof User
  315. || ! \hash_equals($user->activate_string, $args['key'])
  316. ) {
  317. $this->c->Log->warning('Passphrase reset: confirmation, fail', [
  318. 'user' => $user instanceof User ? $user->fLog() : $this->user->fLog(),
  319. 'args' => $args,
  320. ]);
  321. // что-то пошло не так
  322. return $this->c->Message->message('Bad request', false);
  323. }
  324. $this->c->Lang->load('validator');
  325. $this->c->Lang->load('auth');
  326. if ('POST' === $method) {
  327. $v = $this->c->Validator->reset()
  328. ->addRules([
  329. 'token' => 'token:ChangePassword',
  330. 'password' => 'required|string|min:16|password',
  331. 'password2' => 'required|same:password',
  332. 'submit' => 'required|string',
  333. ])->addAliases([
  334. 'password' => 'New pass',
  335. 'password2' => 'Confirm new pass',
  336. ])->addArguments([
  337. 'token' => $args,
  338. ])->addMessages([
  339. 'password.password' => 'Pass format',
  340. 'password2.same' => 'Pass not match',
  341. ]);
  342. $v = $this->c->Test->beforeValidation($v);
  343. if ($v->validation($_POST, true)) {
  344. $user->password = \password_hash($v->password, \PASSWORD_DEFAULT);
  345. $user->email_confirmed = 1;
  346. $user->activate_string = '';
  347. $this->c->users->update($user);
  348. $this->fIswev = ['s', 'Pass updated'];
  349. $this->c->Log->info('Passphrase reset: ok', [
  350. 'user' => $user->fLog(),
  351. ]);
  352. return $this->login([], 'GET');
  353. }
  354. $this->fIswev = $v->getErrors();
  355. $this->c->Log->warning('Passphrase reset: change form, fail', [
  356. 'user' => $user->fLog(),
  357. 'errors' => $v->getErrorsWithoutType(),
  358. 'form' => $v->getData(false, ['token', 'password', 'password2']),
  359. ]);
  360. $this->httpStatus = 400;
  361. }
  362. // активация аккаунта (письмо активации не дошло, заказали восстановление)
  363. if ($user->isUnverified) {
  364. $user->group_id = $this->c->config->i_default_user_group;
  365. $user->email_confirmed = 1;
  366. $this->c->users->update($user);
  367. $this->fIswev = ['i', 'Account activated'];
  368. $this->c->Log->info('Account activation: ok', [
  369. 'user' => $user->fLog(),
  370. ]);
  371. }
  372. $this->hhsLevel = 'secure';
  373. $this->fIndex = 'login';
  374. $this->nameTpl = 'change_passphrase';
  375. $this->onlinePos = 'change_passphrase';
  376. $this->robots = 'noindex';
  377. $this->titles = __('Passphrase reset');
  378. $this->form = $this->formChange($args);
  379. return $this;
  380. }
  381. /**
  382. * Подготавливает массив данных для формы
  383. */
  384. protected function formChange(array $args): array
  385. {
  386. return [
  387. 'action' => $this->c->Router->link('ChangePassword', $args),
  388. 'hidden' => [
  389. 'token' => $this->c->Csrf->create('ChangePassword', $args),
  390. ],
  391. 'sets' => [
  392. 'forget' => [
  393. 'fields' => [
  394. 'password' => [
  395. 'autofocus' => true,
  396. 'type' => 'password',
  397. 'caption' => __('New pass'),
  398. 'required' => true,
  399. 'pattern' => '^.{16,}$',
  400. ],
  401. 'password2' => [
  402. 'type' => 'password',
  403. 'caption' => __('Confirm new pass'),
  404. 'help' => 'Passphrase help',
  405. 'required' => true,
  406. 'pattern' => '^.{16,}$',
  407. ],
  408. ],
  409. ],
  410. ],
  411. 'btns' => [
  412. 'submit' => [
  413. 'type' => 'submit',
  414. 'value' => __('Change passphrase'),
  415. ],
  416. ],
  417. ];
  418. }
  419. }