Controller.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. <?php
  2. /**
  3. * @package Grav\Plugin\Login
  4. *
  5. * @copyright Copyright (C) 2014 - 2020 RocketTheme, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Plugin\Login;
  9. use Grav\Common\Config\Config;
  10. use Grav\Common\Grav;
  11. use Grav\Common\Language\Language;
  12. use Grav\Common\Uri;
  13. use Grav\Common\User\Interfaces\UserCollectionInterface;
  14. use Grav\Common\User\Interfaces\UserInterface;
  15. use Grav\Common\Utils;
  16. use Grav\Plugin\Email\Utils as EmailUtils;
  17. use Grav\Plugin\Login\Events\UserLoginEvent;
  18. use Grav\Plugin\Login\TwoFactorAuth\TwoFactorAuth;
  19. use Grav\Plugin\LoginPlugin;
  20. use RocketTheme\Toolbox\Session\Message;
  21. /**
  22. * Class Controller
  23. * @package Grav\Plugin\Login
  24. */
  25. class Controller
  26. {
  27. /**
  28. * @var Grav
  29. */
  30. public $grav;
  31. /**
  32. * @var string
  33. */
  34. public $action;
  35. /**
  36. * @var array
  37. */
  38. public $post;
  39. /**
  40. * @var string
  41. */
  42. protected $redirect;
  43. /**
  44. * @var int
  45. */
  46. protected $redirectCode;
  47. /**
  48. * @var string
  49. */
  50. protected $prefix = 'task';
  51. /**
  52. * @var Login
  53. */
  54. protected $login;
  55. /**
  56. * @param Grav $grav
  57. * @param string $action
  58. * @param array $post
  59. */
  60. public function __construct(Grav $grav, $action, $post = null)
  61. {
  62. $this->grav = $grav;
  63. $this->action = $action;
  64. $this->login = $this->grav['login'];
  65. $this->post = $post ? $this->getPost($post) : [];
  66. }
  67. /**
  68. * Performs an action.
  69. * @throws \RuntimeException
  70. */
  71. public function execute()
  72. {
  73. $messages = $this->grav['messages'];
  74. // Set redirect if available.
  75. $redirect = $this->post['_redirect'] ?? null;
  76. unset($this->post['_redirect']);
  77. $success = false;
  78. $method = $this->prefix . ucfirst($this->action);
  79. if (!method_exists($this, $method)) {
  80. throw new \RuntimeException('Page Not Found', 404);
  81. }
  82. try {
  83. $success = $this->{$method}();
  84. } catch (\RuntimeException $e) {
  85. $messages->add($e->getMessage(), 'error');
  86. $this->grav['log']->error('plugin.login: '. $e->getMessage());
  87. }
  88. if (!$this->redirect && $redirect) {
  89. $this->setRedirect($redirect, 303);
  90. }
  91. return $success;
  92. }
  93. /**
  94. * Handle login.
  95. *
  96. * @return bool True if the action was performed.
  97. */
  98. public function taskLogin()
  99. {
  100. /** @var Language $t */
  101. $t = $this->grav['language'];
  102. /** @var Message $messages */
  103. $messages = $this->grav['messages'];
  104. // Remove login nonce from the form.
  105. $form = array_diff_key($this->post, ['login-form-nonce' => true]);
  106. // Is twofa enabled?
  107. $twofa = $this->grav['config']->get('plugins.login.twofa_enabled', false);
  108. // Fire Login process.
  109. $event = $this->login->login($form, ['rate_limit' => true, 'remember_me' => true, 'twofa' => $twofa], ['return_event' => true]);
  110. $user = $event->getUser();
  111. $login_redirect = LoginPlugin::defaultRedirectAfterLogin();
  112. if ($user->authenticated) {
  113. if ($user->authorized) {
  114. $event->defMessage('PLUGIN_LOGIN.LOGIN_SUCCESSFUL', 'info');
  115. $event->defRedirect(
  116. $this->grav['session']->redirect_after_login ?:
  117. $login_redirect ?: $this->grav['uri']->referrer('/')
  118. );
  119. } else {
  120. $redirect_to_login = $this->grav['config']->get('plugins.login.redirect_to_login');
  121. $login_route = $this->grav['config']->get('plugins.login.route');
  122. $redirect_route = $redirect_to_login && $login_route ? $login_route : false;
  123. $event->defRedirect($redirect_route ?: $this->grav['uri']->referrer('/'));
  124. }
  125. } else {
  126. if ($user->authorized) {
  127. $event->defMessage('PLUGIN_LOGIN.ACCESS_DENIED', 'error');
  128. $event->defRedirect($this->grav['config']->get('plugins.login.route_unauthorized', '/'));
  129. } else {
  130. $event->defMessage('PLUGIN_LOGIN.LOGIN_FAILED', 'error');
  131. }
  132. }
  133. $message = $event->getMessage();
  134. if ($message) {
  135. $messages->add($t->translate($message), $event->getMessageType());
  136. }
  137. $redirect = $event->getRedirect();
  138. if ($redirect) {
  139. $this->setRedirect($redirect, $event->getRedirectCode());
  140. }
  141. return true;
  142. }
  143. public function taskTwoFa()
  144. {
  145. /** @var Config $config */
  146. $config = $this->grav['config'];
  147. /** @var Language $t */
  148. $t = $this->grav['language'];
  149. /** @var Message $messages */
  150. $messages = $this->grav['messages'];
  151. if (!$config->get('plugins.login.twofa_enabled', false)) {
  152. $messages->add($t->translate('PLUGIN_LOGIN.2FA_FAILED'), 'error');
  153. return true;
  154. }
  155. $twoFa = $this->login->twoFactorAuth();
  156. $user = $this->grav['user'];
  157. $code = $this->post['2fa_code'] ?? null;
  158. $secret = $user->twofa_secret ?? null;
  159. $eventOptions = [
  160. 'credentials' => ['username' => $user->get('username')],
  161. 'options' => ['twofa' => true]
  162. ];
  163. // Attempt to authenticate the user.
  164. $event = new UserLoginEvent($eventOptions);
  165. $event->setUser($user);
  166. if (!$code || !$secret || !$twoFa->verifyCode($secret, $code)) {
  167. $event->setStatus(UserLoginEvent::AUTHENTICATION_FAILURE | UserLoginEvent::AUTHORIZATION_CHALLENGE);
  168. $event->setMessage($t->translate('PLUGIN_LOGIN.2FA_FAILED'), 'error');
  169. $this->grav->fireEvent('onUserLoginFailure', $event);
  170. // Make sure that event didn't mess up with the user authorization.
  171. $user = $event->getUser();
  172. $user->authenticated = false;
  173. $user->authorized = false;
  174. if (!$event->getRedirect()) {
  175. $redirect_to_login = $this->grav['config']->get('plugins.login.route_to_login');
  176. $login_route = $this->grav['config']->get('plugins.login.route');
  177. $event->setRedirect(
  178. $redirect_to_login && $login_route ? $login_route : $this->getCurrentRedirect(),
  179. 303
  180. );
  181. }
  182. } else {
  183. $event->setStatus(UserLoginEvent::AUTHENTICATION_SUCCESS | UserLoginEvent::AUTHORIZATION_CHALLENGE);
  184. $event->setMessage($t->translate('PLUGIN_LOGIN.LOGIN_SUCCESSFUL'), 'info');
  185. $this->grav->fireEvent('onUserLoginAuthorized', $event);
  186. // Make sure that event didn't mess up with the user authorization.
  187. $user = $event->getUser();
  188. $user->authenticated = $event->isSuccess();
  189. $user->authorized = !$event->isDelayed();
  190. if (!$event->getRedirect()) {
  191. $login_redirect = LoginPlugin::defaultRedirectAfterLogin();
  192. $event->setRedirect(
  193. $this->grav['session']->redirect_after_login ?: $login_redirect ?: $this->grav['uri']->referrer('/'),
  194. 303
  195. );
  196. }
  197. }
  198. /** @var Message $messages */
  199. $messages = $this->grav['messages'];
  200. $messages->add($event->getMessage(), $event->getMessageType());
  201. $redirect = $event->getRedirect() ?: $this->getCurrentRedirect();
  202. $this->setRedirect($redirect, $event->getRedirectCode());
  203. return true;
  204. }
  205. public function taskTwofa_cancel()
  206. {
  207. /** @var Config $config */
  208. $config = $this->grav['config'];
  209. /** @var Language $t */
  210. $t = $this->grav['language'];
  211. /** @var Message $messages */
  212. $messages = $this->grav['messages'];
  213. if (!$config->get('plugins.login.twofa_enabled', false)) {
  214. $messages->add($t->translate('PLUGIN_LOGIN.2FA_FAILED'), 'error');
  215. return true;
  216. }
  217. $user = $this->grav['user'];
  218. $eventOptions = [
  219. 'credentials' => ['username' => $user->get('username')],
  220. 'options' => ['twofa' => true]
  221. ];
  222. $event = new UserLoginEvent($eventOptions);
  223. $event->setStatus(UserLoginEvent::AUTHENTICATION_CANCELLED | UserLoginEvent::AUTHORIZATION_CHALLENGE);
  224. $event->setMessage($t->translate('PLUGIN_LOGIN.2FA_FAILED'), 'error');
  225. $this->grav->fireEvent('onUserLoginFailure', $event);
  226. // Make sure that event didn't mess up with the user authorization.
  227. $user = $event->getUser();
  228. $user->authenticated = false;
  229. $user->authorized = false;
  230. if (!$event->getRedirect()) {
  231. $redirect_to_login = $this->grav['config']->get('plugins.login.route_to_login');
  232. $login_route = $this->grav['config']->get('plugins.login.route');
  233. $event->setRedirect(
  234. $redirect_to_login && $login_route ? $login_route : $this->getCurrentRedirect(),
  235. 303
  236. );
  237. }
  238. return true;
  239. }
  240. /**
  241. * Handle logout.
  242. *
  243. * @return bool True if the action was performed.
  244. */
  245. public function taskLogout()
  246. {
  247. $event = $this->login->logout(['remember_me' => true], ['return_event' => true]);
  248. $message = $event->getMessage();
  249. if ($message) {
  250. /** @var Language $t */
  251. $t = $this->grav['language'];
  252. $messages = $this->grav['messages'];
  253. $messages->add($t->translate($message), $event->getMessageType());
  254. }
  255. $logout_redirect = LoginPlugin::defaultRedirectAfterLogout();
  256. $redirect = $event->getRedirect() ?: $logout_redirect ?: $this->getCurrentRedirect();
  257. if ($redirect) {
  258. $this->setRedirect($redirect, $event->getRedirectCode());
  259. }
  260. $this->grav['session']->setFlashCookieObject(LoginPlugin::TMP_COOKIE_NAME, ['message' => $this->grav['language']->translate('PLUGIN_LOGIN.LOGGED_OUT'),
  261. 'status' => 'info']);
  262. return true;
  263. }
  264. /**
  265. * Handle the email password recovery procedure.
  266. *
  267. * @return bool True if the action was performed.
  268. */
  269. protected function taskForgot()
  270. {
  271. $param_sep = $this->grav['config']->get('system.param_sep', ':');
  272. $data = $this->post;
  273. /** @var UserCollectionInterface $users */
  274. $users = $this->grav['accounts'];
  275. $email = $data['email'] ?? '';
  276. $user = !empty($email) ? $users->find($email, ['email']) : null;
  277. /** @var Language $language */
  278. $language = $this->grav['language'];
  279. $messages = $this->grav['messages'];
  280. if (!isset($this->grav['Email'])) {
  281. $messages->add($language->translate('PLUGIN_LOGIN.FORGOT_EMAIL_NOT_CONFIGURED'), 'error');
  282. $this->setRedirect($this->grav['config']->get('plugins.login.route_forgot', '/'));
  283. return true;
  284. }
  285. if (!$user || !$user->exists()) {
  286. $messages->add($language->translate('PLUGIN_LOGIN.FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL'), 'info');
  287. $this->setRedirect($this->grav['config']->get('plugins.login.route_forgot', '/'));
  288. return true;
  289. }
  290. if (empty($user->email)) {
  291. $messages->add($language->translate(['PLUGIN_LOGIN.FORGOT_CANNOT_RESET_EMAIL_NO_EMAIL', $email]),
  292. 'error');
  293. $this->setRedirect($this->grav['config']->get('plugins.login.route_forgot', '/'));
  294. return true;
  295. }
  296. if (empty($user->password) && empty($user->hashed_password)) {
  297. $messages->add($language->translate(['PLUGIN_LOGIN.FORGOT_CANNOT_RESET_EMAIL_NO_PASSWORD', $email]),
  298. 'error');
  299. $this->setRedirect($this->grav['config']->get('plugins.login.route_forgot', '/'));
  300. return true;
  301. }
  302. $from = $this->grav['config']->get('plugins.email.from');
  303. if (empty($from)) {
  304. $messages->add($language->translate('PLUGIN_LOGIN.FORGOT_EMAIL_NOT_CONFIGURED'), 'error');
  305. $this->setRedirect($this->grav['config']->get('plugins.login.route_forgot', '/'));
  306. return true;
  307. }
  308. $userKey = $user->username;
  309. $rateLimiter = $this->login->getRateLimiter('pw_resets');
  310. $rateLimiter->registerRateLimitedAction($userKey);
  311. if ($rateLimiter->isRateLimited($userKey)) {
  312. $messages->add($language->translate(['PLUGIN_LOGIN.FORGOT_CANNOT_RESET_IT_IS_BLOCKED', $email, $rateLimiter->getInterval()]), 'error');
  313. $this->setRedirect($this->grav['config']->get('plugins.login.route', '/'));
  314. return true;
  315. }
  316. $token = md5(uniqid(mt_rand(), true));
  317. $expire = time() + 604800; // next week
  318. $user->reset = $token . '::' . $expire;
  319. $user->save();
  320. $author = $this->grav['config']->get('site.author.name', '');
  321. $fullname = $user->fullname ?: $user->username;
  322. if ($this->grav['language']->getDefault() != $this->grav['language']->getLanguage()) {
  323. $lang = '/'.$this->grav['language']->getLanguage();
  324. } else {
  325. $lang = '';
  326. }
  327. $reset_link = $this->grav['base_url_absolute'] . $lang . $this->grav['config']->get('plugins.login.route_reset') . '/task' . $param_sep . 'login.reset/token' . $param_sep . $token . '/user' . $param_sep . $user->username . '/nonce' . $param_sep . Utils::getNonce('reset-form');
  328. $sitename = $this->grav['config']->get('site.title', 'Website');
  329. $to = $user->email;
  330. $subject = $language->translate(['PLUGIN_LOGIN.FORGOT_EMAIL_SUBJECT', $sitename]);
  331. $content = $language->translate(['PLUGIN_LOGIN.FORGOT_EMAIL_BODY', $fullname, $reset_link, $author, $sitename]);
  332. $sent = EmailUtils::sendEmail($subject, $content, $to);
  333. if ($sent < 1) {
  334. $messages->add($language->translate('PLUGIN_LOGIN.FORGOT_FAILED_TO_EMAIL'), 'error');
  335. } else {
  336. $messages->add($language->translate('PLUGIN_LOGIN.FORGOT_INSTRUCTIONS_SENT_VIA_EMAIL'), 'info');
  337. }
  338. $this->setRedirect($this->grav['config']->get('plugins.login.route', '/'));
  339. return true;
  340. }
  341. /**
  342. * Handle the reset password action.
  343. *
  344. * @return bool True if the action was performed.
  345. * @throws \Exception
  346. */
  347. public function taskReset()
  348. {
  349. $data = $this->post;
  350. $language = $this->grav['language'];
  351. $messages = $this->grav['messages'];
  352. if (isset($data['password'])) {
  353. /** @var UserCollectionInterface $users */
  354. $users = $this->grav['accounts'];
  355. $username = $data['username'] ?? null;
  356. $user = !empty($username) ? $users->find($username) : null;
  357. $password = $data['password'] ?? null;
  358. $token = $data['token'] ?? null;
  359. if ($user && !empty($user->reset) && $user->exists()) {
  360. [$good_token, $expire] = explode('::', $user->reset);
  361. if ($good_token === $token) {
  362. if (time() > $expire) {
  363. $messages->add($language->translate('PLUGIN_LOGIN.RESET_LINK_EXPIRED'), 'error');
  364. $this->grav->redirectLangSafe($this->grav['config']->get('plugins.login.route_forgot', '/'));
  365. return true;
  366. }
  367. unset($user->hashed_password, $user->reset);
  368. $user->password = $password;
  369. $user->save();
  370. $messages->add($language->translate('PLUGIN_LOGIN.RESET_PASSWORD_RESET'), 'info');
  371. $this->setRedirect($this->grav['config']->get('plugins.login.route', '/'));
  372. return true;
  373. }
  374. }
  375. $messages->add($language->translate('PLUGIN_LOGIN.RESET_INVALID_LINK'), 'error');
  376. $this->grav->redirectLangSafe($this->grav['config']->get('plugins.login.route_forgot'));
  377. return true;
  378. }
  379. $user = $this->grav['uri']->param('user');
  380. $token = $this->grav['uri']->param('token');
  381. if (!$user || !$token) {
  382. $messages->add($language->translate('PLUGIN_LOGIN.RESET_INVALID_LINK'), 'error');
  383. $this->grav->redirectLangSafe($this->grav['config']->get('plugins.login.route_forgot'));
  384. return true;
  385. }
  386. return true;
  387. }
  388. /**
  389. * @param null $secret
  390. * @return bool
  391. */
  392. public function taskRegenerate2FASecret()
  393. {
  394. try {
  395. /** @var UserInterface $user */
  396. $user = $this->grav['user'];
  397. if ($user->exists()) {
  398. /** @var TwoFactorAuth $twoFa */
  399. $twoFa = $this->grav['login']->twoFactorAuth();
  400. $secret = $twoFa->createSecret();
  401. $image = $twoFa->getQrImageData($user->username, $secret);
  402. // Change secret in the session.
  403. $user->twofa_secret = $secret;
  404. // Save secret into the user file.
  405. $user->save();
  406. $json_response = ['status' => 'success', 'image' => $image, 'secret' => trim(preg_replace('|(\w{4})|', '\\1 ', $secret))];
  407. } else {
  408. $json_response = ['status' => 'error', 'message' => 'user does not exist'];
  409. }
  410. } catch (\Exception $e) {
  411. $json_response = ['status' => 'error', 'message' => $e->getMessage()];
  412. }
  413. // Return JSON
  414. header('Content-Type: application/json');
  415. echo json_encode($json_response);
  416. exit;
  417. }
  418. /**
  419. * @return string
  420. */
  421. protected function getCurrentRedirect()
  422. {
  423. /** @var Uri $uri */
  424. $uri = $this->grav['uri'];
  425. $redirect = $uri->route();
  426. foreach ($uri->params(null, true) as $key => $value) {
  427. if (!in_array($key, ['task', 'nonce', 'login-nonce', 'logout-nonce'], true)) {
  428. $redirect .= $uri->params($key);
  429. }
  430. }
  431. return $redirect;
  432. }
  433. /**
  434. * Redirects an action
  435. */
  436. public function redirect()
  437. {
  438. if ($this->redirect) {
  439. $this->grav->redirectLangSafe($this->redirect, $this->redirectCode);
  440. }
  441. }
  442. /**
  443. * Set redirect.
  444. *
  445. * @param $path
  446. * @param int $code
  447. */
  448. public function setRedirect($path, $code = 303)
  449. {
  450. $this->redirect = $path;
  451. $this->redirectCode = $code;
  452. }
  453. /**
  454. * @return array Array containing [redirect, code].
  455. */
  456. public function getRedirect()
  457. {
  458. return [$this->redirect, $this->redirectCode];
  459. }
  460. /**
  461. * Prepare and return POST data.
  462. *
  463. * @param array $post
  464. *
  465. * @return array
  466. */
  467. protected function &getPost(array $post)
  468. {
  469. unset($post[$this->prefix]);
  470. // Decode JSON encoded fields and merge them to data.
  471. if (isset($post['_json'])) {
  472. $post = array_merge_recursive($post, $this->jsonDecode($post['_json']));
  473. unset($post['_json']);
  474. }
  475. return $post;
  476. }
  477. /**
  478. * Recursively JSON decode data.
  479. *
  480. * @param array $data
  481. *
  482. * @return array
  483. */
  484. protected function jsonDecode(array $data)
  485. {
  486. foreach ($data as &$value) {
  487. if (\is_array($value)) {
  488. $value = $this->jsonDecode($value);
  489. } else {
  490. $value = json_decode($value, true);
  491. }
  492. }
  493. return $data;
  494. }
  495. /**
  496. * Gets and sets the RememberMe class
  497. *
  498. * @param mixed $var A rememberMe instance to set
  499. *
  500. * @return RememberMe\RememberMe Returns the current rememberMe instance
  501. * @deprecated 2.5.0 Use $grav['login']->rememberMe() instead
  502. */
  503. public function rememberMe($var = null)
  504. {
  505. return $this->login->rememberMe($var);
  506. }
  507. /**
  508. * Check if user may use password reset functionality.
  509. *
  510. * @param UserInterface $user
  511. * @param $field
  512. * @param $count
  513. * @param $interval
  514. * @return bool
  515. * @deprecated 2.5.0 Use $grav['login']->getRateLimiter($context) instead. See Grav\Plugin\Login\RateLimiter class.
  516. */
  517. protected function isUserRateLimited(UserInterface $user, $field, $count, $interval)
  518. {
  519. return $this->login->isUserRateLimited($user, $field, $count, $interval);
  520. }
  521. /**
  522. * Reset the rate limit counter
  523. *
  524. * @param UserInterface $user
  525. * @param $field
  526. * @deprecated 2.5.0 Use $grav['login']->getRateLimiter($context) instead. See Grav\Plugin\Login\RateLimiter class.
  527. */
  528. protected function resetRateLimit(UserInterface $user, $field)
  529. {
  530. $this->login->resetRateLimit($user, $field);
  531. }
  532. /**
  533. * Authenticate user.
  534. *
  535. * @param array $form Form fields.
  536. *
  537. * @return bool
  538. * @deprecated 2.6.2 Will be removed without replacement.
  539. */
  540. protected function authenticate($form)
  541. {
  542. // Remove login nonce.
  543. $form = array_diff_key($form, ['login-form-nonce' => true]);
  544. return $this->login->login($form, ['remember_me' => true])->authenticated;
  545. }
  546. }