我正在尝试通过Flask中的电子邮件链接实施重置密码。 这是我在views.py中的代码:
@app.route("/reset_password/<token>", methods=['GET', 'POST'])
def reset_token(token):
if current_user.is_authenticated:
return redirect(url_for('homepage'))
user = User.verify_reset_token(token)
if user is None:
flash('That is an invalid or expired token', 'warning')
return redirect(url_for('reset_request'))
form = ResetPasswordForm()
if form.validate_on_submit():
hashed_password = generate_password_hash(form.password.data, method='sha256')
User.objects(email=token.email).update_one(set__username=hashed_password)
flash('Your password has been updated! You are now able to log in', 'success')
return redirect(url_for('login'))
return render_template('reset_token.html', title='Reset Password', form=form)
这是我在models.py中的代码
class User(UserMixin, db.Document):
meta = {'collection': 'users'}
email = db.StringField(max_length=35)
name = db.StringField(max_length=35)
surname = db.StringField(max_length=35)
password = db.StringField()
username = db.StringField()
image_file = db.StringField(nullable=False, default='static/img/default.jpg')
skills = db.ListField(db.StringField())
def get_reset_token(self, expires_sec=1800):
s = Serializer(app.config['SECRET_KEY'], expires_sec)
return s.dumps({'email': self.email}).decode('utf-8')
@staticmethod
def verify_reset_token(token):
s = Serializer(app.config['SECRET_KEY'])
try:
email = s.loads(token)['email']
except:
return None
return User.objects(email='email')
def __repr__(self):
return f"User('{self.email}', '{self.image_file}')"
这是我在forms.py中的代码
class RequestResetForm(FlaskForm):
email = StringField('Email', validators=[validators.DataRequired()])
submit = SubmitField('Request Password Reset')
def validate_email(self, email):
user = User.objects(email=email.data).first()
if user is None:
raise ValidationError('There is no account with that email. You must register first.')
class ResetPasswordForm(FlaskForm):
password = PasswordField('New Password', validators=[validators.DataRequired()])
confirm_password = PasswordField('Confirm Password', validators=[validators.DataRequired(), validators.EqualTo('password')])
submit = SubmitField('Reset Password')
当我尝试插入新密码(带有令牌的链接发送到我的电子邮件之后)时,该密码未保存,我可以使用旧密码访问个人资料。 我使用Mongoengine。 有谁可以帮助我吗? 谢谢。
答案 0 :(得分:0)
您已经在此处使用令牌的verify方法定义了用户模型
user = User.verify_reset_token(token)
因此您必须以这种方式“提取”用户的电子邮件
User.objects(email=user.email).update_one(set__username=hashed_password)