maxcountryman/flask-login

current_user and sessions are not saved when logging in from browser

akuppili45 opened this issue · 1 comments

I am running my flask server on http://127.0.0.1:5000/ and my Next.js server on http://localhost:3000. When I login from Insomnia/Postman, the login/logout works as expected. However, on the browser the current_user is not saved. After a successful log in, the current_user changes back to a AnonymousUserMixin Object. When I put the @login_required decorator and logout from the browser I get a 401. I tried experimenting with session variables and I have the same problem. I enabled CORS on my server, I set the supports_credentials to True, and when calling the login and logout apis from the frontend, I am setting the credentials attribute to "include" and the mode attribute to "cors". Am I missing something?

Login call from frontend

    const endpoint = 'http://127.0.0.1:5000/login';
    const options = {
            // The method is POST because we are sending data.
            method: 'POST',
            // Tell the server we're sending JSON.
            headers: {
              'Content-Type': 'application/json',
              'Access-Control-Allow-Origin' : '*',
              'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS',
              'Access-Control-Allow-Credentials': 'true'
            },
            // Body of the request is the JSON data we created above.
            body: JSONdata,
            credentials: 'include',
            mode: 'cors'
    }
    console.log(`email from api/login is ${email} and password is ${password}`)

    const login = await fetchJson(endpoint, options);

Logout call from frontend

        const endpoint = 'http://127.0.0.1:5000/logout';
        const options = {
            // The method is POST because we are sending data.
            method: 'GET',
            // Tell the server we're sending JSON.
            headers: {
              'Content-Type': 'application/json',
              'Access-Control-Allow-Origin' : '*',
                'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS'
            },
            credentials: "include",
            mode: 'cors'
            // Body of the request is the JSON data we created above.
        }
        await fetchJson(endpoint, options);

app.py

# imports
app = Flask(__name__)
SECRET_KEY = os.urandom(32)
app.secret_key = SECRET_KEY
CORS(app, supports_credentials=True)
#... more routes
@app.route('/login', methods=['GET', 'POST'])
@cross_origin()
def login():
    email = request.json['email']
    entered_password = request.json['password']
    u = aws_controller.getUserByEmail(email = email)
    user_json = json.loads(json.dumps(u, default=str))
    user = User(user_json['username'], user_json['email'])
    user.password_hash = user_json['password_hash']
    user.id = user_json['id']
    # print(user.id)
    if user is not None and user.check_password(entered_password):
        # print(type(current_user))
        # print(current_user.is_authenticated)
        login_user(user)
        session['curr'] = 'curr'
        print('login', flush=True)
        print(session, flush=True)
        return json.loads(json.dumps(current_user.__dict__))
    return None

@app.route("/logout", methods=['GET', 'POST'])
@cross_origin()
def logout():
    print(current_user)
    logout_user()
    return json.loads(json.dumps({'logout': True}))

Please use Stack Overflow for questions about your own code. This tracker is for issues related to the project itself. Be sure to include a minimal, complete, and verifiable example.