Login

Authenticate with Email Address

Author:
thom
Posted:
March 29, 2007
Language:
Python
Version:
.96
Tags:
admin user email authenticate ldap
Score:
2 (after 2 ratings)

This code gives you the ability to authenticate a user by their email address instead of the username. I've also added the ability to authenticate via LDAP.

Some code used from this snippet

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import ldap
from django.contrib.auth.models import User
from django.core.validators import email_re

AUTH_LDAP_SERVER = 'xxx.xxx.xxx.xxx'

class Authenticate:
    def authenticate(self, username=None, password=None):
        try:
            user = User.objects.get(email=username)
            if user.check_password(password):
                return user
            else:
                try:
                    l = ldap.open(AUTH_LDAP_SERVER)
                except ldap.LDAPError, e:
                    return None
                
                try:
                    # Attempt to bind to the user's DN
                    l.simple_bind_s(username, password)
                    
                    try:
                        user = User.objects.get(email__exact=username)
                    except:
                        return None
                    
                    # Success.
                    return user
                except ldap.INVALID_CREDENTIALS:
                    return None
        except User.DoesNotExist:
                return None
            
    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

More like this

  1. Use email addresses for user name for django 1.0+ by jasongreen 5 years, 8 months ago
  2. Use email addresses for user name by chris 8 years, 6 months ago
  3. Authentication Against Active Directory (LDAP) over SSL by mary 7 years, 1 month ago
  4. Unusable passwords for LDAP users by rob.ward 6 years, 7 months ago
  5. Email or username authentication with masquerading by petrilli 6 years, 2 months ago

Comments

pihentagy (on September 9, 2008):

Could you update this snippet for django1.0?

thanks

#

Please login first before commenting.