Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access the security context token from the view layer in symfony 2?

Tags:

symfony

If I had a user object stored in the session, I could retrieve the user name in twig using somthing like:

app.session.get('user').UserName

But my user object (UserInterface) resides in the security context, more specifically in the user field of the userToken (TokenInterface) object. How can I access values inside the user object from twig? I am thinking of something along the lines of:

app.security.context.token.user.[my_user_property]
like image 369
Jorge Avatar asked Sep 07 '11 22:09

Jorge


3 Answers

The security context is available from the app global as security:

{{ app.security.getToken().getUser() }}

will output the string representation of your user object (or "anon." if you're not logged in, but are authenticated).

Note that unless you have declared public properties, you'll have to use your getter/setter methods:

{{ app.security.getToken().getUser().getUsername() }}

As a shortcut you can use the set tag to define a user variable in the template:

{% set user = app.security.getToken().getUser() %}

and save yourself a lot of typing, or pass it in from the controller.

like image 124
Derek Stobbe Avatar answered Nov 20 '22 05:11

Derek Stobbe


In our project, we use the app object. It's a Symfony\Bundle\FrameworkBundle\Templating\GlobalVariables

This object has a method getUser to access the user in the security context.

So in your code you can use

{{ app.user.username }} 

to retrieve the user in your views.

like image 36
Reuven Avatar answered Nov 20 '22 05:11

Reuven


Just a note, Twig has a feature where you can check if a user has a given role from the view layer:

{% if is_granted('ROLE_USER') %}
    <a href="...">Delete</a>
{% endif %}
like image 14
mdpatrick Avatar answered Nov 20 '22 04:11

mdpatrick