How to recover a Flask session after coming back from redirect from an external site?

Viewed 27

I have a Flask application that logs users into Facebook, Twitter and more. However, when implementing the authentication, I must handle a redirect coming from these sites, and I lose the session.

For the sake of simplicity, let's consider the Twitter case. The flow is basically asking for a Twitter URL, then redirect the user to that URL, have the user provide permissions, and then redirect back to a callback URL in my app. My code (very simplified) is something like this:

@services.route('/api/twoauth', methods=["GET"])
def tw_oauth():
    oauth_token = request.args.get("oauth_token")
    user_id = session.get("user_id")
    if user_id is None:
        return {"result": "failed", "msg": "Invalid session."}, 401

    # First call, the Twitter URL is obtained and sent back to the client
    if oauth_token is None:
        ...
        return {"result": "success", "redirect_url": redirect_url}, 200
    
    # User is coming back from Twitter, so tokens must be stored and the user must be 
    # redirected to a front-end view. This code is not reached because user_id is None.
    else:
        ...
        return redirect("https://" + URL + ":" + PORT_FRONTEND + "/services/twitteruser?authstatus=1")

The else clause is never reached. How can I recover user_id? My login and logout functions look like this, in case of need:

@auth.route('/api/login', methods=["POST"])
def login():
    email = request.json.get('email')
    password = request.json.get('password')
    remember = request.json.get('remember')
    user_id = check_login(email, password)
    if user_id is None:
        return {"result": "failed", "msg": "Invalid session."}, 401
    session["user_id"] = user_id
    return {"result": "success", "id": user_id, "email": email}, 200

@auth.route("/api/logout", methods=["POST"])
def logout():
    session.pop("user_id")
    return {"result": "success"}, 200

PS: I do not intend to use flask-login nor JWT, I tried both and they messed a lot with the React front-end.

PS2: Two additional short questions: Is there any smarter way to check in which case are we, instead of checking if oauth_token is None? How could I implement the 'remember' functionality into my login?

Thank you all in advance.

0 Answers
Related