I have hashed passwords stored in my database and I want to implement a password change function. Before updating the password, I want to check how similar the old and new passwords are. I have used the difflib library to compare the two values, but even when the old and new passwords are the same, the function successfully updates the password without giving a warning about their similarity.
from werkzeug.security import generate_password_hash, check_password_hash
from difflib import SequenceMatcher
@accounts.route('/<int:id>', methods=['PUT'])
def update_password(id):
try:
account = db_session.query(Account).filter_by(id=id).first()
if not account:
return jsonify({'error': 'Account not found.'}), 404
json_data = request.get_json()
try:
data = AccountPasswordSchema().load(json_data)
except ValidationError as err:
return jsonify({"error": err.messages}), 400
old_password_hash = account.password_hash
new_password = data.get('password')
new_password_hash = generate_password_hash(new_password, method='sha256')
similarity_ratio = SequenceMatcher(None, old_password_hash, new_password_hash).ratio()
if similarity_ratio > 0.8:
return jsonify({'error': 'New password is too similar to the old password.'}), 400
account.password = data.get('password')
db_session.commit()
return jsonify({'message': 'Password successfully updated.'}), 200
except Exception as e:
return jsonify({'error': str(e)}), 400
Kindly, advise how can I implement this task?