El Sam El Sam - 1 month ago 10
PHP Question

FatalErrorException in RedirectionListener.php line 46: Error: Call to a member function getUser() on a non-object

I'm having a problem with FOSUserBundle.

I have a redirection listener to prevent users from using the app without being logged in, here's the code :

class RedirectionListener
{
/**
* RedirectionListener constructor.
* @param ContainerInterface $container
* @throws \Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException
* @throws \Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException
*/
public function __construct(ContainerInterface $container)
{
$this->router = $container->get('router');
$this->securityTokenStorage = $container->get('security.token_storage');
}

/**
* @param GetResponseEvent $event
* @throws \InvalidArgumentException
*/
public function onKernelRequest(GetResponseEvent $event){

$route = $event->getRequest()->attributes->get('_route');

if($route !== 'fos_user_security_login' &&
$route !== 'fos_user_resetting_reset' &&
$route !== 'fos_user_resetting_request' &&
$route !== 'fos_user_resetting_send_email' &&
$route !== 'fos_user_resetting_check_email' &&
$route !== 'fos_user_change_password' &&
!is_object($this->securityTokenStorage->getToken()->getUser())) //this is line 46
{
$event->setResponse(new RedirectResponse($this->router->generate('fos_user_security_login')));
}
}
}


This is my service :

services:
redirectonListener:
class: Projects\ProjectsBundle\Listener\RedirectionListener
arguments: ['@service_container']
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }


And here's my firewall settings from the FOSUserBundle Docs:

firewalls:
# disables authentication for assets and the profiler, adapt it according to your needs
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false

main:
pattern: ^/
form_login:
provider: fos_userbundle
csrf_token_generator: security.csrf.token_manager
# if you are using Symfony < 2.8, use the following config instead:
# csrf_provider: form.csrf_provider

logout: true
anonymous: true


I'm using Symfony 2.8 version. Can anyone help !

Answer

Did you try to set the access_control in your security.yml?

For example:

security:
    #[...]

    access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
        # and so on, until:
        - { path: ^/restricted, role: ROLE_USER }
        # or:
        - { path: ^/*, role: IS_AUTHENTICATED_ANONYMOUSLY }

Edit: Don't forget to clear cache after changes made.