1

I am trying to use Flask Blueprints, but it seems I can't access session object in the different Blueprints.

In an Authentication Blueprint I have the following function:

@authentication_bp.route("/login", methods=["POST"])
def login():
    # Get information about user and try to find him
    username = request.get_json().get("username")
    password = request.get_json().get("password")
    user = User.find_by_username(username)

    # Validate user
    if not user or not user.verify_password(password):
        error_log.error("Login failed!")

        return jsonify(success=False, message="Incorrect username or password!"), 403 # forbidden

    # Update session
    session["LOGGED_IN"] = True
    session["USERNAME"] = username
    info_log.info("%s logged in successfully." % username)

    return jsonify(success=True)

So if the user successfully signs in, session should be updated.

The in main.py I have a checkLogin function:

@app.route("/checkLogin")
def check_login():
    print(session.get("LOGGED_IN"))
    # Check if there is a user logged in
    if session.get("LOGGED_IN"):
        return jsonify(logged_in=True)

    return jsonify(logged_in=False)

I run check_login() right after login(). Login() function returns 'success' but after that print(session.get("LOGGED_IN")) prints None, rather than True.

Is this behaviour of Blueprints expected and how could I achieve what I want?

NOTE: I checked out Flask Blueprint Putting something on session but that didn't answer the question for me.

NOTE: I have imported session in both files and I have set the secret key for the Flask app.

2 Answers2

0

So after some thinking I realised that I don't store a lot of information in the session - only isLoggedIn (boolean) and username (string). I decided to create a separate class called ActiveUser storing those variables and I imported it where needed. I am not really sure if this is a proper solution or just a workaround though.

0

It is better to use Flask-Login extension because Flask sessions are not secure. You can read more about this here: https://blog.miguelgrinberg.com/post/how-secure-is-the-flask-user-session

Mohamed Diaby
  • 176
  • 2
  • 11