Flask装饰器限制访问某些路线

时间:2014-08-10 23:45:58

标签: python web-applications flask

如何使用自定义装饰器限制对路径的访问?或者有更简单的方法吗?

以下是重置忘记密码的代码:

@auth.route('/reset', methods=['GET', 'POST'])
def password_reset_verify():
    if not current_user.is_anonymous():
        return redirect(url_for('main.index'))
    form = PasswordResetVerifyForm()
    if form.validate_on_submit():
        return redirect(url_for('auth.password_reset', uid=form.uid.data))
    return render_template('auth/reset.html', form=form)

在他们验证上述路线之前,我不希望其他人访问此路线。由于您可以通过/ reset / 123456789

更改其他密码
@auth.route('/reset/<uid>', methods=['GET', 'POST'])
def password_reset(uid):
    if not current_user.is_anonymous():
        return redirect(url_for('main.index'))
    form = PasswordResetForm()
    if form.validate_on_submit():
        user = User.query.filter_by(uid=uid).first()
        if user is None:
            return redirect(url_for('main.index'))
        if user.reset_password(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.html', form=form)

如何编写自定义装饰器,以便访客无权进入password_rest路由。换句话说,password_rest路由只能一次访问该验证。或者有没有办法将password_rest合并到password_rest_verify?

1 个答案:

答案 0 :(得分:0)

所以我使用itsdangerous生成令牌

generate_reset_token方法生成一个默认有效时间的令牌。 reset_password函数检查令牌中的id是否与验证用户匹配。