|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace CodedMonkey\Dirigent\Security; |
| 6 | + |
| 7 | +use Symfony\Component\HttpFoundation\RedirectResponse; |
| 8 | +use Symfony\Component\HttpFoundation\Request; |
| 9 | +use Symfony\Component\HttpFoundation\Response; |
| 10 | +use Symfony\Component\Routing\Generator\UrlGeneratorInterface; |
| 11 | +use Symfony\Component\Security\Core\Exception\AccessDeniedException; |
| 12 | +use Symfony\Component\Security\Http\Authorization\AccessDeniedHandlerInterface; |
| 13 | +use Twig\Environment; |
| 14 | + |
| 15 | +readonly class AccessDeniedHandler implements AccessDeniedHandlerInterface |
| 16 | +{ |
| 17 | + public function __construct( |
| 18 | + private Environment $twig, |
| 19 | + private UrlGeneratorInterface $urlGenerator, |
| 20 | + ) { |
| 21 | + } |
| 22 | + |
| 23 | + public function handle(Request $request, AccessDeniedException $accessDeniedException): ?Response |
| 24 | + { |
| 25 | + if ($request->isXmlHttpRequest()) { |
| 26 | + return new Response( |
| 27 | + json_encode([ |
| 28 | + 'error' => 'Access denied', |
| 29 | + 'message' => 'You do not have permission to access this resource.', |
| 30 | + ]), |
| 31 | + Response::HTTP_FORBIDDEN, |
| 32 | + ['Content-Type' => 'application/json'], |
| 33 | + ); |
| 34 | + } |
| 35 | + |
| 36 | + // If user is not authenticated, redirect to login |
| 37 | + if (!$request->getSession()->has('_security_main')) { |
| 38 | + return new RedirectResponse( |
| 39 | + $this->urlGenerator->generate('dashboard_login', [ |
| 40 | + '_target_path' => $request->getUri(), |
| 41 | + ]) |
| 42 | + ); |
| 43 | + } |
| 44 | + |
| 45 | + // Show access denied error page |
| 46 | + $content = $this->twig->render('dashboard/errors/access_denied.html.twig', [ |
| 47 | + 'exception' => $accessDeniedException, |
| 48 | + ]); |
| 49 | + |
| 50 | + return new Response($content, Response::HTTP_FORBIDDEN); |
| 51 | + } |
| 52 | +} |
0 commit comments