I’m trying to use flask to create a backend for a website
flask doesn’t keep the seasion when the user moves into another page, I tried every single solution from the first 10 pages of google search.
this is my backend (removed unrelevant functions and code)
from flask import Flask, request, jsonify, make_response, session,redirect, url_for
from flask_cors import CORS, cross_origin
import logging
import sqlite3
app = Flask(__name__,template_folder="../templates", static_folder="../static")
logging.basicConfig(level=logging.DEBUG)
CORS(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True)
app.secret_key = "166" #don't look!!!
app.config.update(SESSION_COOKIE_SAMESITE=None, SESSION_COOKIE_SECURE=True)
# get the user info example
def get_user(username):
connection = sqlite3.connect('users.db')
cursor = connection.cursor()
cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
user = cursor.fetchone()
connection.close()
return user
# get the current user from the seasion
@app.route('/get_current_user', methods=['GET'])
@cross_origin(supports_credentials=True)
def get_current_user():
if "username" in session:
return session["username"]
else:
return "not logged in"
return True
@app.route('/register', methods=['POST'])
@cross_origin(supports_credentials=True)
def register():
data = request.form
username = data['username']
password = data['password']
.....
# Check if the user already exists
# Add the user to the DB
# Create a session for the user after successful registration
session['username'] = username
session.permanent = True
....
return response
if __name__ == '__main__':
create_database()
app.run(debug=True,port=1661,host='0.0.0.0')
as you can see, I added the SESSION_COOKIE_SAMESITE="None", SESSION_COOKIE_SECURE configs, and I use supports_credentials=True everywhere. yet it doesn’t work.
I also did not forget to use the credentials in the js.
fetch('http://xx.xx.xx.xx:1661/get_current_user', {credentials: 'include'})
.then(response => response.text())
.then(username => {
// Update the content of #user-name with the retrieved username
const userNameElement = document.getElementById('user-name');
userNameElement.textContent = username;
})
.catch(error => {
console.error('Error fetching user data:', error);
// Handle the error if needed
});
what happnes is that the user registers using /register, it the session is created, and then the user gets redirected using js herf to /user, in this page the user’s client sents a get request to get the username from the server using /get_current_user and the code gets to the "return "not logged in" part. No errors. I’m out of idea.
2
Answers
Answering my own question after soooo much troubleshooitng.
What I assume was the issue is that the browser didn't sent the cookie because it was cross-domain (different ports) without htpps.
If I unserstand correctly, there is no way to make it work without either enabling https or avoiding cross-domain requests.
I chose to avoid cross-domain requests by making everything run from the flask server.
Try this…
change the
session["username"]
tosession.get("username")