设置所有页面以要求登录吗? [英] Set all pages to require login, globally?
问题描述
我想将未经身份验证的用户的访问重定向到登录页面,然后将登录的用户重定向到最初请求的页面.
I want to redirect access of unauthenticated users to the login page, after which the logged-in user should be redirected to the originally requested page.
根据文档,使用@user_passes_test
装饰器可以轻松实现此目的.但是似乎我不得不装饰每个视图,这太疯狂了,太多了,而且容易出错.
According to documentation, this is easily achieved using the @user_passes_test
decorator. But it seems I'd have to decorate every view, which is crazy, there are too many and it's error-prone.
什么是全局启用此功能的好方法(除了一小部分固定的视图,例如login
)?也就是说,将所有内容默认设置为仅登录+在需要时显式处理匿名查看.
What is a good way to turn on this functionality globally (except for a small fixed set of views, such as login
)? That is, default everything to logged-in-only + handle anonymous viewing explicitly, where needed.
推荐答案
from django.shortcuts import redirect
from django.conf import settings
class LoginRequiredMiddleware:
def __init__(self, get_response):
self.get_response = get_response
self.login_url = settings.LOGIN_URL
self.open_urls = [self.login_url] + \
getattr(settings, 'OPEN_URLS', [])
def __call__(self, request):
if not request.user.is_authenticated \
and not request.path_info in self.open_urls:
return redirect(self.login_url+'?next='+request.path)
return self.get_response(request)
这篇关于设置所有页面以要求登录吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!