Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Flask session behaves erratically
#1
My Flask Session behaves in an unpredictable manner. I'm using the same Flask Session settings I did in my previous project, and yet this time it's completely chaotic.

I log in, save the value in session["user_type"] to track the account privileges, and then after going to another page with @admin_required wrapper sometimes it goes on in a normal way, and sometimes it redirects me back to the login page with an error message that I don't have an admin level.

I've read somewhere that it may happen with "SECRET_KEY" missing, but as you can see, I have it in my code, so have no idea where the issue might be.

app = Flask(__name__)
app.config["SECRET_KEY"] = "abcdef"

# Session settings
app.config["SESSION_TYPE"] = "filesystem"
app.config["SESSION_FILE_DIR"] = "session"
app.config["SESSION_USE_SIGNER"] = True
app.config["SESSION_PERMANENT"] = True
app.config["PERMANENT_SESSION_LIFETIME"] = timedelta(hours=16)
Session(app)

def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if session.get("user_type") != "admin":
            flash(Markup("<strong>Error: admin level required</strong>" +
                         "<br>If you have an admin account, please sign in."),
                  "danger")
            return redirect("/sign-in")
        return f(*args, **kwargs)
    return decorated_function


@app.route("/admin/article/add")
@admin_required
def article_add():
    return render_template("article_add.html")


@app.route("/admin/dashboard")
@admin_required
def dashboard():
    return render_template("dashboard.html")

@app.route("/sign-in", methods=["GET", "POST"])
def sign_in():
    if request.method == "POST":
        # Clear the session for a new user to sign in
        session.clear()
        # Get the sign in form data
        # . . .
        # Add the session data about the signed in user
        session["user_id"] = users[0]["user_id"]
        session["username"] = users[0]["username"]
        session["user_type"] = users[0]["user_type"]
        if session["user_type"] == "admin":
            return redirect("/admin/dashboard")
        return redirect("/")
    return render_template("sign-in.html")
Reply


Messages In This Thread
Flask session behaves erratically - by Antares - Nov-06-2019, 01:09 PM
RE: Flask session behaves erratically - by Larz60+ - Nov-06-2019, 06:14 PM
RE: Flask session behaves erratically - by Antares - Nov-06-2019, 09:12 PM
RE: Flask session behaves erratically - by Larz60+ - Nov-06-2019, 10:19 PM
RE: Flask session behaves erratically - by Antares - Nov-07-2019, 02:54 PM
RE: Flask session behaves erratically - by Antares - Nov-08-2019, 09:58 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020