kkt-2002 commited on
Commit
1465638
·
1 Parent(s): c063266

Fix session persistence with Flask-Session

Browse files
Files changed (3) hide show
  1. Dockerfile +1 -1
  2. app.py +32 -15
  3. requirements.txt +1 -0
Dockerfile CHANGED
@@ -40,7 +40,7 @@ RUN pip install --no-cache-dir --upgrade pip && \
40
  COPY --chown=user:user . /app
41
 
42
  # Create necessary directories
43
- RUN mkdir -p app/static app/templates
44
 
45
  # Expose Hugging Face port
46
  EXPOSE 7860
 
40
  COPY --chown=user:user . /app
41
 
42
  # Create necessary directories
43
+ RUN mkdir -p app/static app/templates flask_session
44
 
45
  # Expose Hugging Face port
46
  EXPOSE 7860
app.py CHANGED
@@ -1,4 +1,5 @@
1
  from flask import Flask, render_template, request, redirect, url_for, flash, session, jsonify
 
2
  import os
3
  import gc
4
  import logging
@@ -8,7 +9,7 @@ import pymongo
8
  from pymongo import MongoClient
9
  from bson.binary import Binary
10
  import base64
11
- from datetime import datetime, timezone
12
  from dotenv import load_dotenv
13
  import numpy as np
14
  import cv2
@@ -40,16 +41,26 @@ load_dotenv()
40
 
41
  # Initialize Flask app
42
  app = Flask(__name__, static_folder='app/static', template_folder='app/templates')
43
- app.secret_key = os.environ.get('SECRET_KEY', os.urandom(24))
44
-
45
- # SESSION CONFIGURATION FOR HUGGING FACE COMPATIBILITY
46
- app.config['SESSION_COOKIE_SECURE'] = False # Allow non-HTTPS in development
 
 
 
 
47
  app.config['SESSION_COOKIE_HTTPONLY'] = True
 
48
  app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
49
- app.config['PERMANENT_SESSION_LIFETIME'] = 3600 # 1 hour
50
- app.config['SESSION_TYPE'] = 'filesystem'
51
 
52
- print(f"Flask app initialized with secret key: {bool(app.secret_key)}")
 
 
 
 
 
 
 
53
 
54
  # Create temporary directory for image processing
55
  TEMP_DIR = tempfile.mkdtemp()
@@ -554,14 +565,14 @@ def login():
554
  # Clear any existing session
555
  session.clear()
556
 
557
- # Set session variables
558
  session['logged_in'] = True
559
  session['user_type'] = 'student'
560
  session['student_id'] = student_id
561
  session['name'] = student.get('name', 'Unknown')
562
  session.permanent = True
563
 
564
- print(f"Session set: {dict(session)}") # Debug log
565
  flash('Login successful!', 'success')
566
  return redirect(url_for('dashboard'))
567
  else:
@@ -629,7 +640,7 @@ def face_login():
629
  # Clear any existing session
630
  session.clear()
631
 
632
- # Set session variables
633
  session['logged_in'] = True
634
  session['user_type'] = face_role
635
  session[id_field] = user[id_field]
@@ -724,7 +735,7 @@ def auto_face_login():
724
  # Clear any existing session
725
  session.clear()
726
 
727
- # Set session variables
728
  session['logged_in'] = True
729
  session['user_type'] = face_role
730
  session[id_field] = user[id_field]
@@ -813,6 +824,9 @@ def dashboard():
813
  flash(f'Error loading dashboard: {str(e)}', 'danger')
814
  return redirect(url_for('login_page'))
815
 
 
 
 
816
  @app.route('/mark-attendance', methods=['POST'])
817
  def mark_attendance():
818
  if 'logged_in' not in session or session.get('user_type') != 'student':
@@ -1126,7 +1140,7 @@ def teacher_login():
1126
  # Clear any existing session
1127
  session.clear()
1128
 
1129
- # Set session variables
1130
  session['logged_in'] = True
1131
  session['user_type'] = 'teacher'
1132
  session['teacher_id'] = teacher_id
@@ -1285,6 +1299,7 @@ def health_check():
1285
  'status': 'healthy',
1286
  'platform': 'hugging_face',
1287
  'session_working': bool(session.get('logged_in')),
 
1288
  'memory': 'optimized',
1289
  'face_detector': 'haar_cascade',
1290
  'timestamp': datetime.now().isoformat()
@@ -1298,7 +1313,9 @@ def debug_session():
1298
  'logged_in': session.get('logged_in', False),
1299
  'user_type': session.get('user_type', 'None'),
1300
  'cookies': dict(request.cookies),
1301
- 'secret_key_set': bool(app.secret_key)
 
 
1302
  })
1303
 
1304
  @app.route('/test-login')
@@ -1326,5 +1343,5 @@ def manual_cleanup():
1326
  # HUGGING FACE SPECIFIC: Updated port to 7860
1327
  if __name__ == '__main__':
1328
  port = int(os.environ.get('PORT', 7860)) # Hugging Face uses port 7860
1329
- print(f"Starting Flask app on port {port}")
1330
  app.run(host='0.0.0.0', port=port, debug=False)
 
