CôteViande
CôteViande

Reputation: 664

Symfony kernel.response listener with authorization checker

I'm setting up a kernel.response event and I want to test whether the user is logged in or not inside it.

Here is my code:

services.yml

app.kernel.modal_injection:
    class: App\UserBundle\EventListener\ModalListener
    tags:
        - { name: kernel.event_listener, event: kernel.response }
    arguments:
        - @security.authorization_checker

ModalListener.php

<?php
namespace App\UserBundle\EventListener;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Authorization\AuthorizationChecker;


class ConnectModalListener implements EventSubscriberInterface
{
    protected $securityChecker;

    public function __construct( AuthorizationChecker $securityChecker )
    {
        $this->securityChecker = $securityChecker;
    }

    public function onKernelResponse( FilterResponseEvent $event )
    {
        $response = $event->getResponse();
        $request = $event->getRequest();

        if ( !$event->isMasterRequest() ) {
            return;
        }
        if ( $request->isXmlHttpRequest() ) {
            return;
        }

        if ( $this->securityChecker->isGranted( 'IS_AUTHENTICATED_REMEMBERED' ) ) {
            return;
        }

        // CODE HERE


    }

    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::RESPONSE => array( 'onKernelResponse', 0 ),
        );
    }
}

My problem is that upon checking if user IS_AUTHENTICATED_REMEMBER I get an error 500 upon serving css and js files on my page (means no js or css on it). Is there a way to charge those? Eventually filter the kernel.response event on those?

Upvotes: 4

Views: 2325

Answers (1)

C&#244;teViande
C&#244;teViande

Reputation: 664

The token was null in the static files, therefore isGranted returned an error 500. So I have to run a check before:

if ( $this->tokenStorage->getToken() !== null
        && $this->securityChecker->isGranted( 'IS_AUTHENTICATED_REMEMBERED' ) ) {
    return;
}

Upvotes: 1

Related Questions