How to use check_password function in django

Viewed 3888

I'm a beginner in Django. I have a signup form with only 2 fields. Username and Password. The password is encrypted using the pbkdf2_sha256 algorithm. I want to login using the username and password.so the password that I'm inputting in the login page must be checked with the encrypted password. How to do that?. Also, please explain what authenticate and check_password function does?

def save(request):
    if request.method == 'POST':
       name = request.POST.get('name')
       password = request.POST.get('pass')
       enc_pass = pbkdf2_sha256.encrypt(password,rounds=12000,salt_size = 32)
       a = signup(username = name, password = enc_pass)
       a.save()
   return render(request,'save.html')
def login(request):
   if request.method  == 'POST':

       username        = request.POST.get('user')
       password1          = request.POST.get('password1')
       p = check_password(password=password1)
      if signup.objects.filter(username__exact=username).exists() and p is True:
           return HttpResponse("Success")
     else:
           return HttpResponse("Invalid Credentials")
   return render(request, 'login.html')
2 Answers

You can do:

if check_password(password_user_entered, request.user.password):
    # You can authenticate

Here, password_user_entered is password that came from the request(or, pw to be checked). And, request.user.password which is the password with which we want to compare.

check_password does not work like this. To make it work, you need to use Django's own authentication system. If you are concerned about using pbkdf2_sha256, Django provides this hasher. To use this with you own auth system, add it to settings:

PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.Argon2PasswordHasher',
]

And in django authentication, you do not need to hash it manually, django will take care of it itself. All you need to do is save the user like this:

from django.contrib.auth.models import User

user = User.objects.create_user(username=username, email=email, password=password, #.. other required fields)

And to check password:

user = User.objects.get(username=username)
user.check_password(password)

More information can be found in documentation

Related