Under security.yml I added new role called ROLE_PUBLISHER
access_control:
- { path: ^/publisher/, roles: [ ROLE_PUBLISHER ] }
role_hierarchy:
ROLE_TC_ADMIN: [ ROLE_ALLOWED_TO_SWITCH ]
ROLE_PUBLISHER: [ ROLE_PUBLISHER_UNCONFIRMED ]
Role works fine, it is used on production env, but I just noticed that I cannot check in twig if logged user has correct role.
This one works fine, I am getting 'user' word
{% if is_granted('ROLE_USER') %}'user'{% else %}''{% endif %}
This one does not work (always empty string), even I am logged in as publisher
{% if is_granted('ROLE_PUBLISHER') %}'publisher'{% else %}''{% endif %}
Is it possible that user has two roles ROLE_USER and ROLE_PUBLISHER and twig always checking the first one?
Yep I had right, user has two roles, and twig has been checking the first one. So the solution is:
{% set user_role = '' %}
{% for user in app.user.roles %}
{% if user == 'ROLE_PUBLISHER' %}
{% set user_role = 'publisher' %}
{% endif %}
{% endfor %}
Related
In Symfony 4, I have a couple of different roles. I have a view in Twig which shows a user list. Users can have multiple roles. In the list, I want to show some text if a user has a role "MANAGER". Showing all roles is done with:
{% for role in user.roles %}
{{ role }}
{% endfor %}
Now if the user has the role "MANAGER" I want to show some text. I tried:
{% for role in user.roles %}
{% if (role is "MANAGER") %}
Show some text.
{% endif %}
{% endfor %}
but this returns the error
Unexpected token "string" of value "MANAGER" ("name" expected).
Same error is shown when I use {% if is "MANAGER") %} and when I use {% if "MANAGER") %} for some reason Show some text. is shown for every role the user has, no matter which role that is. What am I doing wrong?
As an answer to your self posted answer: a single role is not an array, the containment operator (see https://twig.symfony.com/doc/2.x/templates.html#containment-operator) supports checks for substrings as well, that's what happening here.
So you check works, but might have false-positives if you have for example a role "MINI_MANAGER", e.g.
{% set role = "MINI_MANAGER" %}
{% if "MANAGER" in role %}
Some text here.
{% endif %}
will also output "Some text here.". So the better solution would be:
{% for role in user.roles %}
{% if role == "MANAGER" %}
Some text here.
{% endif %}
{% endfor %}
This could still lead to problems when role is the boolean value "true" (that is not a Twig problem, but normal PHP behavior), so you can also have a look into the "same as" test, see https://twig.symfony.com/doc/2.x/tests/sameas.html
{% for role in user.roles %}
{% if role is same as("MANAGER") %}
Some text here.
{% endif %}
{% endfor %}
So it seems I have figured it out. It seems every single role is in fact an array, so you have to check for the value within the array like this:
{% for role in user.roles %}
{% if "MANAGER" in role %}
Some text here.
{% endif %}
{% endfor %}
I am still not sure why a single role is an array though, but there surely is a reason for that.
What about this?
{% if is_granted('ROLE_MANAGER') %}
Some text here
{% endif %}
Source: Symfony2 security functions in Twig? How to check the user's role?
See also Symfony Doc
Roles: When a user logs in, they receive a set of roles (e.g.
ROLE_ADMIN).
I am having these 3 role's
1. ROLE_ADMIN
2. ROLE_SAMPLE
3. ROLE_USER
This My twig file
{% if is_granted('ROLE_ADMIN') %}
Delete
{% endif %}
i need to show the delete link for ROLE_ADMIN and also ROLE_SAMPLE
how do i get it????
above code is to show the delete link for only ROLE_ADMIN
how to add one more role(ROLE_SAMPLE) in that???
see this link: Symfony2 and Twig sidebar
{% if is_granted('ROLE_ADMIN') or is_granted('ROLE_SAMPLE') %}
Delete
{% endif %}
At least as of Symfony 3.2.8 you can use an array to list roles. So this should work:
{% if is_granted(['ROLE_ADMIN', 'ROLE_SAMPLE']) %}
Delete
{% endif %}
I don't know when this was added, but I prefer it to using multiple calls with or.
I want to display something like that:
Case 1: "logged in as USER"
# UserName [ logout ]
No problems here, i just do:
# {{ app.user.username}} [ logout ]
Case 2: "logged in as ADMIN"
# AdminName [ logout ]
The same works here:
# {{ app.user.username}} [ logout ]
Case 3: "logged in as ADMIN impersonating a USER"
AdminName # UserName [ return ]
Now thats a problem:
{{ ??..what here..?? }} # {{ app.user.username}} [ return ]
This is the only solution I know... it seems a lot of code for a sipmle displaying username :/
{# iterating through user roles to find ROLE_PREVIOUS_ADMIN #}
{% for role in app.security.token.roles %}
{% if role.source is defined %}
{{ role.source.user.username }}
{% endif %}
{% endfor %}
# {{ app.user.username }} [ return ]
Is there any other way? I need a pure TWIG solution -> this is supposed to be part of my main twig template (that is extended by all other templates) -> I can't add controller code to all actions, just to display username.
With the idea you have proposed above,.. can you not just create a custom twig extension that encompasses your logic from your twig template so that you can just call myCustomTwigFunction within your twig template and it will output the original users name?
See http://symfony.com/doc/current/cookbook/templating/twig_extension.html for more info about custom twig extensions
The code you'd have in your Twig extension file would be...
$roles = $this->container->get('security.context')->getToken()->getRoles();
foreach ($roles as $role) {
if (method_exists($role, 'getSource')) {
return ($role->getSource()->getUser()->getUsername());
}
}
Where $container is a class variable of the DI Container on your twig extension class
For anyone looking for a solution for Symfony 4.3/4.4/5.0:
{% if is_granted('ROLE_PREVIOUS_ADMIN') %}
{% for role in app.token.roles %}
{% if role.role == 'ROLE_PREVIOUS_ADMIN' %}
Admin username is {{ role.source.user.username }}
{% endif %}
{% endfor %}
{% endif %}
From Symfony 5.1 onwards, use IS_IMPERSONATOR in place of ROLE_PREVIOUS_ADMIN.
I would like to know how can i know if a user is granted when it's not the current user in twig.
I use this code for the current user:
{% if is_granted('ROLE_USER') %}
Delete
{% endif %}
But i would like to be able to do the same thing with ohter users that are not logged in at the moment.
Thank you.
Edit:
In fact i think there isn't a direct way with twig to test role of a user that is not authenticated.
So i did it directly in the twig template, test if a user is admin or not, then set var.
(in my question i was searching how to do in a list of users.)
{% set from_user_is_admin = false %}
{% for role in from_user.getRoles() %}
{% if role == 'ROLE_ADMIN' %}{% set from_user_admin = true %}{% endif %}
{% if role == 'ROLE_SUPER_ADMIN' %}{% set from_user_admin = true %}{% endif %}
{% endfor %}
{% if from_user_admin == false %}THIS USER IS NOT ADMIN{% endif %}
I think it would be much easier if you implemented an isGranted function in the User entity:
Class User implements UserInterface {
...
public function isGranted($role)
{
return in_array($role, $this->getRoles());
}
}
You can now easily check for granted roles in every layer of your application.
In PHP:
$user->isGranted("USER_ADMIN")
Or in Twig:
user.granted("USER_ADMIN")
If you need to check a role for the current user, you can do this in Twig:
app.user.granted("USER_ADMIN")
Note: the variable "app" is globally defined.
Note 2: this code may throw an exception if you use it outside the secured area of your app, since app.user would be NULL.
You can use similar statement to the above with "not" :
{% if not is_granted('ROLE_USER') %}
Delete
{% endif %}
or use else statement:
{% if is_granted('ROLE_USER') %}
Delete
{% else %}
{# something else for guest user, not logged in #}
{% endif %}
You should create either a twig macro, or a twig function.
Creating a macro is very simple, using your code:
{% macro admin_status(from_user) %}
{% set from_user_is_admin = false %}
{% for role in from_user.getRoles() %}
{% if role == 'ROLE_ADMIN' %}{% set from_user_admin = true %}{% endif %}
{% if role == 'ROLE_SUPER_ADMIN' %}{% set from_user_admin = true %}{% endif %}
{% endfor %}
{% if from_user_admin == false %}THIS USER IS NOT ADMIN{% endif %}
{% endmacro %}
You can then use it in the same file as {% _self.admin_status(user) %}. You may also move it to a separate file, and use twig's import tag to gain access to it.
Creating a twig function is a better option, for details see extending twig. It boils down to creating a regular function, that may be called from twig, so code like this becomes possible:
{% if user_is_admin(user) %}
You'll also need to read enabling custom twig extensions.
i did it this way, have this snippet in the global twig file, in my case layout.html.twig
{% set is_admin = false %}
{% if app.security.token.user.roles is iterable %}
{% for role in app.security.token.user.roles %}
{% if role == 'ROLE_ADMIN' or role == 'ROLE_SUPER_ADMIN' %}
{% set is_admin = true %}
{% endif %}
{% endfor %}
{% endif %}
then i can use anywhere
{% if is_admin %}....{% endif %}
In an application built with Symfony2 we want superadmins to be able to impersonate other users. This is easily done by giving the superadmin user the ROLE_ALLOWED_TO_SWITCH role. The switching is implemented with a call to "somewhere?_switch_user=" as suggesed in the reference documentation.
The problem however, is to detect in a template if the current user is actually impersonated so as to print a link to "somewhere?_switch_user=_exit" on the page, thus enabling the impersonating user to return to her real user.
I haven't been using Symfony2 for a while so I'm not sure, but when you switch to another user you gain all roles assigned to that user and one extra role: ROLE_PREVIOUS_ADMIN. So I guess all you need to do is to use voter to check whether such a role is assigned to the current user using voter.
// Twig
{% if is_granted('ROLE_PREVIOUS_ADMIN') %}
EXIT
{% endif %}
// PHP
<?php if ($view['security']->isGranted('ROLE_PREVIOUS_ADMIN')): ?>
EXIT
<?php endif ?>
An example of how to get more details about the impersonator:
use Symfony\Component\Security\Core\Role\SwitchUserRole;
$sec = $this->get('security.context');
if($sec->isGranted('ROLE_PREVIOUS_ADMIN')) {
foreach($sec->getToken()->getRoles() as $role) {
if ($role instanceof SwitchUserRole) {
$admin_user = $role->getSource()->getUser();
}
}
}
You then have admin_user as the original user object. Remember to use the SwitchUserRole.
An example of how to display impersonator in twig:
{% if is_granted('ROLE_PREVIOUS_ADMIN') %}
{% for role in app.security.token.roles %}
{% if role.role == 'ROLE_PREVIOUS_ADMIN' %}
{{ role.source.user.username }}
{% endif %}
{% endfor %}
{% endif %}
If you need to test role from the previous admin user :
Working on Symfony 3.4
{% if is_granted('ROLE_PREVIOUS_ADMIN') %}
{% for role in app.token.roles %}
{% if role.role == 'ROLE_PREVIOUS_ADMIN' %}
{% for role_from_previous in role.source.roles if role_from_previous.role == "ROLE_DELETE" %}
{{ role.source.user.username }} has "ROLE_DELETE"
{% endfor %}
{% endif %}
{% endfor %}
{% endif %}