Symfony 2:如何检查用户是否未在模板中登录?

时间:2012-03-12 01:39:52

标签: symfony authentication twig symfony-2.1

在Symfony 2模板中(使用Twig),如何有效地检查用户是否未登录?

我不想使用ROLE支票。我想要一种直接的方法来检查用户是否未登录。

我知道将app.user.usernameanon进行比较有效,但这对我来说感觉不对。

2 个答案:

答案 0 :(得分:186)

您可以检查是否设置了app.user.

 {% if app.user %}
    # user is logged in
 {% else %}
    # user is not logged in
 {% endif %}

答案 1 :(得分:89)

虽然目前的答案回答了OP的问题,但我想补充更多细节。

我理解OP不想检查角色,但我将其包含在内,以便其他SO用户可以在将来复制和粘贴。 - 每次我谷歌这个,我最终来到这里!

Symfony Doc来源:


检查是否有用户登录(无论角色如何)

如上所述,您可以使用app.user检查是否已登录任何用户。

{% if app.user %}
    # user is logged in (any and all users, regardless of ROLE_*)
{% elseif not app.user %}
    # user is not logged in (note the `not` in the `elseif` statement)
{% endif %}

检查身份验证状态

您可以使用is_granted()方法检查ROLES,(以下是symfony分配的所有角色,您可能还拥有自己的角色(详情如下)

{% if is_granted('IS_AUTHENTICATED_FULLY') %}
    # This user entered their credentials THIS session
{% elseif is_granted('IS_AUTHENTICATED_REMEMBERED') %}
    # User logged in via a cookie (ie: Auth again before doing sensitive things)
{% elseif is_granted('IS_AUTHENTICATED_ANONYMOUSLY') %}
    # This is a `guest` or anonymous user
{% endif %}
来自文档的

  

IS_AUTHENTICATED_ANONYMOUSLY - 自动分配给用户   在受防火墙保护的网站部分,但实际上并没有   登录。只有在允许匿名访问的情况下才可以使用。

     

IS_AUTHENTICATED_REMEMBERED - 自动分配给曾经的用户   通过记住我的cookie验证。

     

IS_AUTHENTICATED_FULLY - 自动分配给拥有的用户   在当前会话期间提供了他们的登录详细信息。


检查角色

您还可以使用is_granted()来检查角色 假设我们有3个角色(ROLE_SUPER_ADMINROLE_ADMIN,& ROLE_USER

{% if is_granted('ROLE_SUPER_ADMIN') -%}
    # You're `ROLE_SUPER_ADMIN`
{% elseif is_granted('ROLE_ADMIN') -%}
    # You're `ROLE_ADMIN`
{% elseif is_granted('ROLE_USER') -%}
    # You're `ROLE_USER`
{% else %}
    # You're a `nobody` ;P
{%- endif %}

在控制器内执行上述操作

查看以下答案:How to check if an user is logged in Symfony2 inside a controller?