【发布时间】:2016-03-15 20:56:20
【问题描述】:
我目前正在通过 Miguel Grinberg 的书学习 Flask。如果你熟悉你可能知道Flasky(Miguel 在本书中使用的一个应用程序)
我目前在第 8 节,处理密码重置,这里是 原始代码(您也可以在 repo 上找到它。它的标签是 8g):
models.py
class User(UserMixin, db.Model):
__tablename__ = 'users'
...
def generate_reset_token(self, expiration=3600):
s = Serializer(current_app.config['SECRET_KEY'], expiration)
return s.dumps({'reset': self.id})
def reset_password(self, token, new_password):
s = Serializer(current_app.config['SECRET_KEY'])
try:
data = s.loads(token)
except:
return False
if data.get('reset') != self.id:
return False
self.password = new_password
db.session.add(self)
return True
auth/views.py
@auth.route('/reset/<token>', methods=['GET', 'POST'])
def password_reset(token):
if not current_user.is_anonymous:
return redirect(url_for('main.index'))
form = PasswordResetForm()
if form.validate_on_submit():
user = User.query.filter_by(email=form.email.data).first()
if user is None:
return redirect(url_for('main.index'))
if user.reset_password(token, form.password.data):
flash('Your password has been updated.')
return redirect(url_for('auth.login'))
else:
return redirect(url_for('main.index'))
return render_template('auth/reset_password.html', form=form)
auth/forms.py
class PasswordResetForm(Form):
email = StringField('Email', validators=[Required(), Length(1, 64),
Email()])
password = PasswordField('New Password', validators=[
Required(), EqualTo('password2', message='Passwords must match')])
password2 = PasswordField('Confirm password', validators=[Required()])
submit = SubmitField('Reset Password')
def validate_email(self, field):
if User.query.filter_by(email=field.data).first() is None:
raise ValidationError('Unknown email address.')
我的问题:
我不想再次询问用户他们的电子邮件,因为他们正在通过他们收到的电子邮件更改密码。有没有办法从该令牌中获取用户或用户的电子邮件?
【问题讨论】: