1

I have implemented a solution for checking a new password against the last 5 passwords like so:

  1. Created 5 fields in a user profile table to store the encrypted passwords
  2. On creating a new user, I stored the initial password in encrypted form in all the 5 fields
  3. On reset, I changed the views.py from Lib>django>contrib>auth directory from my virtual environment like so:
def form_valid(self, form):
    #all initial code to get the keys etc goes here

    newpwd = form.cleaned_data['new_password2']

    #get the unencrypted passwords from history
    p1 = cipher.decrypt(b64decode(user.pwd1))
    p2 = cipher.decrypt(b64decode(user.pwd2))
    p3 = cipher.decrypt(b64decode(user.pwd3))
    p4 = cipher.decrypt(b64decode(user.pwd4))
    p5 = cipher.decrypt(b64decode(user.pwd5))

    #check if the password is already used and redirect with error message
    if newpwd == p1 or newpwd == p2 or newpwd == p3 or newpwd == p4 or newpwd == p5:
        messages.error(self.request, _('New Password should be different from old password'))
        return redirect('password_change')
    else:
        #store the password in the password history
        user.pwd5=user.pwd4
        user.pwd4=user.pwd3
        user.pwd3=user.pwd2
        user.pwd2=user.pwd1
        user.pwd1=newpwd 
        user.save()
        form.save()
        messages.error(self.request,'Password Changed Successfully')
        return redirect('/user/login')

    form.save()
    # Updating the password logs out all other sessions for the user
    # except the current one.
    update_session_auth_hash(self.request, form.user)
    return super().form_valid(form)

This works fine. But it feels incorrect editing the existing contrib>auth files like this. Is there a way to implement the password history checking without changing the in built auth files?

damon
  • 14,485
  • 14
  • 56
  • 75
Monty Swanson
  • 695
  • 16
  • 41
  • 1
    What you have to do is override the `Authentication Form`. Check this response: https://stackoverflow.com/questions/56183127/how-to-extend-django-authenticationform – Hagyn May 19 '21 at 05:45
  • Can't definitely tell, but for future viewers, make sure that you're not storing the current and past passwords in plaintext. In fact you shouldn't be able to decrypt past passwords at all. Instead you should be hashing the password immediately and then checking past passwords against that. – blueteeth Jun 20 '21 at 17:43

0 Answers0