“shubhamdhamal” commited on
Commit
e7ac0a2
·
1 Parent(s): 9a6b6cc

Fix CSRF: add before_request session init, limit CORS to API routes

Browse files
Files changed (1) hide show
  1. web_app/__init__.py +18 -6
web_app/__init__.py CHANGED
@@ -29,8 +29,13 @@ def create_app(config_class=Config):
29
 
30
  # Initialize CSRF protection
31
  csrf.init_app(app)
 
 
 
 
 
32
 
33
- # Enable CORS for all routes
34
  # This allows requests from Codespace frontend and mobile app
35
  allowed_origins = [
36
  "http://localhost:3000", # React frontend
@@ -45,14 +50,13 @@ def create_app(config_class=Config):
45
  if extra_origin and extra_origin not in allowed_origins:
46
  allowed_origins.append(extra_origin)
47
 
48
- # For mobile devices, allow all origins since they don't send Origin header
49
- # or send the local IP which varies
50
  CORS(app,
51
- resources={r"/*": {"origins": "*"}},
52
  methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"],
53
  allow_headers=["Content-Type", "Authorization", "X-Requested-With"],
54
- supports_credentials=False, # Must be False when using wildcard origin
55
- max_age=3600) # Preflight cache time
56
 
57
  # Set DEV_MODE from environment
58
  app.config['DEV_MODE'] = os.environ.get(
@@ -63,6 +67,14 @@ def create_app(config_class=Config):
63
  db.init_app(app)
64
  login_manager.init_app(app)
65
  migrate.init_app(app, db)
 
 
 
 
 
 
 
 
66
 
67
  # Initialize Redis connection for RQ
68
  try:
 
29
 
30
  # Initialize CSRF protection
31
  csrf.init_app(app)
32
+
33
+ # Exempt API endpoints from CSRF (they use token auth)
34
+ @csrf.exempt
35
+ def csrf_exempt_api():
36
+ pass
37
 
38
+ # Enable CORS for API routes only (not for auth pages)
39
  # This allows requests from Codespace frontend and mobile app
40
  allowed_origins = [
41
  "http://localhost:3000", # React frontend
 
50
  if extra_origin and extra_origin not in allowed_origins:
51
  allowed_origins.append(extra_origin)
52
 
53
+ # Apply CORS only to /api/* routes to avoid interfering with session cookies
 
54
  CORS(app,
55
+ resources={r"/api/*": {"origins": "*"}},
56
  methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"],
57
  allow_headers=["Content-Type", "Authorization", "X-Requested-With"],
58
+ supports_credentials=False,
59
+ max_age=3600)
60
 
61
  # Set DEV_MODE from environment
62
  app.config['DEV_MODE'] = os.environ.get(
 
67
  db.init_app(app)
68
  login_manager.init_app(app)
69
  migrate.init_app(app, db)
70
+
71
+ # Ensure session is always started (required for CSRF tokens)
72
+ @app.before_request
73
+ def ensure_session():
74
+ from flask import session
75
+ if '_csrf_token' not in session:
76
+ session['_csrf_token'] = True
77
+ session.modified = True
78
 
79
  # Initialize Redis connection for RQ
80
  try: