Reputation: 424
I have a route that finds user by id. I want to show different content on the profile depending on whether the user is visiting his own profile or another users profile.
The method in the Controller:
/**
* @Route("/u/{id}", name="profile_show")
* @ParamConverter("user", class="UserBundle:User")
* @Template()
*/
public function showAction(User $user)
{
$auth = $this->getUser();
if ($user->getId() == $auth->getId()) {
$auth->addRole('ROLE_PROFILE_OWNER');
}
return array(
'user' => $user
);
}
The output in Twig:
{% if is_granted('ROLE_PROFILE_OWNER') %}
<p>This is my profile</p>
{% else %}
<p>This is not my profile</p>
{% endif %}
The role shows up on the user if I do {{ dump(app.user) }} yet it outputs the text that it is not my profile. Anyone knows why this does not work?
Also I have no clue if this is actually the right way to do things like this. I want to follow best practice so if this is totally wrong please enlighten me.
Thanks for any help.
Upvotes: 0
Views: 586
Reputation: 5280
Credentials check is happening before showAction()
is executed, so the $auth->addRole('ROLE_PROFILE_OWNER');
line never runs. That is why you always get the "this is not your profile" message.
Also, you should not use user roles to do this kind of profile ownership check. Instead just compare the logged-in user's id
(stored in Session) and the profile user_id
. If they are not the same throw an AccessDeniedException()
.
Take a look at the documentation Securing a controller and Session Management pages.
Upvotes: 1