Django authenticate dont work for Custom User

60 views Asked by At

In my django-rest project , I am trying to make a login autentication using knox

But in my views , even when the user exists and I provide the username and password correctly, serializer.is_valid(raise_exception=True) always returns False

I check the validation method for the AuthKnoxSerializer

class AuthTokenSerializer(serializers.Serializer):
...
   def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')

        if username and password:
            user = authenticate(request=self.context.get('request'),
                                username=username, password=password)

When i check in django shell if autenticate is working properly

in django shell

>>>from django.contrib.auth import authenticate
>>>from django.contrib.auth import get_user_model
>>>get_user_model().objects.get(username="CIEMSA",password="225236Cm.")
<MyUser: CIEMSA>
>>>print(authenticate(username="CIEMSA", password="225236Cm."))
None

my settings.py

INSTALLED_APPS = [
     ...
    'api',
    'rest_framework',
    "knox",
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        # 'rest_framework.authentication.BasicAuthentication',
        # 'rest_framework.authentication.SessionAuthentication',
        'knox.auth.TokenAuthentication',
    ]
}
REST_KNOX = {
    'USER_SERIALIZER': 'api.serializers.UserSerializer'
}

AUTH_USER_MODEL = "api.MyUser"

views.py

from rest_framework.authtoken.serializers import AuthTokenSerializer
from knox.views import LoginView as KnoxLoginView

class LoginAPI(KnoxLoginView):
    permission_classes = (permissions.AllowAny,)

    def post(self, request, format=None):
        serializer = AuthTokenSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        login(request, user)
        return super(LoginAPI, self).post(request, format=None)

My models.py

from django.db import models as m
from django.contrib.auth import get_user_model
from django.dispatch import receiver
from django.contrib.auth.models import AbstractUser

class Company(m.Model):
    name = m.CharField(max_length=100)
    phone_number = m.CharField(max_length=20)
    provider = m.CharField(max_length=15,
                                choices=CompanyWhatsappProvider.choices,
                                default=CompanyWhatsappProvider.META)
    account_sid = m.CharField(max_length=512, null=True)
    auth_token = m.TextField(max_length=512, null=True)

    def __str__(self):
        return f'({self.id}) {self.name}, {self.phone_number}'
    

class MyUser(AbstractUser):
    company  = m.OneToOneField(Company, null=True , on_delete=m.CASCADE)

@receiver(post_save, sender=Company)
def list_create(sender, instance=None, created=False, **kwargs):
    if created:
        get_user_model().objects.create(company=instance, username=instance.name, password=instance.password)
    

Any ideas why is not working?

1

There are 1 answers

0
user20223018 On BEST ANSWER

You're not correctly setting the password, try it like this:


@receiver(post_save, sender=Company)
def list_create(sender, instance=None, created=False, **kwargs):
    if created:
        user = get_user_model().objects.create(company=instance, username=instance.name)
        user.set_password(instance.password)

Now my question is, where does instance.password come from, as you shouldn't store passwords as plain text field in your database.