为我们创建只有授权路由的索引页

2024-04-26 04:09:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个包含两个角色(用户和管理员)的仪表板。我有一个名为requires_admin的装饰器,它阻止简单用户访问页面。你知道吗

我的问题是,我有一个索引页列出了所有的路由,我只想显示允许这个特定用户的路由。你知道吗

这意味着我想知道哪些路由有requires_admin装饰器,哪些没有

这有可能吗?你知道吗


Tags: 用户角色路由admin管理员仪表板装饰页面
1条回答
网友
1楼 · 发布于 2024-04-26 04:09:01

如果您希望使用自定义角色,那么当有人登录时,您可以像这样保存他们的详细信息,包括他们在会话中的角色

from flask import session as login_session
login_session['user_role'] = user.role #assuming you have queried your user object whose attributes include role

然后在呈现模板时,可以传递用户角色

user_role  = login_session['user_role']
return render_template('index.html', user_role= user_role)

然后在模板中(我只是使用一个链接,但可以将整个div括起来)

{% if user_role == 'admin'%}
<a href ="/secretdash">Dashboard</a>
{%endif%}

但我强烈建议您使用flask security(或者按照flask security中的模块之一flask principle中的建议)。使用flask security/flask原理,您可以执行以下操作

1)仅针对登录用户的链接

{% if current_user.is_authenticated %}
 <li> <a href="/firstdashboard"> Dashboard </a> </li>
{% endif %}

2)仅具有特定角色的用户的链接

{% if current_user.has_role('admin') %}
<li><a href="/secretdash">Secret Dash</a></li>
{% endif %}

相关问题 更多 >