我的 Flask Web 应用的重置密码链接未重定向和更新密码

My Reset password link for my flask web app is not redirecting and updating the password

提问人:Naeim Salib 提问时间:11/14/2023 最后编辑:Naeim Salib 更新时间:11/15/2023 访问量:31

问:

所以我有这个功能通过电子邮件重置用户密码,一切正常(几乎) 电子邮件是与令牌一起发送的,我能够打开链接,将我重定向到该页面以输入我的新密码,但是当我这样做并提交时。 它将我重定向到我创建的 404 页面,当用户尝试转到 incorect 页面时,它会转到该页面

这是我的相关代码

def send_reset_email(user):
    token = user.get_reset_token().decode('utf-8')  # Decode bytes to string
    print("Reset Token:", token)
    msg = Message('Password Reset Request', sender='[email protected]', recipients=[user.email])
    msg.body = f'''
    To reset your password, visit the following link:
    {url_for('reset_token', token=token, _external=True)}

    If you did not make this request, please ignore this email and consider changing your email and password.
    '''
    mail.send(msg)

@app.route("/reset_password", methods=['GET', 'POST'])
def reset_request():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RequestResetForm()
    if form.validate_on_submit():
        user = User.query.filter_by(email=form.email.data).first()
        send_reset_email(user)
        flash('Reset password email has been send', 'info')
        return redirect(url_for('signin'))
    return render_template('reset_request.html', title='Reset Password', form=form)

@app.route("/reset_password/<token>", methods=['GET', 'POST'])
def reset_token(token):
    print( url_for('signin') )
    print("Reset Token Route Triggered")
    if current_user.is_authenticated:
        print('redirecting you to index')
        return redirect(url_for('index'))
    user = User.verify_reset_token(token)
    if user is None:
        print('The user value was 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 = bcrypt.generate_password_hash(form.password.data).decode('utf-8')
        user.password = hashed_password
        print(f"new password is {user.password}")
        db.session.commit()
        print("Password has been committed")
        flash(f'Your password has been updated', 'success')
        print("Redirecting you now to sign in")
        return redirect(url_for('signin'))
    return render_template('reset_token.html', title='Reset Password', form=form)

用户模型

class User(db.Model, UserMixin):
    # Manual Table name choice
    __tablename__ = 'users'

    id = db.Column(db.Integer, primary_key=True)
    firstname = db.Column(db.String(100), nullable=False)
    lastname = db.Column(db.String(100), nullable=False)
    email = db.Column(db.String(100), unique=True, nullable=False, index=True)
    password = db.Column(db.String(130), nullable=False)

    def get_reset_token(self, expires_sec=1800):
        s = Serializer(app.config['SECRET_KEY'])
        return s.dumps({'user_id': self.id}).encode('utf-8')

    @staticmethod
    def verify_reset_token(token):
        s = Serializer(app.config['SECRET_KEY'])
        try:
            user_id = s.loads(token)['user_id']
        except:
            return None
        return User.query.get(user_id)

    def __init__(self,firstname,lastname,email,password):
        self.firstname = firstname
        self.lastname = lastname
        self.email = email
        self.password = password

最后是我的Fors重置密码和请求重置表格


class RequestResetForm(FlaskForm):
    email = StringField('Email', validators=[InputRequired(), Email()])
    submit = SubmitField('Request Password Reset')

    def validate_email(self, email):
        user = User.query.filter_by(email=email.data).first()
        if user is None:
            raise ValidationError("There is no account with this email.")


class ResetPasswordForm(FlaskForm):
    password = PasswordField('Password', validators=[InputRequired(), Length(min=4, max=200)])
    confirm_password = PasswordField('Confirm Password', validators=[InputRequired(), Length(min=2, max=200), EqualTo('password')])
    submit = SubmitField('Reset Password')

非常感谢任何人在这里的帮助

谢谢!

我相信我的问题出现在我的reset_token函数中,因为它应该将更新的密码提交到数据库,然后将用户重定向到登录页面,但它没有这样做

python flask Web 应用程序 令牌 重置密码

评论

0赞 furas 11/14/2023
也许首先使用(和、、等)来查看代码的哪一部分被执行,以及变量中真正有什么。它被调用,它有助于查看代码真正在做什么。print()print(type(...))print(len(...))"print debuging"
0赞 furas 11/14/2023
您是否在终端/控制台中运行代码以查看错误消息?
0赞 furas 11/14/2023
重置后执行 - 你有这个功能吗?return redirect(url_for('signin'))signin
0赞 Naeim Salib 11/14/2023
所以是的,我尝试了打印调试,我带来了reset_request乐趣,但根本没有完成,而且我把它作为我的登录函数,是的,我有该函数登录
0赞 Naeim Salib 11/14/2023
我也没有看到任何错误消息,当 URL 无效时,我被重定向到我的 404 页面,该页面会到达该页面

答: 暂无答案