EN VI

Python - Troubleshooting flask error of storing and retreiving session cookies?

2024-03-09 23:30:06
How to Python - Troubleshooting flask error of storing and retreiving session cookies

I am new to using flask for backend, and am facing an issue with storing sessions using memcached. I installed Memurai and connected to it and it was working fine. In my app. The login route apparently works fine and through thunderclient i can see a cookie being generated when user is logged in using correct credentials. However, error occurs when I visit the route /me, where I am constantly getting a 401 unauthorized error. Upon inspection using print commands (at line 44 and 45 of app.py), I can see that Session Data: <MemcachedSession {}> User ID: None , which prolly means the session is not storing any data. Here are my codes for app.py, config.py and models.py. I'd really appreciate if anyone helps me with this issue.

app.py:

from flask import Flask, request, jsonify, session
from flask_bcrypt import Bcrypt
from config import ApplicationConfig
from flask_session import Session
from models import db, User

app = Flask(__name__)
app.config.from_object(ApplicationConfig)

bcrypt = Bcrypt(app)
flask_session = Session(app)
db.init_app(app)

with app.app_context():
    db.create_all()
    
    
@app.route("/register", methods=["POST"])
def register_user():
    email = request.json["email"]
    password = request.json["password"]
    
    user_exists = User.query.filter_by(email=email).first() is not None
    
    if(user_exists):
        return jsonify({
            "error": "User already Exists"
        }), 409
    
    hashed_password = bcrypt.generate_password_hash(password).decode('utf-8')    
    new_user = User(email=email, password=hashed_password)    
    db.session.add(new_user)
    db.session.commit()
    
    return jsonify({
        "id":new_user.id,
        "email":new_user.email
    })

@app.route("/me")
def get_user():
    user_id = session.get("user_id")
    
    print("Session Data:", session)
    print("User ID:", user_id)
    
    if not user_id:
        return jsonify({"error":"Unauthorized"}), 401
    
    user = User.query.filter_by(id=user_id).first()
    return jsonify({
        "id":user.id,
        "email":user.email
    })

@app.route("/login", methods=["POST"])
def login_user():
    email = request.json["email"]
    password = request.json["password"]
    
    user = User.query.filter_by(email=email).first()
    
    if user is None:
        return jsonify({"error":"User Not Found"}), 401
    
    if not bcrypt.check_password_hash(user.password, password):
        return jsonify({"error":"Invalid Password"}), 401
    
    session["user_id"] = user.id
    
    return jsonify({
        "id": user.id,
        "email": user.email
    })


if __name__ == "__main__":
    app.run(debug=True)

config.py file:

from dotenv import load_dotenv
import os 

load_dotenv()

class ApplicationConfig:
    SECRET_KEY = os.environ["SECRET_KEY"]
    
    SQLALCHEMY_TRACK_MODIFICATIONS= False
    SQLALCHEMY_ECHO = True
    SQLALCHEMY_DATABASE_URI = r"sqlite:///./db.authapp"
    
    SESSION_TYPE= 'memcached'
    SESSION_PERMANENT = False
    SESSION_USER_SIGNER = True
    
    MEMCACHED_SERVER = ['127.0.0.1:6379']

models.py:

from flask_sqlalchemy import SQLAlchemy
from uuid import uuid4

db = SQLAlchemy()

def get_uuid():
    return str(uuid4())

class User(db.Model):
    __tablename__ = "users"
    id = db.Column(db.String(32), primary_key = True, unique = True, default= get_uuid)
    email= db.Column(db.String(345),unique=True)
    password= db.Column(db.Text, nullable = False)

Solution:

Based on the code provided, there appears to be a configuration error with the session type in the config.py file. You specified SESSION_TYPE= 'memcached', but the server actually used is Parse, which is compatible with Redis, not Memcached.

To fix this, update your config.py as follows:

class ApplicationConfig:
    # Other configurations...
   
    SESSION_TYPE = 'redis'
    SESSION_PERMANENT = False
    SESSION_USE_SIGNER = True
    SESSION_REDIS = {
        'host': 'localhost',
        'port': 6379,
        'db': 0,
        'socket_timeout': 1
    }

Make sure that your Parse server is running on localhost:6379 as per configuration. Then, restart your Flask application and try again. This should resolve the session saving issue you are having.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login