Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 access user from twig extension service

Tags:

php

twig

symfony

When I inject the security.context in my symfony2 service (twig extension) the following error appears:

Call to a member function getUser() on a non-object .....

class GeninnoShareboardExtension extends \Twig_Extension {
    public function __construct(ContainerInterface $container, SecurityContext $context) {
        $this->doctrine = $container->get('doctrine');
        $this->context = $context;
    }

    public function getUser() {
        return $this->context->getToken()->getUser();
    }

    ........
}

My services.yml looks like this:

services:
  geninno.twig.extension.dashboard:
    class: Geninno\EDSBundle\Twig\Extension\GeninnoShareboardExtension
    arguments:
      container: "@service_container"
      service: "@security.context"
    tags:
     - { name: twig.extension }

A user is logged in and my firewall setup is like this:

access_control:
    - { path: ^/secured/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/secured/create, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/secured/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/, roles: [IS_AUTHENTICATED_FULLY, IS_AUTHENTICATED_REMEMBERED] }
like image 227
Raymen Avatar asked Apr 05 '13 14:04

Raymen


3 Answers

You should try

services:
  geninno.twig.extension.dashboard:
    class: Geninno\EDSBundle\Twig\Extension\GeninnoShareboardExtension
    arguments: [@service_container, @security.context]
    tags:
     - { name: twig.extension }
like image 176
originof Avatar answered Oct 26 '22 23:10

originof


Is the page you are getting the error on behind a firewall? If not then it won't have access to the security token. You will need to put the page behind a firewall and then open it up to unauthenticated users.

something like this should do the trick to open the page up to unauthenticated users, but still have it inside a firewall (security.yml)

access_control:
  - { path: /lost_password, roles: IS_AUTHENTICATED_ANONYMOUSLY}
like image 44
Fred Jiles Avatar answered Oct 26 '22 21:10

Fred Jiles


I solved it by adding an if to my SecurityContext calls. Checking if the GetToken() returned an object (authenticated) or string (anonymous)

if (is_object($this->context->getToken()))
{
    .... // getUser() etc.
}
like image 35
Raymen Avatar answered Oct 26 '22 21:10

Raymen