如何从Django认证后端进行重定向
我们在自己的Django网页应用中使用了自定义的身份验证方式,连接的是公司的LDAP系统。因为我们用了自定义的后端,所以似乎只能返回两个结果,要么是None,要么是我们数据库中某个用户的用户名。
def authenticate(self,username,password):
"""
Authenticate the username credentials, and return the
"""
try:
self.ldap.simple_bind_s(username+"@"+settings.AUTH_LDAP_DOMAIN,password)
self.ldap.unbind_s()
except ldap.INVALID_CREDENTIALS:
logger.debug("Invalid credentials used for login.")
username = None
except ldap.SERVER_DOWN, e:
logger.debug("Ldap server is down.")
username = None
return username
这里明显有三种不同的情况:一种是正常工作,另一种是因为凭证无效而不工作,还有一种是服务器宕机了。不过,Django的自定义后端似乎只处理了这两种情况——无效的凭证和有效的凭证。那么,我该如何引导用户到错误页面,或者告诉他们LDAP服务器宕机了呢?
1 个回答
2
我建议你在你的认证后台抛出一个自定义的异常,然后在登录视图中捕获这个异常。从你的认证后台返回None的意思就是“我无法验证这些凭证——请尝试下一个后台”。
所以,用伪代码来说,
class LoginView(TemplateView):
def post(self, request):
try:
user = authenticate(request.POST['username'], request.POST['password'])
except MyCustomLdapError:
return HttpResponseRedirect('ldap_server_unavailable.html')
else:
if user:
return HttpResponseRedirect('logged_in.html')
else:
return HttpResponseRedirect('login_failed.html')
在实际应用中,你当然会使用一个表单来验证其中的一些内容——不过你明白我的意思了。