Router.php 2.4 KB

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