如何使用带有嵌入式Dash的Flask-Login实现角色

时间:2019-12-27 22:00:14

标签: python flask plotly-dash

我用烧瓶写了网站,并在其中嵌入了Dash。全部在应用工厂注册。出于安全原因,我使用Flask-Login。我使用这个example。一切正常,直到我决定使用这些角色。我知道Flask_Login没有角色选项。在带有装饰器的基于烧瓶的页面中,有些技巧非常有效。我只有两组用户:完全访问权限/受限用户:

if current_user.roles != 'full_access':
    return redirect(url_for('main_bp.main'))

但是在Dash方面该怎么做。在注册功能中,我使用dashapp.server.view_functions。 我有几个带有仪表板的页面,它将传递给此功能:

def _protect_dashviews(dashapp):
    for view_func in dashapp.server.view_functions:
        if view_func.startswith(dashapp.config.url_base_pathname):
            dashapp.server.view_functions[view_func]= 
                                            login_required(dashapp.server.view_functions[view_func])

但是现在如何像在基于烧瓶的页面中那样告诉这个功能

 if current_user.roles != 'full_access':
     do_something

1 个答案:

答案 0 :(得分:0)

好的,我没有找到如何直接将角色实现到其中。

login_required(dashapp.server.view_functions[view_func])

我快速的解决方案非常简单。我在@ dashapp.callback之后插入了验证语句。我对多角色支持做了一些调整,对于像我这样的简单案例可以解决角色问题。

def register_callbacks(dashapp):
    @dashapp.callback(Output('graph', 'figure'),
    ......
    def update_figure(selected_year, selected_dep):
        user_right = current_user.roles.split() #the list from the string of rights in sqlite.
        dash_right = ['full_access', 'right1'] #which right of user could access the dash
    if not any(x in dash_right for x in user_right):
        print('forbidden')
    else:
        print('contruct the figure')