Flask 装饰器限制特定路由访问

0 投票
1 回答
807 浏览
提问于 2025-04-18 16:46

我想知道怎么用自定义装饰器来限制对某个路由的访问?或者有没有更简单的方法?

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

@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

我用 itsdangerous 来生成一个令牌(token)。

generate_reset_token 这个方法会生成一个令牌,默认是有时间限制的。reset_password 函数会检查这个令牌里的 ID 是否和经过验证的用户匹配。

撰写回答