1

The authenticate() function is returning none for registered users in mySQL db. I am using custom user verification, in which the registeration process works perfectly. I am using Django 3.0 The value of Account.objects.get(username = "uname").password == request.POST['password'] is True

here is my models.py

class AccountManager(BaseUserManager):
    #pass USERNAME_FIELD, REQUIRED_FIELDS 
    def create_user(self, email, username, password=None):
        if not email:
            raise ValueError( "Email Id not entered")

        if not username: 
            raise ValueError("User Name not entered")

        user = self.create_user(
            email = self.normalize_email(email),
            username = username,
        )

        user.set_password(password)    
        user.save(using=self._db)
        return user

    def create_superuser(self, email, username, password):
        user = self.create_user(
            email = self.normalize_email(email),
            password = password,
            username = username,
        )

        user.is_admin = True
        user.is_staff = True
        user.is_superuser = True
        user.save(using = self._db)
        return user


# Create your models here.
class Account(AbstractBaseUser):
    username     = models.CharField(max_length = 50, unique= True)
    email        = models.EmailField(verbose_name = "email", max_length = 50, unique=True)
    #few other fields...

    USERNAME_FIELD = "username"
    REQUIRED_FIELDS = ['email']

    objects = AccountManager()
    # any object from Account.object will return __str__ 
    def __str__(self):
        return self.username

    #give permitions to custom user object
    def has_perm(self, perm, obj=None):    
        return self.is_admin

    def has_module_perms(self, app_label):
        return True

views.py


def register(request):
    context = {}
    if request.POST:
        form = RegistrationForm(request.POST)
        if form.is_valid():
            form.save()
            name = form.cleaned_data.get("username")
            raw_password= form.cleaned_data.get('password1')

            account = authenticate(username = name, password = raw_password)
            login(request, account)
            print(str(account))
            return redirect('../dashboard/')
        else: 
            context['registration_form'] = form
    else:
        form = RegistrationForm()
        context['registration_form'] = form
    return render(request, 'register.html')

def login(request):
        context = {}
        if request.method == "POST":
            form = AuthenticationForm(request.POST)

            if form.is_valid:#returns True
                name = request.POST["username"]
                pswd = request.POST["password"]
                user = authenticate(request, username = name, password = pswd)
                print("user = " + str(user)) #always returns None

                if user:
                    print("valid user " + str(user))
                    login(request, user)
                    print("user is " + str(request.user.is_authenticated))
                    return  redirect("../dashboard/") 
        form = AuthenticationForm()
        context['login_form'] = form
        return render(request, 'login.html', context)

settings.py

AUTH_USER_MODEL = "authenticate.Account"
AUTHENTICATION_BACKENDS = (
    #'authenticate.Accounts.'
    'django.contrib.auth.backends.ModelBackend',
)

could you please see what the mistake is?

please excuse my etiquettes as this is my first question in stackoverflow also please consider that i have just started working on django a few weeks ago

Suraj Ingle
  • 372
  • 4
  • 18
  • Passwords are normally *hashed*, hence `Account.objects.get(username = "uname").password == request.POST['password']` should be *false*. – Willem Van Onsem Feb 09 '20 at 10:09
  • @WillemVanOnsem i have used `user.set_password(password)` but for some reasons the passwords stored in db are _unhashed_. which is why although being a wrong method, it is returning true – Suraj Ingle Feb 09 '20 at 11:30

1 Answers1

0

The value of Account.objects.get(username='uname').password == request.POST['password'] is True.

This is not a good idea. Normally passwords are hashed. Indeed, that is why the AbstractBaseUser base class, implements a set_password(..) method [Django-doc]. This will hash the password, and store the hashed password in the database.

The authenticate(..) method will first hash the given password as well, and then check if that hashed password corresponds to the one stored in the database.

See the Password management in Django section for more information.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • i have used `user.set_password(password)` in my code but still the passwords are being stored unhashed in database. – Suraj Ingle Feb 09 '20 at 11:33
  • @user9304976: can you show how you exactly created the user? Please edit your question. – Willem Van Onsem Feb 09 '20 at 11:40
  • 1
    thankyou. knowing that passwords needed to be hashed was crucial to figure out the bug. the problem was in the way i created user. i simply added the user by user.objects.create() but Ive changed it to the view section of above mentioned(edited) code. I've been trying to debug this for two days straight. thank you for your directions – Suraj Ingle Feb 09 '20 at 12:01