Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Python How to Compare Encrypt User's Password

I am working a project which is like CMS (Content Management System) for a website. I am developing this system with django python. But I am new to django python.

I have my own User model (not django user model) that contains some fields like username, email, password etc. and I create new user from my own admin panel.

How can I compare encrypted password with user's password that post on login page.

For example first time I create user, the password for 123 saved on db like pbkdf2_sha24123$000asd$... After that I am trying to login with password 123 but I get error that the passwords are not equals.

from django.contrib.auth.hashers import make_password
from account.models import myUsers

password = make_password(request.POST.get('password'))
email = request.POST.get('email')

if myUsers.password == password and myUsers.email == email:
     #make login and redirect to panel
else:
     #show error message

my own model like;

class myUsers(models.Model):
    username = models.CharField(max_length=25, verbose_name='username', unique=True)
    email = models.CharField(max_length=225, verbose_name='email', unique=True)
    password = models.CharField(max_length=225, verbose_name='password')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='created date')
    secret_question = models.CharField(max_length=225, verbose_name='secret question')
    secret_answer = models.CharField(max_length=225, verbose_name='secret answer')
    last_login = models.DateTimeField(verbose_name='last login')
    secret_guid_key = models.CharField(max_length=15, verbose_name='recover key', unique=True, editable=False, default=uuid.uuid4().hex[:15])
    user_role = models.CharField(max_length=6, verbose_name='member role')
like image 557
user518851726681 Avatar asked Oct 22 '17 15:10

user518851726681


1 Answers

A User Object has a method called check_password() that hashes and checks your plain text password against the hashed password stored in the DB.

https://docs.djangoproject.com/en/2.2/ref/contrib/auth/#django.contrib.auth.models.User.check_password

Example Usage:

from account.models import myUsers

password = request.POST.get('password')
email = request.POST.get('email')

user = myUsers.objects.get(email=email)

if user.check_password(password):
    # Success Code
else:
    # Error Code
like image 164
ASD Avatar answered Sep 20 '22 10:09

ASD