限制用户访问flask中的路由

Restrict users to access routes in flask

我正在尝试创建一个允许用户登录的 Flask 应用程序,此后,他们将被重定向到创建并使用 Bokeh 服务的特定仪表板。

所以,比如我们有一个user1,一开始他会在https:myurl/login开始,成功登录后,他将被重定向到他的特定仪表板所在的 https:myurl/user1

所以,我的问题是,如何避免 user1 从其他用户 user2、user3 等访问仪表板。实际上可以做到吗?我对 Flask 比较陌生,所以如果这个问题听起来很愚蠢,我深表歉意。

from multiprocessing import connection
from functools import wraps
from re import A
from flask import Flask, render_template, request, flash, redirect, url_for, session
import sqlite3


from sqlalchemy import DATE

# Setup
app = Flask(__name__)

app.secret_key = "my_key"

# Routes
@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        connection = sqlite3.connect("user_login.db")
        cursor = connection.cursor()

        # Get what the user has typed in the HTML form
        username = request.form["username"]
        password = request.form["password"]

        # SQL query
        cursor.execute(
            "SELECT * FROM users WHERE username=? AND password=?", (username, password)
        )
        data = cursor.fetchone()

        if data:
            session["username"] = data[1]
            session["password"] = data[2]
            return redirect(url_for("user({data[1]})"))
            # return redirect(f"https://myurl/{session['username']}", code=302)
        else:
            flash("Username and Password Mismatch", "DANGER! Please try again")

    # Render HTML template
    return render_template("login.html")


# Check if user is logged in
# def is_logged_in(f):
#     @wraps(f)
#     def secure_function(*args, **kwargs):
#         if "logged_in" in session:
#             return f(*args, **kwargs)
#         else:
#             flash("Unauthorized, please login", "danger")
#             return redirect(url_for("login"))
#     return secure_function


@app.route("/<username>")
def user(username):
    if username == session['username']:
        return redirect(
            f"https://myurl/{session['username']}", code=302
        )
    else:
        return flash("Unauthorized")


# @app.route('/')
# def logged():
#     return redirect(f"https://myurl/{session['username']}", code=302)


if __name__ == "__main__":
    app.run(debug=True)

如何验证

current_user.username == myurl/<username>

.username 是您模型中用户的名称(如果是名称则 current_user.name,依此类推)

喜欢

@app.route("/dashboard/<username>")
def dashboard(username):
    if username == current_user.username:
        #proceed
    else:
        return "Access Denied"

*** 编辑 ***

您为 return 语句提供的代码

redirect(url_for("user({data[1]})"))

可以写成:


return redirect(url_for('user', username = data[1]))