I have implemented a solution for checking a new password against the last 5 passwords like so:
- Created 5 fields in a user profile table to store the encrypted passwords
- On creating a new user, I stored the initial password in encrypted form in all the 5 fields
- 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?