Login

Custom Auth Backend to use E-Mail in Django

Author:
bsoculd
Posted:
March 30, 2015
Language:
Python
Version:
1.7
Score:
0 (after 0 ratings)

Instead of the default Django User the Auth Model is 'customer' from the usercp App.

User's can use username as a display to the public, without disclosing their login information. This way they can use a forum with their username, which is seen by everyone. The login credentials, however are more privat, since it is the e-mail address. Allowing the user to not disclose any information.

 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
# settings file:
AUTH_USER_MODEL = 'usercp.Customer'
AUTHENTICATION_BACKENDS = ('usercp.backend.MyAuth', )

# backend.py in usercp (APP) folder
from models import Customer
from django.contrib.auth.hashers import check_password

# Taken from http://www.djangorocks.com/tutorials/creating-a-custom-authentication-backend/creating-a-simple-authentication-backend.html
class MyAuth:

    def authenticate(self, email="", password=""):
        try:
            user = Customer.objects.get(email=email)
            if check_password(password, user.password):
                return user
            else:
                return None
        except Customer.DoesNotExist:
            # No user was found, return None - triggers default login failed
            return None

    # Required for your backend to work properly - unchanged in most scenarios
    def get_user(self, user_id):
        try:
            return Customer.objects.get(pk=user_id)
        except Customer.DoesNotExist:
            return None

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.