Custom Authentication Still Requires Login to Admin Site

Viewed 26

I am creating a custom user model with the ability to use a username or email to login. I have created a custom login function and can normally login into the website but it still requires me to login again when I try to access the admin site (even though the user has admin privileges).

Any idea what might be the issue?

User Model

class User(AbstractUser):
    status = models.CharField(max_length=100,blank=True)
    class Meta:
        db_table='auth_user'

Backend

class BothAuthBackend(object):
    def authenticate(self, loginDetail=None, password=None):
        
        try:
            user = UserModel.objects.get(email=loginDetail)
        except:
            user = None

        if user == None:
            try:
                user = UserModel.objects.get(username=loginDetail)
            except:
                user = None

        try:
            if user.check_password(password):
                return user
        except UserModel.DoesNotExist:
            return None

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

View Function

def login(request):

    if request.method == 'GET':
        form = LoginForm2()
        return render(request,'users/login.html',{'form': form})
    
    if request.method == 'POST':
        form = LoginForm2(request.POST)

        if form.is_valid():
            
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = BothAuthBackend.authenticate(request, loginDetail=username, password=password)
            
            if user is not None:  
                return render(request,'users/afterLogin.html')
            else:           
                return render(request, 'users/login.html', {'form': LoginForm2()})
        else:
            form = LoginForm2()
            return render(request,'users/login.html',{'form': form})

Settings

AUTH_USER_MODEL = 'users.User'
AUTHENTICATION_BACKENDS = ['django.contrib.auth.backends.ModelBackend','users.backends.BothAuthBackend']
1 Answers

Found my own solution,

Need to import this in views (and change the view function name)

from django.contrib.auth import login

Then in the view method

if user is not None:         
      login(request,user) 
      return redirect('users:afterLogin')

Also only need the 'users.backends.BothAuthBackend' in the settings file

Related