Le-Hao Nguyen
Le-Hao Nguyen

Reputation: 85

Django authentication with multiple databases

I want to create an App for Customers where every customer has its own DB. So as Login information they need to enter three different fields: customernumber, username, password.

The username and password should do the normal authentication stuff and the customernumber is there to go to the right database user table for authentication i can go to other databases through the using() function.

class CustomAuthBackend(ModelBackend):

def authenticate(self, request, username=None, password=None, **kwargs):
    user = CustomUser.objects.using(request.POST['kundennr']).get(username=username)
    if user.check_password(password) and self.user_can_authenticate(user) :
         try:
            user = CustomUser.objects.using(request.POST['kundennr']).get(username=username)
            return user
         except User.DoesNotExist:
            return None

def get_user(self, user_id):
    try:
        return CustomUser.objects.get(pk=user_id)
    except User.DoesNotExist:
        return None

The authentication function works fine that way the problem i have is the get_user function i guess because the get_user function has no request where i can define which database it should call on. because everytime i call {% if user.is_authenticated %} it goes to the default database and says user is Anonymous. I dont know the right way to solve this problem is my solution just wrong?

Upvotes: 1

Views: 1452

Answers (1)

Le-Hao Nguyen
Le-Hao Nguyen

Reputation: 85

okay after trying some stuff i got a solution which i think works for the first step but i dont know if there are security problems or any other errors if i use it like this

from app.models import CustomUser
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import login as auth_login
from app.middleware import ThreadLocal

class CustomAuthBackend(ModelBackend):

def authenticate(self, request, username=None, password=None, **kwargs):
    user = CustomUser.objects.using(request.POST['kundennr']).get(username=username)
    if user.check_password(password) and self.user_can_authenticate(user) :
         try:
            user = CustomUser.objects.using(request.POST['kundennr']).get(username=username)
            request.session['kundennr']=request.POST['kundennr']
            return user
         except User.DoesNotExist:
            return None

def get_user(self, user_id):
    try:
        request = ThreadLocal.get_current_request()
        return CustomUser.objects.using(request.session['kundennr']).get(pk=user_id)
    except User.DoesNotExist:
        return None

i imported a ThreadLocal.py into middleware so i can get the request object in get_user and when i login i save the customer into a session variable which i call in get_user then is this solution acceptable or are there some risks?

Upvotes: 1

Related Questions