Skip to content
This repository
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 77 lines (65 sloc) 2.374 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
<?php

/*
* This file is part of the FOSRestBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace FOS\RestBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\EventListener\ExceptionListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;

/**
* This listener handles ensures that for specific formats AccessDeniedExceptions
* will return a 403 regardless of how the firewall is configured
*
* @author Lukas Kahwe Smith <smith@pooteeweet.org>
*/
class AccessDeniedListener extends ExceptionListener
{
    private $formats;

    /**
* Constructor.
*
* @param array $formats key value pairs of format names and if for the given format
* the exception should be intercepted to return a 403
*/
    public function __construct($formats, $controller, LoggerInterface $logger = null)
    {
        $this->formats = $formats;
        parent::__construct($controller, $logger);
    }

    /**
* @param GetResponseForExceptionEvent $event The event
*/
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        static $handling;

        if (true === $handling) {
            return false;
        }

        // TODO do we need to do content type negotiation here?
        if (empty($this->formats[$event->getRequest()->getRequestFormat()])) {
            return false;
        }

        $handling = true;

        $exception = $event->getException();
        if ($exception instanceof AccessDeniedException) {
            $exception = new AccessDeniedHttpException('You do not have the necessary permissions', $exception);
            $event->setException($exception);
            parent::onKernelException($event);
        }
    }

    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::EXCEPTION => array('onKernelException', 5),
        );
    }
}
Something went wrong with that request. Please try again.