要重置Bcrypt哈希值,每当用户POST数据时,可以按照以下步骤进行解决:
from flask_bcrypt import Bcrypt
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'your_database_uri'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
password = db.Column(db.String(120), nullable=False)
def __init__(self, username, password):
self.username = username
self.password = bcrypt.generate_password_hash(password).decode('utf-8')
def check_password(self, password):
return bcrypt.check_password_hash(self.password, password)
db.create_all()
@app.route('/login', methods=['POST'])
def login():
username = request.form.get('username')
password = request.form.get('password')
user = User.query.filter_by(username=username).first()
if user and user.check_password(password):
# 登录成功
return jsonify({'message': 'Login successful'})
else:
# 登录失败
return jsonify({'message': 'Invalid credentials'})
@app.route('/change-password', methods=['POST'])
def change_password():
username = request.form.get('username')
old_password = request.form.get('old_password')
new_password = request.form.get('new_password')
user = User.query.filter_by(username=username).first()
if user and user.check_password(old_password):
# 更新密码哈希值
user.password = bcrypt.generate_password_hash(new_password).decode('utf-8')
db.session.commit()
return jsonify({'message': 'Password updated successfully'})
else:
return jsonify({'message': 'Invalid credentials'})
这样,当用户POST数据时,可以根据需要重置密码的哈希值,并确保用户的密码不再有效。