djangoauthenticationbackendcustom-backend

Custom Authentication django


I have an app called cAdmin which for company users administration. And have Django superuser for create this company admins , which is stored in User Model as well. I have a custom backend called MyCustomAuthBackend and it only check CompanyAdmin model credentials . But the problems is whenever i try to login using User model credentials also allows . The reason that i foun is if the first backend fails it jumps over to next backend which is ModelBackend. How to stop when the first backend fails to jump to second back end in this specific app cAdmin.

from django.contrib.auth.backends import BaseBackend
from .models import CompanyAdmin
from django.contrib.auth.hashers import make_password,check_password

class MyCustomAuthBackend(BaseBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = CompanyAdmin.objects.get(adminName=username)
            print(user.adminPassword,"      ",make_password(password))
            if check_password(password, user.adminPassword):
                print("worked password", user.adminPassword, password)
                #user.is_authenticated = True
                print(user,"printer duser")
                return user
            
        except CompanyAdmin.DoesNotExist:
            return None 
        return None

and the view is given below,

from django.shortcuts import render,HttpResponse
from django.views.decorators.cache import cache_control
from User.models import TicketDetails,Tickets,Category
from cAdmin.decorators import signin_required
#from cAdmin.backends import authenticate
from django.contrib.auth import authenticate,login,logout

@cache_control(no_cache=True, must_revalidate=True, no_store=True) 
def Login(request,id=None):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        print("login view password")
        user=authenticate(request,username=username,password=password)
        print(user)
        if user:
            print(user)
            login(request,user)
            context = {'LoggedUser': user}
            return render(request,'cAdmin/adminDashboard.html',context) 
        else:
            return render(request, 'cAdmin/index.html',{'flag': 1})

    request.session.flush()
    return render(request, 'cAdmin/index.html',{})

and the order of Backend is given below,

` AUTHENTICATION_BACKENDS = [

 'cAdmin.backends.MyCustomAuthBackend',
 'django.contrib.auth.backends.ModelBackend',

]`

just used a middleware generated by chatGPT that did'nt worked

from django.contrib.auth.backends import ModelBackend

class MyAppAuthMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Check the current app and set the authentication backend accordingly
        if request.path.startswith('/cAdmin/'):
            print("Auth workeeeeeeeeeeeed")
            request.backend = 'cAdmin.backends.MyCustomAuthBackend'
        elif request.path.startswith('/'):

            request.backend = 'django.contrib.auth.backends.ModelBackend'
            print("lhglhflghlfshdglhfdlh")
            

        response = self.get_response(request)
        return response

Solution

  • You can try this

    login in define your custom authentication backend

    from .. import MyCustomAuthBackend
    def Login(request,id=None):
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']
            print("login view password")
            if request.path.startswith('/cAdmin/'): 
                user=authenticate(request,username=username,password=password)
                if user:
                    login(request,user,,backend="django.contrib.auth.backends.ModelBackend")
                    context = {'LoggedUser': user}
                    return render(request,'cAdmin/adminDashboard.html',context) 
            elif request.path.startswith('/'):
                
                email_auth = MyCustomAuthBackend()
                user=email_auth.authenticate(request,username=username,password=password)
                if user:
                    login(request,user,backend="cAdmin.backends.MyCustomAuthBackend")
                    return render(request, 'cAdmin/index.html',{'flag': 1})
    
        request.session.flush()
        return render(request, 'cAdmin/index.html',{})