Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
7682 lines (6501 loc) · 279 KB
/
Copy pathapp.py
File metadata and controls
7682 lines (6501 loc) · 279 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import csv
import io
import os
import re
import math
import hashlib
import click
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
from flask import Flask, render_template, request, redirect, session, url_for, make_response, flash, jsonify, abort
from datetime import date, datetime, timedelta, timezone
from calendar import monthrange
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from db import get_db, close_db, IntegrityError, USE_PG
from extensions import csrf, limiter, bcrypt
from authlib.integrations.flask_client import OAuth
from utils.dates import (
get_today, get_current_day_range, get_current_week_range,
get_current_month_range, get_previous_month_range,
)
# ---------------------------------------------------------------------------
# App initialisation
# ---------------------------------------------------------------------------
app = Flask(__name__)
app.teardown_appcontext(close_db)
# Keep users logged in for a full year — no surprise sign-outs on mobile PWA
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=365)
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
app.config['SESSION_COOKIE_HTTPONLY'] = True
@app.after_request
def add_security_headers(response):
"""Add security headers to every response to mitigate XSS, Clickjacking, and sniffing."""
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['X-Frame-Options'] = 'SAMEORIGIN'
response.headers['X-XSS-Protection'] = '1; mode=block'
response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
response.headers['Permissions-Policy'] = 'geolocation=(), microphone=(self), camera=()'
# Only enforce HSTS in production/secure contexts so we don't break local HTTP dev
if os.environ.get('FLASK_ENV') == 'production' or request.is_secure:
response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
# Allow local development and common CDNs for scripts/styles
csp = (
"default-src 'self'; "
"connect-src 'self' https: ws: wss:; "
"script-src 'self' 'unsafe-inline' 'unsafe-eval' https://cdn.jsdelivr.net https://code.jquery.com https://kit.fontawesome.com https://cdnjs.cloudflare.com; "
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://fonts.googleapis.com https://cdnjs.cloudflare.com; "
"font-src 'self' https://fonts.gstatic.com https://kit-free.fontawesome.com https://cdn.jsdelivr.net https://cdnjs.cloudflare.com data:; "
"img-src 'self' data: https: blob:;"
)
response.headers['Content-Security-Policy'] = csp
return response
@app.before_request
def check_session_timeout():
"""Sessions are permanent (365 days). No inactivity timeout — mobile PWA users
should never be surprised by a sign-out. The cookie expiry handles cleanup."""
if "user_id" in session:
# Ensure every session is flagged as permanent so the browser keeps the
# cookie across restarts (especially important for Android/iOS PWA installs).
session.permanent = True
# SECRET_KEY must come from the environment in production.
# Fail loudly at startup if it is missing or still set to the known placeholder.
_KNOWN_INSECURE_KEYS = {
"super-secret-key-change-this",
"dev-secret-key-change-in-production",
"changeme",
"",
}
_secret = os.environ.get("SECRET_KEY", "")
if not _secret or _secret in _KNOWN_INSECURE_KEYS:
# Allow insecure key only in explicit testing/dev modes
if os.environ.get("FLASK_ENV") in ("production", None) and not os.environ.get("TESTING"):
raise RuntimeError(
"[RunRush] SECRET_KEY is missing or is a known insecure placeholder. "
"Set a strong SECRET_KEY environment variable before starting the app."
)
# Fallback for local dev / test runs
_secret = _secret or "dev-secret-key-change-in-production"
app.secret_key = _secret
app.config['DEV_LOGIN_ENABLED'] = (
os.environ.get("FLASK_ENV") == "development" and
os.environ.get("DEV_LOGIN_ENABLED", "false").lower() == "true"
)
# Wire up Flask extensions
csrf.init_app(app)
limiter.init_app(app)
from flask_wtf.csrf import CSRFError
from flask import jsonify
@app.errorhandler(CSRFError)
def handle_csrf_error(e):
return jsonify({"error": e.description}), 400
bcrypt.init_app(app)
oauth = OAuth(app)
if os.environ.get("GOOGLE_CLIENT_ID") and os.environ.get("GOOGLE_CLIENT_SECRET"):
oauth.register(
name='google',
server_metadata_url='https://accounts.google.com/.well-known/openid-configuration',
client_id=os.environ.get("GOOGLE_CLIENT_ID"),
client_secret=os.environ.get("GOOGLE_CLIENT_SECRET"),
client_kwargs={
'scope': 'openid email profile'
}
)
DEFAULT_WEIGHT = 0.0 # used if user hasn't set weight yet
# Temporary announcement banner — auto-expires server-side after this date.
# Remove this constant (and the template logic) once the date has passed.
ANNOUNCEMENT_EXPIRES = date(2026, 9, 20)
def _apply_startup_schema_updates():
"""Ensure essential tables and defaults exist in production without requiring manual shell access."""
if os.environ.get("TESTING"):
return
try:
conn = get_db()
# 1. monthly_report_preferences
conn.execute("""
CREATE TABLE IF NOT EXISTS monthly_report_preferences (
user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
popup_enabled INTEGER NOT NULL DEFAULT 1,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# 2. monthly_summary_deliveries
if USE_PG:
conn.execute("""
CREATE TABLE IF NOT EXISTS monthly_summary_deliveries (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
year INTEGER NOT NULL,
month INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'PENDING',
error TEXT,
sent_at TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, year, month)
)
""")
else:
conn.execute("""
CREATE TABLE IF NOT EXISTS monthly_summary_deliveries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
year INTEGER NOT NULL,
month INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'PENDING',
error TEXT,
sent_at TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, year, month),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
""")
# 3. Ensure indexes
try:
conn.execute("CREATE INDEX IF NOT EXISTS idx_msd_user ON monthly_summary_deliveries(user_id)")
conn.execute("CREATE INDEX IF NOT EXISTS idx_msd_status ON monthly_summary_deliveries(status)")
except Exception:
pass
# 4. Auto-enable email summaries for Google users
try:
conn.execute("""
UPDATE users
SET email = COALESCE(NULLIF(email, ''), google_email),
email_monthly_summary = 1,
email_weekly_summary = 1
WHERE (google_id IS NOT NULL OR google_email IS NOT NULL)
""")
conn.commit()
except Exception:
pass
conn.close()
except Exception as e:
print(f"[RunRush DB] Startup schema check warning: {e}", flush=True)
with app.app_context():
_apply_startup_schema_updates()
# ----------------- DB HELPERS -----------------
@app.cli.command("init-db")
def init_db_command():
"""Initialize the database (create tables)."""
init_db()
def init_db():
conn = get_db()
if USE_PG:
print("[RunRush DB] Connected to PostgreSQL. Persistent storage is ACTIVE.")
# ---- PostgreSQL DDL (all columns from the start) ----
conn.execute("""
CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
username TEXT UNIQUE NOT NULL,
pin TEXT NOT NULL,
display_name TEXT,
profile_emoji TEXT DEFAULT '🏃🏻',
weight REAL,
theme TEXT,
height REAL,
last_login TEXT,
role TEXT DEFAULT 'user',
status TEXT DEFAULT 'active',
google_id TEXT UNIQUE,
google_avatar_url TEXT
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS runs (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id),
date TEXT NOT NULL,
distance_km REAL NOT NULL,
time_min REAL NOT NULL,
pace REAL NOT NULL,
calories REAL NOT NULL,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
insight TEXT
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS edit_history (
id SERIAL PRIMARY KEY,
run_id INTEGER NOT NULL REFERENCES runs(id),
user_id INTEGER NOT NULL REFERENCES users(id),
field_name TEXT NOT NULL,
old_value TEXT,
new_value TEXT,
edited_at TEXT DEFAULT CURRENT_TIMESTAMP
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS activity_logs (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
action TEXT NOT NULL,
details TEXT,
timestamp TEXT NOT NULL
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS admin_notes (
id SERIAL PRIMARY KEY,
target_user_id INTEGER NOT NULL REFERENCES users(id),
author_id INTEGER NOT NULL REFERENCES users(id),
note TEXT NOT NULL,
timestamp TEXT NOT NULL
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS badges (
id SERIAL PRIMARY KEY,
key TEXT UNIQUE NOT NULL,
name TEXT NOT NULL,
description TEXT,
icon_url TEXT,
criteria_type TEXT NOT NULL,
criteria_value REAL NOT NULL
)
""")
conn.execute("ALTER TABLE users ADD COLUMN IF NOT EXISTS google_id TEXT UNIQUE")
conn.execute("ALTER TABLE users ADD COLUMN IF NOT EXISTS google_avatar_url TEXT")
conn.execute("ALTER TABLE users ADD COLUMN IF NOT EXISTS profile_emoji TEXT DEFAULT '🏃🏻'")
conn.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_users_google_id ON users(google_id)")
# PIN recovery token table (PG)
conn.execute("""
CREATE TABLE IF NOT EXISTS pin_resets (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id),
code_hash TEXT NOT NULL,
expires_at TEXT NOT NULL,
attempts INTEGER DEFAULT 0,
created_at TEXT NOT NULL,
used_at TEXT
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS user_badges (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
badge_id INTEGER NOT NULL REFERENCES badges(id) ON DELETE RESTRICT,
run_id INTEGER REFERENCES runs(id) ON DELETE SET NULL,
unlocked_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, badge_id)
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS user_stats (
id SERIAL PRIMARY KEY,
user_id INTEGER UNIQUE NOT NULL REFERENCES users(id),
total_distance_km REAL DEFAULT 0.0,
current_streak INTEGER DEFAULT 0,
best_streak INTEGER DEFAULT 0,
last_activity_date TEXT,
updated_at TEXT
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS friends (
id SERIAL PRIMARY KEY,
follower_id INTEGER NOT NULL REFERENCES users(id),
followed_id INTEGER NOT NULL REFERENCES users(id),
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
UNIQUE (follower_id, followed_id)
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS run_likes (
id SERIAL PRIMARY KEY,
run_id INTEGER NOT NULL REFERENCES runs(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
UNIQUE (run_id, user_id)
)
""")
conn.execute("CREATE INDEX IF NOT EXISTS idx_run_likes_run_id ON run_likes(run_id)")
conn.execute("""
CREATE TABLE IF NOT EXISTS user_weekly_goals (
user_id INTEGER PRIMARY KEY REFERENCES users(id),
goal_km REAL NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS monthly_goals (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
year INTEGER NOT NULL,
month INTEGER NOT NULL,
target_km REAL NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, year, month)
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS web_push_subscriptions (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
endpoint TEXT NOT NULL UNIQUE,
p256dh TEXT NOT NULL,
auth TEXT NOT NULL,
expiration_time DOUBLE PRECISION,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_web_push_subscriptions_user_id "
"ON web_push_subscriptions(user_id)"
)
conn.execute("""
CREATE TABLE IF NOT EXISTS monthly_summary_deliveries (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
year INTEGER NOT NULL,
month INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'PENDING',
error TEXT,
sent_at TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, year, month)
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS monthly_report_views (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
year INTEGER NOT NULL,
month INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'DISMISSED_DAY_1',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, year, month)
)
""")
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_monthly_report_views_user "
"ON monthly_report_views(user_id)"
)
conn.execute("""
CREATE TABLE IF NOT EXISTS monthly_report_preferences (
user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
popup_enabled INTEGER NOT NULL DEFAULT 1,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS user_dashboard_layout (
user_id INTEGER PRIMARY KEY REFERENCES users(id),
layout_json TEXT NOT NULL
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS challenges (
id SERIAL PRIMARY KEY,
key TEXT UNIQUE NOT NULL,
name TEXT NOT NULL,
description TEXT NOT NULL,
target_value REAL NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS user_challenge_progress (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
challenge_id INTEGER NOT NULL REFERENCES challenges(id) ON DELETE RESTRICT,
current_progress REAL DEFAULT 0.0,
completed_at TIMESTAMP,
UNIQUE(user_id, challenge_id)
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS user_goals (
id SERIAL PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id),
goal_type TEXT NOT NULL,
target_distance_km REAL NOT NULL,
target_date TEXT NOT NULL,
days_per_week INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'active',
created_at TEXT NOT NULL,
dashboard_pinned BOOLEAN DEFAULT false
)
""")
# Add columns that may not exist (PG migration — uses IF NOT EXISTS, safe to re-run)
for pg_migration in [
"ALTER TABLE runs ADD COLUMN IF NOT EXISTS run_type TEXT DEFAULT 'easy'",
"ALTER TABLE runs ADD COLUMN IF NOT EXISTS notes TEXT",
"ALTER TABLE users ADD COLUMN IF NOT EXISTS email TEXT",
"ALTER TABLE users ADD COLUMN IF NOT EXISTS email_weekly_summary INTEGER DEFAULT 1",
"ALTER TABLE users ADD COLUMN IF NOT EXISTS email_monthly_summary INTEGER DEFAULT 1",
"ALTER TABLE users ADD COLUMN IF NOT EXISTS google_id TEXT",
"ALTER TABLE users ADD COLUMN IF NOT EXISTS google_email TEXT",
"ALTER TABLE users ADD COLUMN IF NOT EXISTS height REAL",
# Weather / location columns
"ALTER TABLE users ADD COLUMN IF NOT EXISTS home_city TEXT",
"ALTER TABLE users ADD COLUMN IF NOT EXISTS home_latitude REAL",
"ALTER TABLE users ADD COLUMN IF NOT EXISTS home_longitude REAL",
"ALTER TABLE users ADD COLUMN IF NOT EXISTS failed_login_attempts INTEGER DEFAULT 0",
"ALTER TABLE users ADD COLUMN IF NOT EXISTS locked_until TEXT",
"ALTER TABLE runs ADD COLUMN IF NOT EXISTS weather_temp REAL",
"ALTER TABLE runs ADD COLUMN IF NOT EXISTS weather_humidity INTEGER",
"ALTER TABLE runs ADD COLUMN IF NOT EXISTS weather_wind_kph REAL",
"ALTER TABLE runs ADD COLUMN IF NOT EXISTS weather_condition TEXT",
"ALTER TABLE runs ADD COLUMN IF NOT EXISTS weather_emoji TEXT",
# PIN recovery columns
"ALTER TABLE users ADD COLUMN IF NOT EXISTS recovery_email TEXT",
"ALTER TABLE users ADD COLUMN IF NOT EXISTS recovery_email_verified INTEGER DEFAULT 0",
# Public profile columns
"ALTER TABLE users ADD COLUMN IF NOT EXISTS bio TEXT",
"ALTER TABLE users ADD COLUMN IF NOT EXISTS next_race TEXT",
"ALTER TABLE users ADD COLUMN IF NOT EXISTS avatar_image BYTEA",
"ALTER TABLE users ADD COLUMN IF NOT EXISTS avatar_mime_type TEXT",
# Onboarding redesign columns
"ALTER TABLE users ADD COLUMN IF NOT EXISTS experience TEXT",
"ALTER TABLE users ADD COLUMN IF NOT EXISTS primary_goal TEXT",
"ALTER TABLE users ADD COLUMN IF NOT EXISTS frequency TEXT",
]:
try:
conn.execute(pg_migration)
except Exception:
pass
else:
print(f"DEBUG: init_db using conn {conn._conn}", flush=True)
print("[RunRush DB WARNING] Connected to SQLite (runs.db). Data is EPHEMERAL on Render/cloud hosting. To persist profiles across deploys, set DATABASE_URL in Render environment variables.")
# ---- SQLite DDL (with ALTER TABLE migrations) ----
conn.execute("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
pin TEXT NOT NULL
)
""")
# add new columns if they don't exist (SQLite migration style)
import sqlite3 as _sqlite3
_alter_columns = [
"ALTER TABLE users ADD COLUMN display_name TEXT",
"ALTER TABLE users ADD COLUMN weight REAL",
"ALTER TABLE users ADD COLUMN theme TEXT",
"ALTER TABLE users ADD COLUMN height REAL",
"ALTER TABLE users ADD COLUMN last_login TEXT",
"ALTER TABLE users ADD COLUMN role TEXT DEFAULT 'user'",
"ALTER TABLE users ADD COLUMN status TEXT DEFAULT 'active'",
"ALTER TABLE users ADD COLUMN email TEXT",
"ALTER TABLE users ADD COLUMN email_weekly_summary INTEGER DEFAULT 1",
"ALTER TABLE users ADD COLUMN email_monthly_summary INTEGER DEFAULT 1",
"ALTER TABLE users ADD COLUMN google_id TEXT",
"ALTER TABLE users ADD COLUMN google_email TEXT",
# Weather / location columns
"ALTER TABLE users ADD COLUMN home_city TEXT",
"ALTER TABLE users ADD COLUMN home_latitude REAL",
"ALTER TABLE users ADD COLUMN home_longitude REAL",
"ALTER TABLE users ADD COLUMN failed_login_attempts INTEGER DEFAULT 0",
"ALTER TABLE users ADD COLUMN locked_until TEXT",
# PIN recovery columns
"ALTER TABLE users ADD COLUMN recovery_email TEXT",
"ALTER TABLE users ADD COLUMN recovery_email_verified INTEGER DEFAULT 0",
# Onboarding redesign columns
"ALTER TABLE users ADD COLUMN experience TEXT",
"ALTER TABLE users ADD COLUMN primary_goal TEXT",
"ALTER TABLE users ADD COLUMN frequency TEXT",
"ALTER TABLE users ADD COLUMN profile_emoji TEXT DEFAULT '🏃🏻'",
]
for sql in _alter_columns + [
"ALTER TABLE users ADD COLUMN bio TEXT",
"ALTER TABLE users ADD COLUMN next_race TEXT",
"ALTER TABLE users ADD COLUMN avatar_image BLOB",
"ALTER TABLE users ADD COLUMN avatar_mime_type TEXT",
]:
try:
conn.execute(sql)
except _sqlite3.OperationalError:
pass
conn.execute("CREATE UNIQUE INDEX IF NOT EXISTS idx_users_google_id ON users(google_id)")
# PIN recovery token table (SQLite)
conn.execute("""
CREATE TABLE IF NOT EXISTS pin_resets (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
code_hash TEXT NOT NULL,
expires_at TEXT NOT NULL,
attempts INTEGER DEFAULT 0,
created_at TEXT NOT NULL,
used_at TEXT,
FOREIGN KEY (user_id) REFERENCES users(id)
)
""")
# runs table
conn.execute("""
CREATE TABLE IF NOT EXISTS runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
date TEXT NOT NULL,
distance_km REAL NOT NULL,
time_min REAL NOT NULL,
pace REAL NOT NULL,
calories REAL NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id)
)
""")
# Add columns to runs if missing (SQLite migration — safe to re-run)
for sql in [
"ALTER TABLE runs ADD COLUMN created_at TEXT DEFAULT CURRENT_TIMESTAMP",
"ALTER TABLE runs ADD COLUMN insight TEXT",
"ALTER TABLE runs ADD COLUMN run_type TEXT DEFAULT 'easy'",
"ALTER TABLE runs ADD COLUMN notes TEXT", # Feature: friend mentions
# Weather columns
"ALTER TABLE runs ADD COLUMN weather_temp REAL",
"ALTER TABLE runs ADD COLUMN weather_humidity INTEGER",
"ALTER TABLE runs ADD COLUMN weather_wind_kph REAL",
"ALTER TABLE runs ADD COLUMN weather_condition TEXT",
"ALTER TABLE runs ADD COLUMN weather_emoji TEXT",
]:
try:
conn.execute(sql)
except _sqlite3.OperationalError:
pass
# edit_history table
conn.execute("""
CREATE TABLE IF NOT EXISTS edit_history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
run_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
field_name TEXT NOT NULL,
old_value TEXT,
new_value TEXT,
edited_at TEXT DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (run_id) REFERENCES runs(id),
FOREIGN KEY (user_id) REFERENCES users(id)
)
""")
# activity logs
conn.execute("""
CREATE TABLE IF NOT EXISTS activity_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
action TEXT NOT NULL,
details TEXT,
timestamp TEXT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id)
)
""")
# admin notes
conn.execute("""
CREATE TABLE IF NOT EXISTS admin_notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
target_user_id INTEGER NOT NULL,
author_id INTEGER NOT NULL,
note TEXT NOT NULL,
timestamp TEXT NOT NULL,
FOREIGN KEY (target_user_id) REFERENCES users(id),
FOREIGN KEY (author_id) REFERENCES users(id)
)
""")
# badges table
conn.execute("""
CREATE TABLE IF NOT EXISTS badges (
id INTEGER PRIMARY KEY AUTOINCREMENT,
key TEXT UNIQUE NOT NULL,
name TEXT NOT NULL,
description TEXT,
icon_url TEXT,
criteria_type TEXT NOT NULL,
criteria_value REAL NOT NULL
)
""")
# user_badges table
conn.execute("""
CREATE TABLE IF NOT EXISTS user_badges (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
badge_id INTEGER NOT NULL,
unlocked_at TEXT DEFAULT CURRENT_TIMESTAMP,
run_id INTEGER,
UNIQUE (user_id, badge_id),
FOREIGN KEY (user_id) REFERENCES users(id)
)
""")
# user_stats table
conn.execute("""
CREATE TABLE IF NOT EXISTS user_stats (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER UNIQUE NOT NULL,
total_distance_km REAL DEFAULT 0.0,
current_streak INTEGER DEFAULT 0,
best_streak INTEGER DEFAULT 0,
last_activity_date TEXT,
updated_at TEXT,
FOREIGN KEY (user_id) REFERENCES users(id)
)
""")
# friends / follow system
conn.execute("""
CREATE TABLE IF NOT EXISTS friends (
id INTEGER PRIMARY KEY AUTOINCREMENT,
follower_id INTEGER NOT NULL,
followed_id INTEGER NOT NULL,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
UNIQUE (follower_id, followed_id),
FOREIGN KEY (follower_id) REFERENCES users(id),
FOREIGN KEY (followed_id) REFERENCES users(id)
)
""")
# likes on runs (activity feed)
conn.execute("""
CREATE TABLE IF NOT EXISTS run_likes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
run_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
UNIQUE (run_id, user_id),
FOREIGN KEY (run_id) REFERENCES runs(id) ON DELETE CASCADE,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
""")
conn.execute("CREATE INDEX IF NOT EXISTS idx_run_likes_run_id ON run_likes(run_id)")
conn.execute("""
CREATE TABLE IF NOT EXISTS user_weekly_goals (
user_id INTEGER PRIMARY KEY,
goal_km REAL NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id)
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS monthly_goals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
year INTEGER NOT NULL,
month INTEGER NOT NULL,
target_km REAL NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, year, month)
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS monthly_summary_deliveries (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
year INTEGER NOT NULL,
month INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'PENDING',
error TEXT,
sent_at TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, year, month)
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS monthly_report_views (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
year INTEGER NOT NULL,
month INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'DISMISSED_DAY_1',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, year, month)
)
""")
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_monthly_report_views_user "
"ON monthly_report_views(user_id)"
)
conn.execute("""
CREATE TABLE IF NOT EXISTS monthly_report_preferences (
user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE,
popup_enabled INTEGER NOT NULL DEFAULT 1,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS user_dashboard_layout (
user_id INTEGER PRIMARY KEY,
layout_json TEXT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id)
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS challenges (
id INTEGER PRIMARY KEY AUTOINCREMENT,
key TEXT UNIQUE NOT NULL,
name TEXT NOT NULL,
description TEXT NOT NULL,
target_value REAL NOT NULL,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS user_challenge_progress (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
challenge_id INTEGER NOT NULL,
current_progress REAL DEFAULT 0.0,
completed_at TEXT,
UNIQUE (user_id, challenge_id),
FOREIGN KEY (user_id) REFERENCES users(id)
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS user_goals (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
goal_type TEXT NOT NULL,
target_distance_km REAL NOT NULL,
target_date TEXT NOT NULL,
days_per_week INTEGER NOT NULL,
status TEXT NOT NULL DEFAULT 'active',
created_at TEXT NOT NULL,
dashboard_pinned BOOLEAN DEFAULT false,
FOREIGN KEY (user_id) REFERENCES users(id)
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS notifications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
message TEXT NOT NULL,
type TEXT NOT NULL,
created_by INTEGER NOT NULL,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
expires_at TEXT,
audience_type TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'SENT',
FOREIGN KEY (created_by) REFERENCES users(id)
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS user_notifications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
notification_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
delivered_at TEXT DEFAULT CURRENT_TIMESTAMP,
read_at TEXT,
UNIQUE(notification_id, user_id),
FOREIGN KEY (notification_id) REFERENCES notifications(id),
FOREIGN KEY (user_id) REFERENCES users(id)
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS web_push_subscriptions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
endpoint TEXT NOT NULL UNIQUE,
p256dh TEXT NOT NULL,
auth TEXT NOT NULL,
expiration_time REAL,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
)
""")
conn.execute(
"CREATE INDEX IF NOT EXISTS idx_web_push_subscriptions_user_id "
"ON web_push_subscriptions(user_id)"
)
conn.execute("""
CREATE TABLE IF NOT EXISTS notifications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
message TEXT NOT NULL,
type TEXT NOT NULL,
created_by INTEGER NOT NULL,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
expires_at TEXT,
audience_type TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'SENT',
FOREIGN KEY (created_by) REFERENCES users(id)
)
""")
conn.execute("""
CREATE TABLE IF NOT EXISTS user_notifications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
notification_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
delivered_at TEXT DEFAULT CURRENT_TIMESTAMP,
read_at TEXT,
UNIQUE(notification_id, user_id),
FOREIGN KEY (notification_id) REFERENCES notifications(id),
FOREIGN KEY (user_id) REFERENCES users(id)
)
""")
conn.commit()
# Seed badges and challenges
import os
seed_path = os.path.join(os.path.dirname(__file__), 'migrations', '002_seed_badges_challenges.sql')
if os.path.exists(seed_path):
with open(seed_path, 'r', encoding='utf-8') as f:
seed_sql = f.read()
try:
db_url = os.environ.get("DATABASE_URL", "")
is_postgres = db_url.startswith("postgres")
if is_postgres:
conn.execute(seed_sql)
else:
conn.executescript(seed_sql)
conn.commit()
except Exception as e:
print(f"Warning: Failed to seed DB (it may already be seeded): {e}")
# ---------------------------------------------------------------------------
# CLI Commands
# ---------------------------------------------------------------------------
@app.cli.command("migrate-pins")
@click.option("--dry-run", is_flag=True, default=False, help="Preview changes without writing to DB.")
def migrate_pins(dry_run):
"""
Hash all plaintext PINs in the users table using bcrypt.
Run ONLY against a local copy / backup of the database, never production.
Idempotent: already-hashed PINs (starting with '$2') are skipped.
"""
conn = get_db()
users = conn.execute("SELECT id, username, pin FROM users").fetchall()
updated = 0
skipped = 0
for u in users:
raw_pin = u["pin"] or ""
if raw_pin.startswith("$2"): # already a bcrypt hash
click.echo(f" SKIP user={u['username']} (already hashed)")
skipped += 1
continue
hashed = bcrypt.generate_password_hash(raw_pin)
if not dry_run:
conn.execute("UPDATE users SET pin = ? WHERE id = ?", (hashed, u["id"]))
click.echo(f" {'DRY ' if dry_run else ''}HASH user={u['username']}")
updated += 1
if not dry_run:
conn.commit()
conn.close()
click.echo(f"\nDone. Updated={updated}, Skipped={skipped}" + (" (dry-run, no changes written)" if dry_run else ""))
@app.cli.command("preview-monthly-summary")
@click.option("--user-id", type=int, required=True, help="User ID to build the summary for.")
@click.option("--year", type=int, required=True, help="Calendar year, e.g. 2026.")
@click.option("--month", type=int, required=True, help="Calendar month, 1-12.")
@click.option("--output", type=str, default=None,
help="Path to write the rendered HTML. Defaults to "
"dev_previews/monthly_summary_<user_id>_<year>_<month>.html")
def preview_monthly_summary(user_id, year, month, output):
"""
Render a specific user's monthly summary email locally and save it to
disk. Does NOT send anything — no Resend call is made here at all.
Example:
flask preview-monthly-summary --user-id 3 --year 2026 --month 9
"""
from services.monthly_summary_service import build_monthly_summary
from services.monthly_summary_renderer import render_html, render_subject
if not (1 <= month <= 12):
click.echo(f"Error: --month must be 1-12, got {month}", err=True)
raise SystemExit(1)
try:
summary = build_monthly_summary(user_id, year, month)
except ValueError as e:
click.echo(f"Error: {e}", err=True)
raise SystemExit(1)
subject = render_subject(summary)
html_out = render_html(summary)
if not output:
output = os.path.join("dev_previews", f"monthly_summary_{user_id}_{year}_{month:02d}.html")
os.makedirs(os.path.dirname(output) or ".", exist_ok=True)
with open(output, "w", encoding="utf-8") as f:
f.write(html_out)
def _safe_echo(text):