我尝试编写一个login_required装饰器,用于使用WSGI中间件验证对Django中受保护视图的请求。
这是我的代码:
def login_required(f, request_class=HTTPRequest):
def _wrapper(*args, **kwargs):
if not isinstance(args[0], request_class):
req = request_class(environ=args[0])
else:
req = args[0]
wsgi_app = WSGIController()
settings = wsgi_app.settings
google_client = client.GoogleClient(
settings.OAUTH2_CLIENT_ID,
access_token=settings.OAUTH2_ACCESS_TOKEN,
scope='email',
redirect_url=settings.OAUTH2_REDIRECT_URL,
login_path="/session_login/")
wsgi_app = google_client.wsgi_middleware(wsgi_app, \
secret=settings.SECRET_KEY)
def process_middleware(environ, start_response):
return wsgi_app(environ, start_response)
response = process_middleware(req.environ, f)
return f(*args, **kwargs)
return _wrapper
如何处理响应对象(生成器)以将用户重定向到oauth登录页面?
更新:如果我添加以下代码:
redirect = [response.next()中项目的项目
然后我收到以下错误:
TypeError:不可用类型:' list'
答案 0 :(得分:0)
您可以在django/contrib/auth/decoractors.py
当登录检查失败时,它会使用redirect_to_login
函数重定向到登录页面。
from django.contrib.auth.views import redirect_to_login
return redirect_to_login(path, resolved_login_url, redirect_field_name)