开发者

How do redirect from Django Authentication backend

We use custom authentication for our django webapp, where we hit the company ldap. Since we're using a custom backend, we seem to only be able to return None, or the username of a user from our db.

d开发者_开发百科ef 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

Clearly there are three different use cases here - one where it works, one where it doesn't because the credentials are invalid, and one where the server is down. Django's custom backend seems to only really handle two of these though - invalid credentials, or working ones. How would I redirect to an error page, or inform the user that ldap is down?


I'd look at raising a custom exception in your auth backend, and catch it in your login view. Returning None from your auth backend simply means "I couldn't authenticate these credentials - try the next backend".

So, in pseudo-code,

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')

In real life, you'd of course use a form to validate some of this - but you get the idea.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