【问题标题】:How to logout on all browsers if I logout in one browser in Django?如果我在 Django 中注销一个浏览器,如何注销所有浏览器?
【发布时间】:2017-05-02 05:10:13
【问题描述】:

我有一个 Django 应用程序,用户可以使用 Django 的内置身份验证系统登录/注销。我没有在后端使用任何会话概念来为登录用户维护不同的会话。

我在自定义模型中使用单个字段来存储登录/注销状态。

现在,如果任何用户从 2 个不同的浏览器登录,login_state 将为 true。如果用户现在从一个浏览器注销,那么他/她的 login_state 将设置为 False。

让他/她也自动从其他浏览器注销的 Django 方式是什么?我的意思是自动将他/她重定向到所有其他浏览器的登录页面?

PS:即使在其他浏览器上刷新页面后,也不会重定向到登录页面。我在视图上使用 login_required 装饰器,以便可以将流重定向到登录页面。如果用户未经身份验证,我在 settings.py 中使用 LOGIN_URL 重定向到登录页面。

【问题讨论】:

  • 这当然会自行解决,因为您转到下一页,用户的登录状态错误

标签: python django session


【解决方案1】:

我建议覆盖 login_required 装饰器来检查 login_state。如果 login_state 为 true,则正常继续,否则注销用户会话并重定向到登录页面。

请遵循以下代码。我在我的项目中使用它来自定义 login_required 行为。

def custom_user_passes_test(test_func, login_url=None,
                            redirect_field_name=REDIRECT_FIELD_NAME):
    """
    Decorator for views that checks that the user passes the given test,
    redirecting to the log-in page if necessary. The test should be a callable
    that takes the user object and returns True if the user passes.
    """

    def decorator(view_func):
        @wraps(view_func, assigned=available_attrs(view_func))
        def _wrapped_view(request, *args, **kwargs):
            if test_func(request.user):
                #get current login_state and store in variable named login_state
                if login_state:
                    return view_func(request, *args, **kwargs)
                else:
                    return redirect_to_login(path, resolved_login_url,
                                     redirect_field_name)
        return _wrapped_view
    return decorator

def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME,
                   login_url=None):
    """
    Decorator for views that checks that the user is logged in, redirecting
    to the log-in page if necessary.
    """
    actual_decorator = custom_user_passes_test(lambda u: u.is_authenticated(),
                                               login_url=login_url,
                                               redirect_field_name=\
                                               redirect_field_name)
    if function:
        return actual_decorator(function)
    return actual_decorator

【讨论】:

  • 我猜 django 的 auth 应用程序也使用相同的 login_required 方法定义在用户注销时重定向到登录页面。那你为什么要为 login_reqiured 定义自己的定义?
  • 我在用户登录时在会话中存储了一些信息,这是正确运行应用程序所必需的。因此,我检查了每个请求是否对会话数据进行了调整,是否将用户重定向到再次登录。
  • 在您的情况下,您可以检查 login_state。
猜你喜欢
  • 2017-06-05
  • 2012-10-10
  • 1970-01-01
  • 2012-07-15
  • 1970-01-01
  • 2017-01-05
  • 1970-01-01
  • 1970-01-01
  • 2017-12-28
相关资源
最近更新 更多