1
  from flask import Flask, render_template, request, redirect, url_for, flash, session, jsonify
2
+ from flask_session import Session
3
  import os
4
  import gc
5
  import logging
 
9
  from pymongo import MongoClient
10
  from bson.binary import Binary
11
  import base64
12
+ from datetime import datetime, timezone, timedelta
13
  from dotenv import load_dotenv
14
  import numpy as np
15
  import cv2
 
41
 
42
  # Initialize Flask app
43
  app = Flask(__name__, static_folder='app/static', template_folder='app/templates')
44
+ app.secret_key = os.environ.get('SECRET_KEY', os.urandom(32))
45
+
46
+ # FLASK-SESSION CONFIGURATION FOR SERVER-SIDE SESSIONS
47
+ app.config['SESSION_TYPE'] = 'filesystem' # Store sessions on server disk
48
+ app.config['SESSION_FILE_DIR'] = './flask_session/' # Directory for session files
49
+ app.config['SESSION_PERMANENT'] = True
50
+ app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(hours=2) # 2 hour sessions
51
+ app.config['SESSION_USE_SIGNER'] = True
52
  app.config['SESSION_COOKIE_HTTPONLY'] = True
53
+ app.config['SESSION_COOKIE_SECURE'] = False # Set True if HTTPS
54
  app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
 
 
55
 
56
+ # Create session directory if it doesn't exist
57
+ if not os.path.exists('./flask_session/'):
58
+ os.makedirs('./flask_session/')
59
+
60
+ # Initialize Flask-Session
61
+ Session(app)
62
+
63
+ print(f"Flask app initialized with Flask-Session: filesystem storage")
64
 
65
  # Create temporary directory for image processing
66
  TEMP_DIR = tempfile.mkdtemp()
 
565
  # Clear any existing session
566
  session.clear()
567
 
568
+ # Set session variables with Flask-Session
569
  session['logged_in'] = True
570
  session['user_type'] = 'student'
571
  session['student_id'] = student_id
572
  session['name'] = student.get('name', 'Unknown')
573
  session.permanent = True
574
 
575
+ print(f"Session set successfully: {dict(session)}") # Debug log
576
  flash('Login successful!', 'success')
577
  return redirect(url_for('dashboard'))
578
  else:
 
640
  # Clear any existing session
641
  session.clear()
642
 
643
+ # Set session variables with Flask-Session
644
  session['logged_in'] = True
645
  session['user_type'] = face_role
646
  session[id_field] = user[id_field]
 
735
  # Clear any existing session
736
  session.clear()
737
 
738
+ # Set session variables with Flask-Session
739
  session['logged_in'] = True
740
  session['user_type'] = face_role
741
  session[id_field] = user[id_field]
 
824
  flash(f'Error loading dashboard: {str(e)}', 'danger')
825
  return redirect(url_for('login_page'))
826
 
827
+ # Add all your other existing routes here (mark-attendance, liveness-preview, teacher routes, etc.)
828
+ # ... (copy all remaining routes from your previous code)
829
+
830
  @app.route('/mark-attendance', methods=['POST'])
831
  def mark_attendance():
832
  if 'logged_in' not in session or session.get('user_type') != 'student':
 
1140
  # Clear any existing session
1141
  session.clear()
1142
 
1143
+ # Set session variables with Flask-Session
1144
  session['logged_in'] = True
1145
  session['user_type'] = 'teacher'
1146
  session['teacher_id'] = teacher_id
 
1299
  'status': 'healthy',
1300
  'platform': 'hugging_face',
1301
  'session_working': bool(session.get('logged_in')),
1302
+ 'session_storage': app.config['SESSION_TYPE'],
1303
  'memory': 'optimized',
1304
  'face_detector': 'haar_cascade',
1305
  'timestamp': datetime.now().isoformat()
 
1313
  'logged_in': session.get('logged_in', False),
1314
  'user_type': session.get('user_type', 'None'),
1315
  'cookies': dict(request.cookies),
1316
+ 'secret_key_set': bool(app.secret_key),
1317
+ 'session_type': app.config['SESSION_TYPE'],
1318
+ 'session_dir': app.config['SESSION_FILE_DIR']
1319
  })
1320
 
1321
  @app.route('/test-login')
 
1343
  # HUGGING FACE SPECIFIC: Updated port to 7860
1344
  if __name__ == '__main__':
1345
  port = int(os.environ.get('PORT', 7860)) # Hugging Face uses port 7860
1346
+ print(f"Starting Flask app on port {port} with Flask-Session")
1347
  app.run(host='0.0.0.0', port=port, debug=False)
requirements.txt CHANGED
@@ -1,4 +1,5 @@
1
  Flask==2.3.3
 
2
  pymongo==4.6.0
3
  python-dotenv==1.0.0
4
  opencv-python-headless==4.8.1.78
 
1
  Flask==2.3.3
2
+ Flask-Session==0.8.0
3
  pymongo==4.6.0
4
  python-dotenv==1.0.0
5
  opencv-python-headless==4.8.1.78