saran14 commited on
Commit
23d4e21
Β·
1 Parent(s): 67436b5
Files changed (1) hide show
  1. app.py +37 -10
app.py CHANGED
@@ -3,6 +3,7 @@ from apscheduler.schedulers.background import BackgroundScheduler
3
  from datetime import datetime
4
  import traceback
5
  import os
 
6
 
7
  from config import RSS_URL, APP_TITLE, APP_SOURCE_NAME, FETCH_INTERVAL_MINUTES, DATABASE, TIMEZONE
8
  from db import init_db, upsert_article, get_latest, get_article_by_guid
@@ -35,14 +36,17 @@ def load_keywords():
35
 
36
  app = Flask(__name__)
37
  # Use environment variable for secret key or generate a secure one
38
- app.secret_key = os.environ.get('SECRET_KEY', 'fallback-secret-key-change-in-production-2024')
 
39
 
40
- # Configure session to be more reliable in production
41
- app.config['SESSION_COOKIE_SECURE'] = False # Set to True if using HTTPS
42
  app.config['SESSION_COOKIE_HTTPONLY'] = True
43
  app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
44
  app.config['PERMANENT_SESSION_LIFETIME'] = 7200 # 2 hours
45
  app.config['SESSION_COOKIE_NAME'] = 'news_session'
 
 
46
 
47
  # Ensure DB is initialized for all environments (including production)
48
  init_db(DATABASE)
@@ -67,12 +71,16 @@ def login():
67
  username = request.form['username']
68
  password = request.form['password']
69
  if check_user(username, password):
 
70
  session['username'] = username
 
71
  session.permanent = True # Make session permanent
72
- print(f"User {username} logged in successfully. Session set.")
 
 
73
  return redirect(url_for('home'))
74
  else:
75
- print(f"Failed login attempt for username: {username}")
76
  error_message = 'Invalid username or password'
77
  return render_template('login.html', app_title=APP_TITLE, error=error_message)
78
  return render_template('login.html', app_title=APP_TITLE)
@@ -83,6 +91,16 @@ def logout():
83
  print("User logged out, session cleared")
84
  return redirect(url_for('login'))
85
 
 
 
 
 
 
 
 
 
 
 
86
  def fetch_and_update():
87
  """
88
  1) Parse RSS
@@ -133,14 +151,23 @@ def fetch_and_update():
133
  # Home page now fetches and displays news from 5 RSS feeds filtered by keywords
134
  @app.route("/")
135
  def home():
136
- print(f"Home route accessed. Session keys: {list(session.keys())}")
137
- print(f"Username in session: {'username' in session}")
 
138
 
139
- if 'username' not in session:
140
- print("No username in session, redirecting to login")
 
 
 
 
 
 
 
 
141
  return redirect(url_for('login'))
142
 
143
- print(f"User {session['username']} accessing home page")
144
 
145
  try:
146
  keywords = load_keywords()
 
3
  from datetime import datetime
4
  import traceback
5
  import os
6
+ import secrets
7
 
8
  from config import RSS_URL, APP_TITLE, APP_SOURCE_NAME, FETCH_INTERVAL_MINUTES, DATABASE, TIMEZONE
9
  from db import init_db, upsert_article, get_latest, get_article_by_guid
 
36
 
37
  app = Flask(__name__)
38
  # Use environment variable for secret key or generate a secure one
39
+ import secrets
40
+ app.secret_key = os.environ.get('SECRET_KEY', secrets.token_hex(32))
41
 
42
+ # Configure session to be more reliable in HF Spaces containerized environment
43
+ app.config['SESSION_COOKIE_SECURE'] = False # HF Spaces uses HTTP internally
44
  app.config['SESSION_COOKIE_HTTPONLY'] = True
45
  app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
46
  app.config['PERMANENT_SESSION_LIFETIME'] = 7200 # 2 hours
47
  app.config['SESSION_COOKIE_NAME'] = 'news_session'
48
+ app.config['SESSION_COOKIE_PATH'] = '/'
49
+ app.config['SESSION_COOKIE_DOMAIN'] = None # Let Flask handle this automatically
50
 
51
  # Ensure DB is initialized for all environments (including production)
52
  init_db(DATABASE)
 
71
  username = request.form['username']
72
  password = request.form['password']
73
  if check_user(username, password):
74
+ session.clear() # Clear any existing session data
75
  session['username'] = username
76
+ session['authenticated'] = True
77
  session.permanent = True # Make session permanent
78
+ # Add extra debugging for HF Spaces
79
+ print(f"βœ… User {username} logged in successfully")
80
+ print(f"βœ… Session data: {dict(session)}")
81
  return redirect(url_for('home'))
82
  else:
83
+ print(f"❌ Failed login attempt for username: {username}")
84
  error_message = 'Invalid username or password'
85
  return render_template('login.html', app_title=APP_TITLE, error=error_message)
86
  return render_template('login.html', app_title=APP_TITLE)
 
91
  print("User logged out, session cleared")
92
  return redirect(url_for('login'))
93
 
94
+ @app.route('/debug-session')
95
+ def debug_session():
96
+ """Debug route to check session status"""
97
+ return {
98
+ 'session_keys': list(session.keys()),
99
+ 'session_data': dict(session),
100
+ 'authenticated': session.get('authenticated', False),
101
+ 'username': session.get('username', 'Not set')
102
+ }
103
+
104
  def fetch_and_update():
105
  """
106
  1) Parse RSS
 
151
  # Home page now fetches and displays news from 5 RSS feeds filtered by keywords
152
  @app.route("/")
153
  def home():
154
+ print(f"🏠 Home route accessed")
155
+ print(f"πŸ” Session keys: {list(session.keys())}")
156
+ print(f"πŸ‘€ Session data: {dict(session)}")
157
 
158
+ # Check multiple conditions for authentication
159
+ username_exists = 'username' in session
160
+ auth_flag = session.get('authenticated', False)
161
+
162
+ print(f"βœ… Username in session: {username_exists}")
163
+ print(f"βœ… Authenticated flag: {auth_flag}")
164
+
165
+ if not username_exists or not auth_flag:
166
+ print("❌ Authentication failed, redirecting to login")
167
+ session.clear() # Clear any corrupted session data
168
  return redirect(url_for('login'))
169
 
170
+ print(f"βœ… User {session['username']} successfully accessing home page")
171
 
172
  try:
173
  keywords = load_keywords()