login.php 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237
  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;
  9. use Composer\Autoload\ClassLoader;
  10. use Grav\Common\Data\Data;
  11. use Grav\Common\Debugger;
  12. use Grav\Common\Flex\Types\Users\UserObject;
  13. use Grav\Common\Grav;
  14. use Grav\Common\Language\Language;
  15. use Grav\Common\Page\Interfaces\PageInterface;
  16. use Grav\Common\Page\Page;
  17. use Grav\Common\Page\Pages;
  18. use Grav\Common\Plugin;
  19. use Grav\Common\Twig\Twig;
  20. use Grav\Common\User\Interfaces\UserCollectionInterface;
  21. use Grav\Common\User\Interfaces\UserInterface;
  22. use Grav\Common\Utils;
  23. use Grav\Common\Uri;
  24. use Grav\Events\SessionStartEvent;
  25. use Grav\Framework\Flex\Interfaces\FlexCollectionInterface;
  26. use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
  27. use Grav\Framework\Session\SessionInterface;
  28. use Grav\Plugin\Form\Form;
  29. use Grav\Plugin\Login\Events\UserLoginEvent;
  30. use Grav\Plugin\Login\Login;
  31. use Grav\Plugin\Login\Controller;
  32. use Grav\Plugin\Login\RememberMe\RememberMe;
  33. use RocketTheme\Toolbox\Event\Event;
  34. use RocketTheme\Toolbox\Session\Message;
  35. /**
  36. * Class LoginPlugin
  37. * @package Grav\Plugin\Login
  38. */
  39. class LoginPlugin extends Plugin
  40. {
  41. const TMP_COOKIE_NAME = 'tmp-message';
  42. /** @var string */
  43. protected $route;
  44. /** @var bool */
  45. protected $authenticated = true;
  46. /** @var Login */
  47. protected $login;
  48. /** @var bool */
  49. protected $redirect_to_login;
  50. /**
  51. * @return array
  52. */
  53. public static function getSubscribedEvents()
  54. {
  55. return [
  56. SessionStartEvent::class => ['onSessionStart', 0],
  57. 'onPluginsInitialized' => [['autoload', 100000], ['initializeSession', 10000], ['initializeLogin', 1000]],
  58. 'onTask.login.login' => ['loginController', 0],
  59. 'onTask.login.twofa' => ['loginController', 0],
  60. 'onTask.login.twofa_cancel' => ['loginController', 0],
  61. 'onTask.login.forgot' => ['loginController', 0],
  62. 'onTask.login.logout' => ['loginController', 0],
  63. 'onTask.login.reset' => ['loginController', 0],
  64. 'onTask.login.regenerate2FASecret' => ['loginController', 0],
  65. 'onPagesInitialized' => ['storeReferrerPage', 0],
  66. 'onPageInitialized' => ['authorizePage', 0],
  67. 'onPageFallBackUrl' => ['authorizeFallBackUrl', 0],
  68. 'onTwigTemplatePaths' => ['onTwigTemplatePaths', 0],
  69. 'onTwigSiteVariables' => ['onTwigSiteVariables', -100000],
  70. 'onFormProcessed' => ['onFormProcessed', 0],
  71. 'onUserLoginAuthenticate' => [['userLoginAuthenticateRateLimit', 10003], ['userLoginAuthenticateByRegistration', 10002], ['userLoginAuthenticateByRememberMe', 10001], ['userLoginAuthenticateByEmail', 10000], ['userLoginAuthenticate', 0]],
  72. 'onUserLoginAuthorize' => ['userLoginAuthorize', 0],
  73. 'onUserLoginFailure' => ['userLoginGuest', 0],
  74. 'onUserLoginGuest' => ['userLoginGuest', 0],
  75. 'onUserLogin' => [['userLoginResetRateLimit', 1000], ['userLogin', 0]],
  76. 'onUserLogout' => ['userLogout', 0],
  77. ];
  78. }
  79. /**
  80. * [onPluginsInitialized:100000] Composer autoload.
  81. *
  82. * @return ClassLoader
  83. */
  84. public function autoload() : ClassLoader
  85. {
  86. return require __DIR__ . '/vendor/autoload.php';
  87. }
  88. public function onSessionStart(SessionStartEvent $event)
  89. {
  90. $session = $event->session;
  91. $user = $session->user ?? null;
  92. if ($user && $user->exists() && ($this->config()['session_user_sync'] ?? false)) {
  93. // User is stored into the filesystem.
  94. /** @var UserCollectionInterface $accounts */
  95. $accounts = $this->grav['accounts'];
  96. /** @var UserObject $stored */
  97. if ($accounts instanceof FlexCollectionInterface) {
  98. $stored = $accounts[$user->username];
  99. } else {
  100. // TODO: remove when removing legacy support.
  101. $stored = $accounts->load($user->username);
  102. }
  103. if ($stored && $stored->exists()) {
  104. // User still exists, update user object in the session.
  105. $user->update($stored->jsonSerialize());
  106. } else {
  107. // User doesn't exist anymore, prepare for session invalidation.
  108. $user->state = 'disabled';
  109. }
  110. if ($user->state !== 'enabled') {
  111. // If user isn't enabled, clear all session data and display error.
  112. $session->invalidate()->start();
  113. /** @var Message $messages */
  114. $messages = $this->grav['messages'];
  115. $messages->add($this->grav['language']->translate('PLUGIN_LOGIN.USER_ACCOUNT_DISABLED'), 'error');
  116. }
  117. }
  118. }
  119. /**
  120. * [onPluginsInitialized] Initialize login plugin if path matches.
  121. * @throws \RuntimeException
  122. */
  123. public function initializeSession()
  124. {
  125. // Check to ensure sessions are enabled.
  126. if (!$this->config->get('system.session.enabled')) {
  127. throw new \RuntimeException('The Login plugin requires "system.session" to be enabled');
  128. }
  129. // Define login service.
  130. $this->grav['login'] = static function (Grav $c) {
  131. return new Login($c);
  132. };
  133. // Define current user service.
  134. $this->grav['user'] = static function (Grav $c) {
  135. $session = $c['session'];
  136. if (empty($session->user)) {
  137. // Try remember me login.
  138. $session->user = $c['login']->login(
  139. ['username' => ''],
  140. ['remember_me' => true, 'remember_me_login' => true, 'failureEvent' => 'onUserLoginGuest']
  141. );
  142. }
  143. return $session->user;
  144. };
  145. }
  146. /**
  147. * [onPluginsInitialized] Initialize login plugin if path matches.
  148. * @throws \RuntimeException
  149. */
  150. public function initializeLogin()
  151. {
  152. $this->login = $this->grav['login'];
  153. /** @var Uri $uri */
  154. $uri = $this->grav['uri'];
  155. // Admin has its own login; make sure we're not in admin.
  156. if (!isset($this->grav['admin'])) {
  157. $this->route = $this->config->get('plugins.login.route');
  158. $this->enable([
  159. 'onPagesInitialized' => ['pageVisibility', 0],
  160. ]);
  161. }
  162. $path = $uri->path();
  163. $this->redirect_to_login = $this->config->get('plugins.login.redirect_to_login');
  164. // Register route to login page if it has been set.
  165. if ($this->route && $this->route === $path) {
  166. $this->enable([
  167. 'onPagesInitialized' => ['addLoginPage', 0],
  168. ]);
  169. return;
  170. }
  171. if ($path === $this->config->get('plugins.login.route_forgot')) {
  172. $this->enable([
  173. 'onPagesInitialized' => ['addForgotPage', 0],
  174. ]);
  175. return;
  176. }
  177. if ($path === $this->config->get('plugins.login.route_reset')) {
  178. $this->enable([
  179. 'onPagesInitialized' => ['addResetPage', 0],
  180. ]);
  181. return;
  182. }
  183. if ($path === $this->config->get('plugins.login.route_register')) {
  184. if ($this->config->get('plugins.login.user_registration.enabled')) {
  185. $this->enable([
  186. 'onPagesInitialized' => ['addRegisterPage', 0],
  187. ]);
  188. } else {
  189. throw new \RuntimeException($this->grav['language']->translate('PLUGIN_LOGIN.REGISTRATION_DISABLED'), 404);
  190. }
  191. return;
  192. }
  193. if ($path === $this->config->get('plugins.login.route_activate')) {
  194. $this->enable([
  195. 'onPagesInitialized' => ['handleUserActivation', 0],
  196. ]);
  197. return;
  198. }
  199. if ($path === $this->config->get('plugins.login.route_profile')) {
  200. $this->enable([
  201. 'onPagesInitialized' => ['addProfilePage', 0],
  202. ]);
  203. return;
  204. }
  205. }
  206. /**
  207. * Optional ability to dynamically set visibility based on page access and page header
  208. * that states `login.visibility_requires_access: true`
  209. *
  210. * Note that this setting may be slow on large sites as it loads all pages into memory for each page load!
  211. *
  212. * @param Event $e
  213. */
  214. public function pageVisibility(Event $e)
  215. {
  216. if ($this->config->get('plugins.login.dynamic_page_visibility')) {
  217. /** @var Pages $pages */
  218. $pages = $e['pages'];
  219. $user = $this->grav['user'];
  220. foreach ($pages->instances() as $page) {
  221. if ($page) {
  222. $header = $page->header();
  223. if ($header && isset($header->access) && isset($header->login['visibility_requires_access']) && $header->login['visibility_requires_access'] === true) {
  224. $config = $this->mergeConfig($page);
  225. $access = $this->login->isUserAuthorizedForPage($user, $page, $config);
  226. if ($access === false) {
  227. $page->visible(false);
  228. }
  229. }
  230. }
  231. }
  232. }
  233. }
  234. /**
  235. * [onPagesInitialized]
  236. */
  237. public function storeReferrerPage()
  238. {
  239. $invalid_redirect_routes = [
  240. $this->config->get('plugins.login.route') ?: '/login',
  241. $this->config->get('plugins.login.route_register') ?: '/register',
  242. $this->config->get('plugins.login.route_activate') ?: '/activate_user',
  243. $this->config->get('plugins.login.route_forgot') ?: '/forgot_password',
  244. $this->config->get('plugins.login.route_reset') ?: '/reset_password',
  245. ];
  246. /** @var Uri $uri */
  247. $uri = $this->grav['uri'];
  248. $current_route = $uri->route();
  249. $redirect = static::defaultRedirectAfterLogin();
  250. if (!$redirect && !in_array($current_route, $invalid_redirect_routes, true)) {
  251. // No login redirect set in the configuration; can we redirect to the current page?
  252. $allowed = true;
  253. /** @var PageInterface $page */
  254. $page = $this->grav['pages']->dispatch($current_route);
  255. if ($page) {
  256. $header = $page->header();
  257. if (isset($header->login_redirect_here) && $header->login_redirect_here === false) {
  258. $allowed = false;
  259. }
  260. if ($allowed && $page->routable()) {
  261. $redirect = $page->route();
  262. foreach ($uri->params(null, true) as $key => $value) {
  263. if (!in_array($key, ['task', 'nonce', 'login-nonce', 'logout-nonce'], true)) {
  264. $redirect .= $uri->params($key);
  265. }
  266. }
  267. }
  268. }
  269. } else {
  270. $redirect = $this->grav['session']->redirect_after_login;
  271. }
  272. $this->grav['session']->redirect_after_login = $redirect;
  273. }
  274. /**
  275. * Add Login page
  276. * @throws \Exception
  277. */
  278. public function addLoginPage()
  279. {
  280. /** @var Pages $pages */
  281. $pages = $this->grav['pages'];
  282. $page = $pages->dispatch($this->route);
  283. if (!$page) {
  284. // Only add login page if it hasn't already been defined.
  285. $page = new Page();
  286. $page->init(new \SplFileInfo(__DIR__ . '/pages/login.md'));
  287. $page->slug(basename($this->route));
  288. $pages->addPage($page, $this->route);
  289. }
  290. }
  291. /**
  292. * Add Login page
  293. * @throws \Exception
  294. */
  295. public function addForgotPage()
  296. {
  297. $route = $this->config->get('plugins.login.route_forgot');
  298. /** @var Pages $pages */
  299. $pages = $this->grav['pages'];
  300. $page = $pages->dispatch($route);
  301. if (!$page) {
  302. // Only add forgot page if it hasn't already been defined.
  303. $page = new Page();
  304. $page->init(new \SplFileInfo(__DIR__ . '/pages/forgot.md'));
  305. $page->slug(basename($route));
  306. $pages->addPage($page, $route);
  307. }
  308. }
  309. /**
  310. * Add Reset page
  311. * @throws \Exception
  312. */
  313. public function addResetPage()
  314. {
  315. $route = $this->config->get('plugins.login.route_reset');
  316. $uri = $this->grav['uri'];
  317. $token = $uri->param('token');
  318. $user = $uri->param('user');
  319. if (!$user || !$token) {
  320. return;
  321. }
  322. /** @var Pages $pages */
  323. $pages = $this->grav['pages'];
  324. $page = $pages->dispatch($route);
  325. if (!$page) {
  326. // Only add login page if it hasn't already been defined.
  327. $page = new Page();
  328. $page->init(new \SplFileInfo(__DIR__ . '/pages/reset.md'));
  329. $page->slug(basename($route));
  330. $pages->addPage($page, $route);
  331. }
  332. }
  333. /**
  334. * Add Register page
  335. * @throws \Exception
  336. */
  337. public function addRegisterPage()
  338. {
  339. $route = $this->config->get('plugins.login.route_register');
  340. /** @var Pages $pages */
  341. $pages = $this->grav['pages'];
  342. $page = $pages->dispatch($route);
  343. if (!$page) {
  344. $page = new Page();
  345. $page->init(new \SplFileInfo(__DIR__ . '/pages/register.md'));
  346. $page->slug(basename($route));
  347. $pages->addPage($page, $route);
  348. }
  349. }
  350. /**
  351. * Handle user activation
  352. * @throws \RuntimeException
  353. */
  354. public function handleUserActivation()
  355. {
  356. /** @var Uri $uri */
  357. $uri = $this->grav['uri'];
  358. /** @var Message $messages */
  359. $messages = $this->grav['messages'];
  360. /** @var UserCollectionInterface $users */
  361. $users = $this->grav['accounts'];
  362. $username = $uri->param('username');
  363. $token = $uri->param('token');
  364. $user = $users->load($username);
  365. $redirect_route = $this->config->get('plugins.login.user_registration.redirect_after_activation');
  366. $redirect_code = null;
  367. if (empty($user->activation_token)) {
  368. $message = $this->grav['language']->translate('PLUGIN_LOGIN.INVALID_REQUEST');
  369. $messages->add($message, 'error');
  370. } else {
  371. [$good_token, $expire] = explode('::', $user->activation_token, 2);
  372. if ($good_token === $token) {
  373. if (time() > $expire) {
  374. $message = $this->grav['language']->translate('PLUGIN_LOGIN.ACTIVATION_LINK_EXPIRED');
  375. $messages->add($message, 'error');
  376. } else {
  377. if ($this->config->get('plugins.login.user_registration.options.manually_enable', false)) {
  378. $message = $this->grav['language']->translate('PLUGIN_LOGIN.USER_ACTIVATED_SUCCESSFULLY_NOT_ENABLED');
  379. } else {
  380. $user['state'] = 'enabled';
  381. $message = $this->grav['language']->translate('PLUGIN_LOGIN.USER_ACTIVATED_SUCCESSFULLY');
  382. }
  383. $messages->add($message, 'info');
  384. unset($user->activation_token);
  385. $user->save();
  386. if ($this->config->get('plugins.login.user_registration.options.send_welcome_email', false)) {
  387. $this->login->sendWelcomeEmail($user);
  388. }
  389. if ($this->config->get('plugins.login.user_registration.options.send_notification_email', false)) {
  390. $this->login->sendNotificationEmail($user);
  391. }
  392. if ($this->config->get('plugins.login.user_registration.options.login_after_registration', false)) {
  393. $loginEvent = $this->login->login(['username' => $username], ['after_registration' => true], ['user' => $user, 'return_event' => true]);
  394. // If there's no activation redirect, get one from login.
  395. if (!$redirect_route) {
  396. $message = $loginEvent->getMessage();
  397. if ($message) {
  398. $messages->add($message, $loginEvent->getMessageType());
  399. }
  400. $redirect_route = $loginEvent->getRedirect();
  401. $redirect_code = $loginEvent->getRedirectCode();
  402. }
  403. }
  404. $this->grav->fireEvent('onUserActivated', new Event(['user' => $user]));
  405. }
  406. } else {
  407. $message = $this->grav['language']->translate('PLUGIN_LOGIN.INVALID_REQUEST');
  408. $messages->add($message, 'error');
  409. }
  410. }
  411. $this->grav->redirectLangSafe($redirect_route ?: '/', $redirect_code);
  412. }
  413. /**
  414. * Add Profile page
  415. */
  416. public function addProfilePage()
  417. {
  418. $route = $this->config->get('plugins.login.route_profile');
  419. /** @var Pages $pages */
  420. $pages = $this->grav['pages'];
  421. $page = $pages->dispatch($route);
  422. if (!$page) {
  423. // Only add forgot page if it hasn't already been defined.
  424. $page = new Page();
  425. $page->init(new \SplFileInfo(__DIR__ . '/pages/profile.md'));
  426. $page->slug(basename($route));
  427. $pages->addPage($page, $route);
  428. }
  429. $this->storeReferrerPage();
  430. }
  431. /**
  432. * Set Unauthorized page
  433. * @throws \Exception
  434. */
  435. public function setUnauthorizedPage()
  436. {
  437. $route = $this->config->get('plugins.login.route_unauthorized');
  438. /** @var Pages $pages */
  439. $pages = $this->grav['pages'];
  440. $page = $pages->dispatch($route);
  441. if (!$page) {
  442. $page = new Page();
  443. $page->init(new \SplFileInfo(__DIR__ . '/pages/unauthorized.md'));
  444. $page->slug(basename($route));
  445. $pages->addPage($page, $route);
  446. }
  447. unset($this->grav['page']);
  448. $this->grav['page'] = $page;
  449. }
  450. /**
  451. * Initialize login controller
  452. */
  453. public function loginController()
  454. {
  455. /** @var Uri $uri */
  456. $uri = $this->grav['uri'];
  457. $task = $_POST['task'] ?? $uri->param('task');
  458. $task = substr($task, \strlen('login.'));
  459. $post = !empty($_POST) ? $_POST : [];
  460. switch ($task) {
  461. case 'login':
  462. if (!isset($post['login-form-nonce']) || !Utils::verifyNonce($post['login-form-nonce'], 'login-form')) {
  463. $this->grav['messages']->add($this->grav['language']->translate('PLUGIN_LOGIN.ACCESS_DENIED'),
  464. 'info');
  465. $twig = $this->grav['twig'];
  466. $twig->twig_vars['notAuthorized'] = true;
  467. return;
  468. }
  469. break;
  470. case 'forgot':
  471. if (!isset($post['forgot-form-nonce']) || !Utils::verifyNonce($post['forgot-form-nonce'], 'forgot-form')) {
  472. $this->grav['messages']->add($this->grav['language']->translate('PLUGIN_LOGIN.ACCESS_DENIED'),'info');
  473. return;
  474. }
  475. break;
  476. }
  477. $controller = new Controller($this->grav, $task, $post);
  478. $controller->execute();
  479. $controller->redirect();
  480. }
  481. /**
  482. * Authorize the Page fallback url (page media accessed through the page route)
  483. */
  484. public function authorizeFallBackUrl()
  485. {
  486. if ($this->config->get('plugins.login.protect_protected_page_media', false)) {
  487. $page_url = \dirname($this->grav['uri']->path());
  488. $page = $this->grav['pages']->find($page_url);
  489. unset($this->grav['page']);
  490. $this->grav['page'] = $page;
  491. $this->authorizePage();
  492. }
  493. }
  494. /**
  495. * [onPageInitialized] Authorize Page
  496. */
  497. public function authorizePage()
  498. {
  499. if (!$this->authenticated) {
  500. return;
  501. }
  502. /** @var UserInterface $user */
  503. $user = $this->grav['user'];
  504. /** @var PageInterface $page */
  505. $page = $this->grav['page'];
  506. if (!$page || $this->grav['login']->isUserAuthorizedForPage($user, $page, $this->mergeConfig($page))) {
  507. return;
  508. }
  509. // If this is not an HTML page request, simply throw a 403 error
  510. $uri_extension = $this->grav['uri']->extension('html');
  511. $supported_types = $this->config->get('media.types');
  512. if ($uri_extension !== 'html' && array_key_exists($uri_extension, $supported_types)) {
  513. header('HTTP/1.0 403 Forbidden');
  514. exit;
  515. }
  516. $authorized = $user->authenticated && $user->authorized;
  517. // User is not logged in; redirect to login page.
  518. if ($this->redirect_to_login && $this->route && !$authorized) {
  519. $this->grav->redirectLangSafe($this->route, 302);
  520. }
  521. /** @var Twig $twig */
  522. $twig = $this->grav['twig'];
  523. $login_page = null;
  524. // Reset page with login page.
  525. if (!$authorized) {
  526. if ($this->route) {
  527. $login_page = $this->grav['pages']->dispatch($this->route);
  528. }
  529. if (!$login_page) {
  530. $login_page = new Page();
  531. // Get the admin Login page is needed, else the default
  532. if ($this->isAdmin()) {
  533. $login_file = $this->grav['locator']->findResource('plugins://admin/pages/admin/login.md');
  534. $login_page->init(new \SplFileInfo($login_file));
  535. } else {
  536. $login_page->init(new \SplFileInfo(__DIR__ . '/pages/login.md'));
  537. }
  538. $login_page->slug(basename($this->route));
  539. /** @var Pages $pages */
  540. $pages = $this->grav['pages'];
  541. $pages->addPage($login_page, $this->route);
  542. }
  543. $this->authenticated = false;
  544. unset($this->grav['page']);
  545. $this->grav['page'] = $login_page;
  546. $twig->twig_vars['form'] = new Form($login_page);
  547. } else {
  548. /** @var Language $l */
  549. $l = $this->grav['language'];
  550. $this->grav['messages']->add($l->translate('PLUGIN_LOGIN.ACCESS_DENIED'), 'error');
  551. $twig->twig_vars['notAuthorized'] = true;
  552. $this->setUnauthorizedPage();
  553. }
  554. }
  555. /**
  556. * [onTwigTemplatePaths] Add twig paths to plugin templates.
  557. */
  558. public function onTwigTemplatePaths()
  559. {
  560. $twig = $this->grav['twig'];
  561. $twig->twig_paths[] = __DIR__ . '/templates';
  562. }
  563. /**
  564. * [onTwigSiteVariables] Set all twig variables for generating output.
  565. */
  566. public function onTwigSiteVariables()
  567. {
  568. /** @var Twig $twig */
  569. $twig = $this->grav['twig'];
  570. $this->grav->fireEvent('onLoginPage');
  571. $extension = $this->grav['uri']->extension();
  572. $extension = $extension ?: 'html';
  573. if (!$this->authenticated) {
  574. $twig->template = "login.{$extension}.twig";
  575. }
  576. // add CSS for frontend if required
  577. if (!$this->isAdmin() && $this->config->get('plugins.login.built_in_css')) {
  578. $this->grav['assets']->add('plugin://login/css/login.css');
  579. }
  580. $task = $this->grav['uri']->param('task') ?: ($_POST['task'] ?? '');
  581. $task = substr($task, \strlen('login.'));
  582. if ($task === 'reset') {
  583. $username = $this->grav['uri']->param('user');
  584. $token = $this->grav['uri']->param('token');
  585. if (!empty($username) && !empty($token)) {
  586. $twig->twig_vars['username'] = $username;
  587. $twig->twig_vars['token'] = $token;
  588. }
  589. } elseif ($task === 'login') {
  590. $twig->twig_vars['username'] = $_POST['username'] ?? '';
  591. }
  592. $flashData = $this->grav['session']->getFlashCookieObject(self::TMP_COOKIE_NAME);
  593. if (isset($flashData->message)) {
  594. $this->grav['messages']->add($flashData->message, $flashData->status);
  595. }
  596. }
  597. /**
  598. * Process the user registration, triggered by a registration form
  599. *
  600. * @param Form $form
  601. * @throws \RuntimeException
  602. */
  603. private function processUserRegistration($form, Event $event)
  604. {
  605. $language = $this->grav['language'];
  606. $messages = $this->grav['messages'];
  607. if (!$this->config->get('plugins.login.enabled')) {
  608. throw new \RuntimeException($language->translate('PLUGIN_LOGIN.PLUGIN_LOGIN_DISABLED'));
  609. }
  610. if (!$this->config->get('plugins.login.user_registration.enabled')) {
  611. throw new \RuntimeException($language->translate('PLUGIN_LOGIN.USER_REGISTRATION_DISABLED'));
  612. }
  613. $form->validate();
  614. /** @var Data $form_data */
  615. $form_data = $form->getData();
  616. /** @var UserCollectionInterface $users */
  617. $users = $this->grav['accounts'];
  618. // Check for existing username
  619. $username = $form_data->get('username');
  620. $existing_username = $users->find($username, ['username']);
  621. if ($existing_username->exists()) {
  622. $this->grav->fireEvent('onFormValidationError', new Event([
  623. 'form' => $form,
  624. 'message' => $language->translate([
  625. 'PLUGIN_LOGIN.USERNAME_NOT_AVAILABLE',
  626. $username
  627. ])
  628. ]));
  629. $event->stopPropagation();
  630. return;
  631. }
  632. // Check for existing email
  633. $email = $form_data->get('email');
  634. $existing_email = $users->find($email, ['email']);
  635. if ($existing_email->exists()) {
  636. $this->grav->fireEvent('onFormValidationError', new Event([
  637. 'form' => $form,
  638. 'message' => $language->translate([
  639. 'PLUGIN_LOGIN.EMAIL_NOT_AVAILABLE',
  640. $email
  641. ])
  642. ]));
  643. $event->stopPropagation();
  644. return;
  645. }
  646. $data = [];
  647. $data['username'] = $username;
  648. // if multiple password fields, check they match and set password field from it
  649. if ($this->config->get('plugins.login.user_registration.options.validate_password1_and_password2',
  650. false)
  651. ) {
  652. if ($form_data->get('password1') !== $form_data->get('password2')) {
  653. $this->grav->fireEvent('onFormValidationError', new Event([
  654. 'form' => $form,
  655. 'message' => $language->translate('PLUGIN_LOGIN.PASSWORDS_DO_NOT_MATCH')
  656. ]));
  657. $event->stopPropagation();
  658. return;
  659. }
  660. $data['password'] = $form_data->get('password1');
  661. }
  662. $fields = (array)$this->config->get('plugins.login.user_registration.fields', []);
  663. foreach ($fields as $field) {
  664. // Process value of field if set in the page process.register_user
  665. $default_values = (array)$this->config->get('plugins.login.user_registration.default_values');
  666. if ($default_values) {
  667. foreach ($default_values as $key => $param) {
  668. if ($key === $field) {
  669. if (\is_array($param)) {
  670. $values = explode(',', $param);
  671. } else {
  672. $values = $param;
  673. }
  674. $data[$field] = $values;
  675. }
  676. }
  677. }
  678. if (!isset($data[$field]) && $form_data->get($field)) {
  679. $data[$field] = $form_data->get($field);
  680. }
  681. }
  682. if ($this->config->get('plugins.login.user_registration.options.set_user_disabled', false)) {
  683. $data['state'] = 'disabled';
  684. } else {
  685. $data['state'] = 'enabled';
  686. }
  687. $data_object = (object) $data;
  688. $this->grav->fireEvent('onUserLoginRegisterData', new Event(['data' => &$data_object]));
  689. $flash = $form->getFlash();
  690. $user = $this->login->register((array)$data_object, $flash->getFilesByFields(true));
  691. if ($user instanceof FlexObjectInterface) {
  692. $flash->clearFiles();
  693. $flash->save();
  694. }
  695. $this->grav->fireEvent('onUserLoginRegisteredUser', new Event(['user' => &$user]));
  696. $fullname = $user->fullname ?? $user->username;
  697. if ($this->config->get('plugins.login.user_registration.options.send_activation_email', false)) {
  698. $this->login->sendActivationEmail($user);
  699. $message = $language->translate(['PLUGIN_LOGIN.ACTIVATION_NOTICE_MSG', $fullname]);
  700. $messages->add($message, 'info');
  701. } else {
  702. if ($this->config->get('plugins.login.user_registration.options.send_welcome_email', false)) {
  703. $this->login->sendWelcomeEmail($user);
  704. }
  705. if ($this->config->get('plugins.login.user_registration.options.send_notification_email', false)) {
  706. $this->login->sendNotificationEmail($user);
  707. }
  708. $message = $language->translate(['PLUGIN_LOGIN.WELCOME_NOTICE_MSG', $fullname]);
  709. $messages->add($message, 'info');
  710. }
  711. $this->grav->fireEvent('onUserLoginRegistered', new Event(['user' => $user]));
  712. $redirect = $this->config->get('plugins.login.user_registration.redirect_after_registration');
  713. $redirect_code = null;
  714. if (isset($user['state']) && $user['state'] === 'enabled' && $this->config->get('plugins.login.user_registration.options.login_after_registration', false)) {
  715. $loginEvent = $this->login->login(['username' => $user->username], ['after_registration' => true], ['user' => $user, 'return_event' => true]);
  716. // If there's no registration redirect, get one from login.
  717. if (!$redirect) {
  718. $message = $loginEvent->getMessage();
  719. if ($message) {
  720. $messages->add($message, $loginEvent->getMessageType());
  721. }
  722. $redirect = $loginEvent->getRedirect();
  723. $redirect_code = $loginEvent->getRedirectCode();
  724. }
  725. }
  726. if ($redirect) {
  727. $event['redirect'] = $redirect;
  728. $event['redirect_code'] = $redirect_code;
  729. }
  730. }
  731. /**
  732. * Save user profile information
  733. *
  734. * @param Form $form
  735. * @param Event $event
  736. * @return bool
  737. */
  738. private function processUserProfile($form, Event $event)
  739. {
  740. /** @var UserInterface $user */
  741. $user = $this->grav['user'];
  742. $language = $this->grav['language'];
  743. $form->validate();
  744. /** @var Data $form_data */
  745. $form_data = $form->getData();
  746. // Don't save if user doesn't exist
  747. if (!$user->exists()) {
  748. $this->grav->fireEvent('onFormValidationError', new Event([
  749. 'form' => $form,
  750. 'message' => $language->translate('PLUGIN_LOGIN.USER_IS_REMOTE_ONLY')
  751. ]));
  752. $event->stopPropagation();
  753. return false;
  754. }
  755. // Stop overloading of username
  756. $username = $form->data('username');
  757. if (isset($username)) {
  758. $this->grav->fireEvent('onFormValidationError', new Event([
  759. 'form' => $form,
  760. 'message' => $language->translate([
  761. 'PLUGIN_LOGIN.USERNAME_NOT_AVAILABLE',
  762. $username
  763. ])
  764. ]));
  765. $event->stopPropagation();
  766. return false;
  767. }
  768. /** @var UserCollectionInterface $users */
  769. $users = $this->grav['accounts'];
  770. // Check for existing email
  771. $email = $form->getData('email');
  772. $existing_email = $users->find($email, ['email']);
  773. if ($user->username !== $existing_email->username && $existing_email->exists()) {
  774. $this->grav->fireEvent('onFormValidationError', new Event([
  775. 'form' => $form,
  776. 'message' => $language->translate([
  777. 'PLUGIN_LOGIN.EMAIL_NOT_AVAILABLE',
  778. $email
  779. ])
  780. ]));
  781. $event->stopPropagation();
  782. return false;
  783. }
  784. $fields = (array)$this->config->get('plugins.login.user_registration.fields', []);
  785. $data = [];
  786. foreach ($fields as $field) {
  787. $data_field = $form_data->get($field);
  788. if (!isset($data[$field]) && isset($data_field)) {
  789. $data[$field] = $form_data->get($field);
  790. }
  791. }
  792. try {
  793. $flash = $form->getFlash();
  794. $user->update($data, $flash->getFilesByFields(true));
  795. $user->save();
  796. if ($user instanceof FlexObjectInterface) {
  797. $flash->clearFiles();
  798. $flash->save();
  799. }
  800. } catch (\Exception $e) {
  801. $form->setMessage($e->getMessage(), 'error');
  802. return false;
  803. }
  804. return true;
  805. }
  806. /**
  807. * [onFormProcessed] Process a registration form. Handles the following actions:
  808. *
  809. * - register_user: registers a user
  810. * - update_user: updates user profile
  811. *
  812. * @param Event $event
  813. * @throws \RuntimeException
  814. */
  815. public function onFormProcessed(Event $event)
  816. {
  817. $form = $event['form'];
  818. $action = $event['action'];
  819. switch ($action) {
  820. case 'register_user':
  821. $this->processUserRegistration($form, $event);
  822. break;
  823. case 'update_user':
  824. $this->processUserProfile($form, $event);
  825. break;
  826. }
  827. }
  828. /**
  829. * @param UserLoginEvent $event
  830. * @throws \RuntimeException
  831. */
  832. public function userLoginAuthenticateRateLimit(UserLoginEvent $event)
  833. {
  834. // Check that we're logging in with rate limit turned on.
  835. if (!$event->getOption('rate_limit')) {
  836. return;
  837. }
  838. $credentials = $event->getCredentials();
  839. $username = $credentials['username'];
  840. // Check rate limit for both IP and user, but allow each IP a single try even if user is already rate limited.
  841. if ($interval = $this->login->checkLoginRateLimit($username)) {
  842. /** @var Language $t */
  843. $t = $this->grav['language'];
  844. $event->setMessage($t->translate(['PLUGIN_LOGIN.TOO_MANY_LOGIN_ATTEMPTS', $interval]), 'error');
  845. $event->setRedirect($this->grav['config']->get('plugins.login.route', '/'));
  846. $event->setStatus(UserLoginEvent::AUTHENTICATION_CANCELLED);
  847. $event->stopPropagation();
  848. }
  849. }
  850. /**
  851. * @param UserLoginEvent $event
  852. * @throws \RuntimeException
  853. */
  854. public function userLoginAuthenticateByRegistration(UserLoginEvent $event)
  855. {
  856. // Check that we're logging in after registration.
  857. if (!$event->getOption('after_registration') || $this->isAdmin()) {
  858. return;
  859. }
  860. $event->setStatus($event::AUTHENTICATION_SUCCESS);
  861. $event->stopPropagation();
  862. }
  863. /**
  864. * @param UserLoginEvent $event
  865. * @throws \RuntimeException
  866. */
  867. public function userLoginAuthenticateByRememberMe(UserLoginEvent $event)
  868. {
  869. // Check that we're logging in with remember me.
  870. if (!$event->getOption('remember_me_login') || !$event->getOption('remember_me') || $this->isAdmin()) {
  871. return;
  872. }
  873. // Only use remember me if user isn't set and feature is enabled.
  874. if ($this->grav['config']->get('plugins.login.rememberme.enabled') && !$event->getUser()->exists()) {
  875. /** @var Debugger $debugger */
  876. $debugger = $this->grav['debugger'];
  877. /** @var RememberMe $rememberMe */
  878. $rememberMe = $this->grav['login']->rememberMe();
  879. $username = $rememberMe->login();
  880. if ($rememberMe->loginTokenWasInvalid()) {
  881. // Token was invalid. We will display error page as this was likely an attack.
  882. $debugger->addMessage('Remember Me: Stolen token!');
  883. throw new \RuntimeException($this->grav['language']->translate('PLUGIN_LOGIN.REMEMBER_ME_STOLEN_COOKIE'), 403);
  884. }
  885. if ($username === false) {
  886. // User has not been remembered, there is no point of continuing.
  887. $debugger->addMessage('Remember Me: No token matched.');
  888. $event->setStatus($event::AUTHENTICATION_FAILURE);
  889. $event->stopPropagation();
  890. return;
  891. }
  892. /** @var UserCollectionInterface $users */
  893. $users = $this->grav['accounts'];
  894. // Allow remember me to work with different login methods.
  895. $user = $users->load($username);
  896. $event->setCredential('username', $username);
  897. $event->setUser($user);
  898. if (!$user->exists()) {
  899. $debugger->addMessage('Remember Me: User does not exist');
  900. $event->setStatus($event::AUTHENTICATION_FAILURE);
  901. $event->stopPropagation();
  902. return;
  903. }
  904. $debugger->addMessage('Remember Me: Authenticated!');
  905. $event->setStatus($event::AUTHENTICATION_SUCCESS);
  906. $event->stopPropagation();
  907. return;
  908. }
  909. }
  910. public function userLoginAuthenticateByEmail(UserLoginEvent $event)
  911. {
  912. if (($username = $event->getCredential('username')) && !$event->getUser()->exists()) {
  913. /** @var UserCollectionInterface $users */
  914. $users = $this->grav['accounts'];
  915. $event->setUser($users->find($username));
  916. }
  917. }
  918. public function userLoginAuthenticate(UserLoginEvent $event)
  919. {
  920. $user = $event->getUser();
  921. $credentials = $event->getCredentials();
  922. if (!$user->exists()) {
  923. // Never let non-existing users to pass the authentication.
  924. // Higher level plugins may override this behavior by stopping propagation.
  925. $event->setStatus($event::AUTHENTICATION_FAILURE);
  926. $event->stopPropagation();
  927. return;
  928. }
  929. // Never let empty password to pass the authentication.
  930. // Higher level plugins may override this behavior by stopping propagation.
  931. if (empty($credentials['password'])) {
  932. $event->setStatus($event::AUTHENTICATION_FAILURE);
  933. $event->stopPropagation();
  934. return;
  935. }
  936. // Try default user authentication. Stop propagation if authentication succeeds.
  937. if ($user->authenticate($credentials['password'])) {
  938. $event->setStatus($event::AUTHENTICATION_SUCCESS);
  939. $event->stopPropagation();
  940. return;
  941. }
  942. // If authentication status is undefined, lower level event handlers may still be able to authenticate user.
  943. }
  944. public function userLoginAuthorize(UserLoginEvent $event)
  945. {
  946. // Always block access if authorize defaulting to site.login fails.
  947. $user = $event->getUser();
  948. foreach ($event->getAuthorize() as $authorize) {
  949. if (!$user->authorize($authorize)) {
  950. if ($user->state !== 'enabled') {
  951. $event->setMessage($this->grav['language']->translate('PLUGIN_LOGIN.USER_ACCOUNT_DISABLED'), 'error');
  952. }
  953. $event->setStatus($event::AUTHORIZATION_DENIED);
  954. $event->stopPropagation();
  955. return;
  956. }
  957. }
  958. if ($event->getOption('twofa') && $user->twofa_enabled && $user->twofa_secret) {
  959. $event->setStatus($event::AUTHORIZATION_DELAYED);
  960. }
  961. }
  962. public function userLoginGuest(UserLoginEvent $event)
  963. {
  964. /** @var UserCollectionInterface $users */
  965. $users = $this->grav['accounts'];
  966. $user = $users->load('');
  967. $event->setUser($user);
  968. $this->grav['session']->user = $user;
  969. }
  970. public function userLoginResetRateLimit(UserLoginEvent $event)
  971. {
  972. if ($event->getOption('rate_limit')) {
  973. // Reset user rate limit.
  974. $user = $event->getUser();
  975. $this->login->resetLoginRateLimit($user->get('username'));
  976. }
  977. }
  978. public function userLogin(UserLoginEvent $event)
  979. {
  980. /** @var SessionInterface $session */
  981. $session = $this->grav['session'];
  982. // Prevent session fixation if supported.
  983. // TODO: remove method_exists() test when requiring Grav v1.7
  984. if (method_exists($session, 'regenerateId')) {
  985. $session->regenerateId();
  986. }
  987. $session->user = $user = $event->getUser();
  988. if ($event->getOption('remember_me')) {
  989. /** @var Login $login */
  990. $login = $this->grav['login'];
  991. $session->remember_me = (bool)$event->getOption('remember_me_login');
  992. // If the user wants to be remembered, create Rememberme cookie.
  993. $username = $user->get('username');
  994. if ($event->getCredential('rememberme')) {
  995. $login->rememberMe()->createCookie($username);
  996. }
  997. }
  998. }
  999. public function userLogout(UserLoginEvent $event)
  1000. {
  1001. if ($event->getOption('remember_me')) {
  1002. /** @var Login $login */
  1003. $login = $this->grav['login'];
  1004. if (!$login->rememberMe()->login()) {
  1005. $login->rememberMe()->getStorage()->cleanAllTriplets($event->getUser()->get('username'));
  1006. }
  1007. $login->rememberMe()->clearCookie();
  1008. }
  1009. /** @var SessionInterface $session */
  1010. $session = $this->grav['session'];
  1011. // Clear all session data.
  1012. $session->invalidate()->start();
  1013. }
  1014. public static function defaultRedirectAfterLogin()
  1015. {
  1016. $config = Grav::instance()['config'];
  1017. $redirect_after_login = $config->get('plugins.login.redirect_after_login');
  1018. $route_after_login = $config->get('plugins.login.route_after_login');
  1019. return is_bool($redirect_after_login) && $redirect_after_login == true ? $route_after_login : $redirect_after_login;
  1020. }
  1021. public static function defaultRedirectAfterLogout()
  1022. {
  1023. $config = Grav::instance()['config'];
  1024. $redirect_after_logout = $config->get('plugins.logout.redirect_after_logout');
  1025. $route_after_logout = $config->get('plugins.logout.route_after_logout');
  1026. return is_bool($redirect_after_logout) && $redirect_after_logout == true ? $route_after_logout : $redirect_after_logout;
  1027. }
  1028. }