0
votes

I am working on a project to integrate LDAP authentication in an existing Django app. Using this site and others I have finally been able to configure everything correctly using the django_auth_ldap backend. Including:

AUTH_LDAP_REQUIRE_GROUP = "CN=myGroup,CN=groups [...] " So only users in group "myGroup" can log in.

Everything is configured correctly now in the settings.py and within the user_login view there is just:

...
user = authenticate(username=username, password=password)
if user:
    if user.is_active:
        login(request, user)
        return redirect('index')
    else:
        message = "Your account is disabled."
else:
    message = "Invalid username or password supplied."
...

Now the last step has to be a notification to the user why his login had failed. right now the fail message will always be: "Invalid username or password supplied." This should be either:
- Wrong username/password
- Not in the right group

Something like:

if user:
...
else: 
    if (LDAP auth failed reason == user does not satisfy AUTH_LDAP_REQUIRE_GROUP):
       message = "You are not in the right user group."
    else:
       message = "Invalid username or password supplied."
...


How can I know, in my user_login view the reason for LDAP Authentication failed?


P.S.: in the django_auth_ldap log I DO see "DEBUG Authentication failed for username: user does not satisfy AUTH_LDAP_REQUIRE_GROUP"
But how to know this in the user_login view?

1

1 Answers

0
votes

Okay, to answer my own question. For now I just removed AUTH_LDAP_REQUIRE_GROUP = "CN=myGroup,CN=groups [...] " from my config, and added the following to the views.py:

from django_auth_ldap.backend import populate_user
def populate_user_callback(sender, **kwargs):
    global isLdapUser;
    global isInRightGroup;

    isLdapUser = True;
    if "myGroup" in kwargs["ldap_user"].group_names:
        isInRightGroup = True;

populate_user.connect(populate_user_callback)   

And in the user_login:

    isLdapUser = False;
    isInRightGroup = False;

    user = authenticate(username=username, password=password)

    if (isLdapUser and not isInRightGroup):
        user = None
        message = "User is not in the right AD group."
        ...
        return ...

authenticate() will call the populate_user_callback() function if the ldap backend is used. So I just check for the correct group myself.


Probably there is a cleaner/better answer for this, but this is working for now.