LoginRouter.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. /**
  3. * @package Grav\Plugin\Admin
  4. *
  5. * @copyright Copyright (c) 2015 - 2023 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Plugin\Admin\Routers;
  9. use Grav\Plugin\Admin\Admin;
  10. use Grav\Plugin\Admin\Controllers\Login\LoginController;
  11. use Psr\Http\Message\ServerRequestInterface;
  12. class LoginRouter
  13. {
  14. /** @var string[] */
  15. private $taskTemplates = [
  16. 'logout' => 'login',
  17. 'twofa' => 'login',
  18. 'forgot' => 'forgot',
  19. 'reset' => 'reset'
  20. ];
  21. /**
  22. * @param ServerRequestInterface $request
  23. * @return array
  24. */
  25. public function matchServerRequest(ServerRequestInterface $request): array
  26. {
  27. $adminInfo = $request->getAttribute('admin');
  28. $task = $adminInfo['task'];
  29. $class = LoginController::class;
  30. // Special controller for the new sites.
  31. if (!Admin::doAnyUsersExist()) {
  32. $method = $task === 'register' ? 'taskRegister' : 'displayRegister';
  33. return [
  34. 'controller' => [
  35. 'class' => $class,
  36. 'method' => $method,
  37. 'params' => []
  38. ],
  39. 'template' => 'register',
  40. ];
  41. }
  42. $httpMethod = $request->getMethod();
  43. $template = $this->taskTemplates[$task] ?? $adminInfo['view'];
  44. $params = [];
  45. switch ($template) {
  46. case 'forgot':
  47. break;
  48. case 'reset':
  49. $path = $adminInfo['path'];
  50. if (str_starts_with($path, 'u/')) {
  51. // Path is 'u/username/token'
  52. $parts = explode('/', $path, 4);
  53. $user = $parts[1] ?? null;
  54. $token = $parts[2] ?? null;
  55. } else {
  56. // Old path used to be 'task:reset/user:username/token:token'
  57. if ($httpMethod === 'GET' || $httpMethod === 'HEAD') {
  58. $task = null;
  59. }
  60. $route = $request->getAttribute('route');
  61. $user = $route->getGravParam('user');
  62. $token = $route->getGravParam('token');
  63. }
  64. $params = [$user, $token];
  65. break;
  66. default:
  67. $template = 'login';
  68. }
  69. $method = ($task ? 'task' : 'display') . ucfirst($task ?? $template);
  70. if (!method_exists($class, $method)) {
  71. $method = 'displayUnauthorized';
  72. }
  73. return [
  74. 'controller' => [
  75. 'class' => $class,
  76. 'method' => $method,
  77. 'params' => $params
  78. ],
  79. 'template' => $template,
  80. ];
  81. }
  82. }