Router.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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;
  9. use Grav\Common\Grav;
  10. use Grav\Common\Processors\ProcessorBase;
  11. use Grav\Framework\Route\Route;
  12. use Grav\Plugin\Admin\Routers\LoginRouter;
  13. use Psr\Http\Message\ResponseInterface;
  14. use Psr\Http\Message\ServerRequestInterface;
  15. use Psr\Http\Server\RequestHandlerInterface;
  16. class Router extends ProcessorBase
  17. {
  18. public $id = 'admin_router';
  19. public $title = 'Admin Panel';
  20. /** @var Admin */
  21. protected $admin;
  22. public function __construct(Grav $container, Admin $admin)
  23. {
  24. parent::__construct($container);
  25. $this->admin = $admin;
  26. }
  27. /**
  28. * Handle routing to the dashboard, group and build objects.
  29. *
  30. * @param ServerRequestInterface $request
  31. * @param RequestHandlerInterface $handler
  32. * @return ResponseInterface
  33. */
  34. public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
  35. {
  36. $this->startTimer();
  37. $context = $request->getAttributes();
  38. $query = $request->getQueryParams();
  39. /** @var Route $route */
  40. $route = $context['route'];
  41. $normalized = mb_strtolower(trim($route->getRoute(), '/'));
  42. $parts = explode('/', $normalized);
  43. array_shift($parts); // Admin path
  44. $routeStr = implode('/', $parts);
  45. $view = array_shift($parts);
  46. $path = implode('/', $parts);
  47. $task = $this->container['task'] ?? $query['task'] ?? null;
  48. $action = $this->container['action'] ?? $query['action'] ?? null;
  49. $params = ['view' => $view, 'route' => $routeStr, 'path' => $path, 'parts' => $parts, 'task' => $task, 'action' => $action];
  50. $request = $request->withAttribute('admin', $params);
  51. // Run login controller if user isn't fully logged in or asks to logout.
  52. $user = $this->admin->user;
  53. if (!$user->authorized || !$user->authorize('admin.login')) {
  54. $params = (new LoginRouter())->matchServerRequest($request);
  55. $request = $request->withAttribute('admin', $params + $request->getAttribute('admin'));
  56. }
  57. $this->admin->request = $request;
  58. $response = $handler->handle($request);
  59. $this->stopTimer();
  60. // Never allow admin pages to be rendered in <frame>, <iframe>, <embed> or <object> for improved security.
  61. return $response->withHeader('X-Frame-Options', 'DENY');
  62. }
  63. }