if (false === $this->get('security.context')->isGranted('ROLE_ADMIN')) { throw new AccessDeniedException(); }
public function indexAction() { if (!$this->get('security.context')->isGranted(new Expression( '"ROLE_ADMIN" in roles or (user and user.isSuperAdmin())' ))) { throw new AccessDeniedException(); } // ... }
Thanks to the SensioFrameworkExtraBundle, you can also secure your controller using annotations:
// ... use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; /** * @Security("has_role('ROLE_ADMIN')") */ public function helloAction($name) { // ... }
public function indexAction() { $user = $this->get('security.context')->getToken()->getUser(); }
In a controller this can be shortcut to:
public function indexAction() { $user = $this->getUser(); }
{# src/Acme/SecurityBundle/Resources/views/Security/login.html.twig #}
{% if error %}
<div>{{ error.message }}</div>
{% endif %}
<form action="{{ path('login_check') }}" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="_username" value="{{ last_username }}" />
<label for="password">Password:</label>
<input type="password" id="password" name="_password" />
{#
If you want to control the URL the user
is redirected to on success (more details below)
<input type="hidden" name="_target_path" value="/account" />
#}
<button type="submit">login</button>
</form>
{% if is_granted('ROLE_ADMIN') %}
<a href="...">Delete</a>
{% endif %}
{% if is_granted(expression(
'"ROLE_ADMIN" in roles or (user and user.isSuperAdmin())'
)) %}
<a href="...">Delete</a>
{% endif %}
{% if app.user %}
<ul>
<li><a href="{{ path('fos_user_profile_show') }}">Профиль</a></li>
<li><a href="{{ path('fos_user_security_logout') }}">Выйти</a></li>
</ul>
{% else %}
<li><a href="{{ path('fos_user_security_login') }}">Логин</a></li>
{% endif %}
<p>Username: {{ app.user.username }}</p>
<p>Full name: {{ app.user.fullname }}</p>