How to hash stored passwords in mysql using pbkdf2_sha256 using Django


I have list of user passwords stored as plain text. I think I need a script to run over the stored passwords and hash them. I’m new to Django and not sure where to start or how.

I created login and creating accounts only works for new users:

def add_emp(request):
    if request.method == 'POST':
        user_name = request.POST['user_name']
        user_email = request.POST['user_email']
        user_otj = request.POST['user_otj']
        user_password = pwo.generate()
        user_password1 = make_password(user_password)
        empObj = User.objects.create(user_name=user_name, user_email=user_email, user_password=user_password1, user_otj=user_otj)
        if empObj:
            subject = 'Advanced Analytics Portal - Login Info'
            message = f'Name : {user_name}, n Email : {user_email}, n Password : {user_password} n FROM - AA Portal'
            email_from = settings.EMAIL_HOST_USER
            send_mail(subject, message, email_from, [user_email])
            messages.success(request, "Employee was added successfully!")
            return HttpResponseRedirect('/create-emp')
            messages.error(request, "Some error was occurred!")
            return HttpResponseRedirect('/create-emp')
    return render(request, 'AddEmp.html')

def user_login(request):
    if request.method == "POST":
        user_email = request.POST['user_email']
        user_password = request.POST['user_password']
        user_details = User.objects.filter(user_email=user_email).first()

        if user_details and check_password(user_password, user_details.user_password):
            request.session['logged_in'] = True
            request.session['user_email'] = user_details.user_email
            request.session['u_id'] = user_details.user_email
            request.session['user_name'] = user_details.user_name
            request.session['u_type'] = "emp"
            return HttpResponseRedirect('/user_index')
            return render(request, 'EmpLogin.html', {'msg': "0"})
        return render(request, 'EmpLogin.html')

How can I make previous users log in without creating new accounts for them.

Asked By: JHS99



You can use make_password() to hash the password and is_password_usable() to avoid re-hashing already hashed passwords by checking whether the password is hashed or not.

Write a script or a management command to loop over the existing User objects and update their passwords, like following:

from django.contrib.auth.hashers import make_password, is_password_usable
from myapp.models import User

def hash_existing_passwords():
    for user in User.objects.all():
        if not is_password_usable(user.password):
        user.password = make_password(user.password)


You can run this script using the following command:

python shell < path/to/
Answered By: Sunderam Dubey