Nov-06-2019, 01:09 PM
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
I've read somewhere that it may happen with
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.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
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" ) |