Spaces:
Sleeping
Sleeping
Hkoradiya123 commited on
Commit ·
cfef7c6
1
Parent(s): 11a0309
feat: Migrate from Firestore to MongoDB and add MongoDB configuration
Browse files- Updated .env.example to include MONGODB_URI and MONGODB_DB_NAME
- Modified config.py to load MongoDB settings
- Enhanced auth.py to utilize MongoDB for user management
- Refactored dashboard.py and matches.py to normalize match data
- Updated performance.py and players.py to improve user identity matching
- Replaced Firestore data handling with MongoDB in firestore_data.py
- Added migration script for transferring data from Firestore to MongoDB
- Updated requirements.txt to include pymongo
- Updated service worker and App.jsx for PWA improvements
- Removed PWA install prompt from main.jsx
- Enhanced Profile.jsx to fetch user data more reliably
- Improved error handling in api.js for Firebase authentication
- backend/.env.example +2 -0
- backend/app/config.py +4 -0
- backend/app/middleware/auth.py +11 -1
- backend/app/routes/dashboard.py +14 -14
- backend/app/routes/matches.py +51 -1
- backend/app/routes/performance.py +25 -11
- backend/app/routes/players.py +13 -3
- backend/app/utils/firestore_data.py +100 -52
- backend/migrate_firestore_to_mongo.py +227 -0
- backend/requirements.txt +1 -0
- backend/tempCodeRunnerFile.py +1 -0
- frontend/public/env.js +1 -0
- frontend/public/service-worker.js +7 -1
- frontend/src/App.jsx +0 -2
- frontend/src/main.jsx +16 -89
- frontend/src/pages/Profile.jsx +27 -15
- frontend/src/utils/api.js +92 -3
backend/.env.example
CHANGED
|
@@ -13,6 +13,8 @@ API_TITLE=SSC API
|
|
| 13 |
API_VERSION=1.0.0
|
| 14 |
DEBUG=False
|
| 15 |
CORS_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
|
|
|
|
|
|
|
| 16 |
FIREBASE_AUTH_ENABLED=True
|
| 17 |
FIREBASE_PROJECT_ID=
|
| 18 |
FIREBASE_WEB_API_KEY=
|
|
|
|
| 13 |
API_VERSION=1.0.0
|
| 14 |
DEBUG=False
|
| 15 |
CORS_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
|
| 16 |
+
MONGODB_URI=
|
| 17 |
+
MONGODB_DB_NAME=ssc
|
| 18 |
FIREBASE_AUTH_ENABLED=True
|
| 19 |
FIREBASE_PROJECT_ID=
|
| 20 |
FIREBASE_WEB_API_KEY=
|
backend/app/config.py
CHANGED
|
@@ -60,6 +60,10 @@ class Settings(BaseSettings):
|
|
| 60 |
"http://localhost:3000,http://127.0.0.1:3000",
|
| 61 |
)
|
| 62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
# Firebase Auth integration
|
| 64 |
FIREBASE_AUTH_ENABLED: bool = env_first_bool(
|
| 65 |
["FIREBASE_AUTH_ENABLED", "FIREBASEAUTHENABLED"],
|
|
|
|
| 60 |
"http://localhost:3000,http://127.0.0.1:3000",
|
| 61 |
)
|
| 62 |
|
| 63 |
+
# MongoDB data store
|
| 64 |
+
MONGODB_URI: str = env_first(["MONGODB_URI", "MONGODBURI"], "")
|
| 65 |
+
MONGODB_DB_NAME: str = env_first(["MONGODB_DB_NAME", "MONGODBDBNAME"], "ssc")
|
| 66 |
+
|
| 67 |
# Firebase Auth integration
|
| 68 |
FIREBASE_AUTH_ENABLED: bool = env_first_bool(
|
| 69 |
["FIREBASE_AUTH_ENABLED", "FIREBASEAUTHENABLED"],
|
backend/app/middleware/auth.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
from fastapi import Depends, HTTPException, status
|
| 2 |
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
|
|
|
| 3 |
from app.utils.auth import decode_token
|
| 4 |
from app.utils.firestore_data import COLL, as_obj, create_doc, first_doc, now_utc, update_doc
|
| 5 |
|
|
@@ -12,6 +13,7 @@ async def get_current_user(
|
|
| 12 |
"""Get current authenticated user"""
|
| 13 |
token = credentials.credentials
|
| 14 |
token_data = decode_token(token)
|
|
|
|
| 15 |
email = token_data.get("email")
|
| 16 |
display_name = token_data.get("name")
|
| 17 |
|
|
@@ -20,11 +22,15 @@ async def get_current_user(
|
|
| 20 |
if user and user.get("updated_at") is None:
|
| 21 |
user["updated_at"] = now_utc()
|
| 22 |
|
|
|
|
|
|
|
|
|
|
| 23 |
if not user and email:
|
| 24 |
inferred_name = display_name or email.split("@")[0]
|
| 25 |
user = create_doc(
|
| 26 |
COLL.users,
|
| 27 |
{
|
|
|
|
| 28 |
"name": inferred_name,
|
| 29 |
"email": email,
|
| 30 |
"password": "",
|
|
@@ -62,7 +68,11 @@ async def get_admin_user(
|
|
| 62 |
current_user = Depends(get_current_user),
|
| 63 |
):
|
| 64 |
"""Verify current user is admin"""
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
raise HTTPException(
|
| 67 |
status_code=status.HTTP_403_FORBIDDEN,
|
| 68 |
detail="Only admins can access this resource",
|
|
|
|
| 1 |
from fastapi import Depends, HTTPException, status
|
| 2 |
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
| 3 |
+
from app.config import settings
|
| 4 |
from app.utils.auth import decode_token
|
| 5 |
from app.utils.firestore_data import COLL, as_obj, create_doc, first_doc, now_utc, update_doc
|
| 6 |
|
|
|
|
| 13 |
"""Get current authenticated user"""
|
| 14 |
token = credentials.credentials
|
| 15 |
token_data = decode_token(token)
|
| 16 |
+
token_sub = token_data.get("sub")
|
| 17 |
email = token_data.get("email")
|
| 18 |
display_name = token_data.get("name")
|
| 19 |
|
|
|
|
| 22 |
if user and user.get("updated_at") is None:
|
| 23 |
user["updated_at"] = now_utc()
|
| 24 |
|
| 25 |
+
if user and token_sub and not user.get("uid"):
|
| 26 |
+
user = update_doc(COLL.users, user["id"], {"uid": token_sub, "updated_at": now_utc()}) or user
|
| 27 |
+
|
| 28 |
if not user and email:
|
| 29 |
inferred_name = display_name or email.split("@")[0]
|
| 30 |
user = create_doc(
|
| 31 |
COLL.users,
|
| 32 |
{
|
| 33 |
+
"uid": token_sub,
|
| 34 |
"name": inferred_name,
|
| 35 |
"email": email,
|
| 36 |
"password": "",
|
|
|
|
| 68 |
current_user = Depends(get_current_user),
|
| 69 |
):
|
| 70 |
"""Verify current user is admin"""
|
| 71 |
+
user_role = (getattr(current_user, "role", "") or "").lower()
|
| 72 |
+
user_email = (getattr(current_user, "email", "") or "").lower()
|
| 73 |
+
admin_email = (settings.ADMIN_EMAIL or "").lower()
|
| 74 |
+
|
| 75 |
+
if user_role != "admin" and user_email != admin_email:
|
| 76 |
raise HTTPException(
|
| 77 |
status_code=status.HTTP_403_FORBIDDEN,
|
| 78 |
detail="Only admins can access this resource",
|
backend/app/routes/dashboard.py
CHANGED
|
@@ -75,20 +75,20 @@ async def get_extended_overview():
|
|
| 75 |
top_performance = list_docs(COLL.performance_logs, sort_key="performance_rating", reverse=True, limit=1)
|
| 76 |
top = top_performance[0] if top_performance else None
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
}
|
| 93 |
|
| 94 |
try:
|
|
|
|
| 75 |
top_performance = list_docs(COLL.performance_logs, sort_key="performance_rating", reverse=True, limit=1)
|
| 76 |
top = top_performance[0] if top_performance else None
|
| 77 |
|
| 78 |
+
return {
|
| 79 |
+
"total_players": total_players,
|
| 80 |
+
"premium_players": premium_players,
|
| 81 |
+
"total_matches": total_matches,
|
| 82 |
+
"total_runs": total_runs,
|
| 83 |
+
"total_wickets": total_wickets,
|
| 84 |
+
"avg_runs_per_match": avg_runs_per_match,
|
| 85 |
+
"premium_ratio": premium_ratio,
|
| 86 |
+
"top_performance": {
|
| 87 |
+
"match_date": top.get("match_date") if top else None,
|
| 88 |
+
"performance_rating": top.get("performance_rating", 0) if top else 0,
|
| 89 |
+
"runs_scored": top.get("runs_scored", 0) if top else 0,
|
| 90 |
+
"wickets_taken": top.get("wickets_taken", 0) if top else 0,
|
| 91 |
+
},
|
| 92 |
}
|
| 93 |
|
| 94 |
try:
|
backend/app/routes/matches.py
CHANGED
|
@@ -17,6 +17,51 @@ from app.utils.logger import log_action
|
|
| 17 |
router = APIRouter(prefix="/matches", tags=["Matches"])
|
| 18 |
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
def ensure_match_editor(match_obj: dict, current_user):
|
| 21 |
if current_user.role == "admin":
|
| 22 |
return
|
|
@@ -252,7 +297,12 @@ async def create_match(payload: MatchCreate, current_user=Depends(get_current_us
|
|
| 252 |
async def list_matches(current_user=Depends(get_current_user)):
|
| 253 |
_ = current_user
|
| 254 |
matches = list_docs(COLL.matches, sort_key="created_at", reverse=True, limit=50)
|
| 255 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
|
| 257 |
|
| 258 |
@router.get("/{match_id}", response_model=MatchDetailResponse)
|
|
|
|
| 17 |
router = APIRouter(prefix="/matches", tags=["Matches"])
|
| 18 |
|
| 19 |
|
| 20 |
+
def _normalize_match_for_response(row: dict) -> dict | None:
|
| 21 |
+
"""Normalize a match row to MatchResponse shape; skip incompatible legacy docs."""
|
| 22 |
+
try:
|
| 23 |
+
match_id = int(row.get("id"))
|
| 24 |
+
except (TypeError, ValueError):
|
| 25 |
+
return None
|
| 26 |
+
|
| 27 |
+
title = row.get("title")
|
| 28 |
+
created_by_id = row.get("created_by_id")
|
| 29 |
+
team_a_name = row.get("team_a_name")
|
| 30 |
+
team_b_name = row.get("team_b_name")
|
| 31 |
+
overs_per_innings = row.get("overs_per_innings")
|
| 32 |
+
status = row.get("status")
|
| 33 |
+
current_innings = row.get("current_innings")
|
| 34 |
+
created_at = row.get("created_at") or row.get("createdAt")
|
| 35 |
+
|
| 36 |
+
# Legacy docs from unrelated schema (teamA/teamB/scoreState, etc.) are ignored.
|
| 37 |
+
if not all(
|
| 38 |
+
[
|
| 39 |
+
title,
|
| 40 |
+
created_by_id is not None,
|
| 41 |
+
team_a_name,
|
| 42 |
+
team_b_name,
|
| 43 |
+
overs_per_innings is not None,
|
| 44 |
+
status,
|
| 45 |
+
current_innings is not None,
|
| 46 |
+
created_at is not None,
|
| 47 |
+
]
|
| 48 |
+
):
|
| 49 |
+
return None
|
| 50 |
+
|
| 51 |
+
return {
|
| 52 |
+
"id": match_id,
|
| 53 |
+
"title": str(title),
|
| 54 |
+
"created_by_id": created_by_id,
|
| 55 |
+
"team_a_name": str(team_a_name),
|
| 56 |
+
"team_b_name": str(team_b_name),
|
| 57 |
+
"overs_per_innings": int(overs_per_innings),
|
| 58 |
+
"status": str(status).lower(),
|
| 59 |
+
"current_innings": int(current_innings),
|
| 60 |
+
"batting_team": row.get("batting_team"),
|
| 61 |
+
"created_at": created_at,
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
def ensure_match_editor(match_obj: dict, current_user):
|
| 66 |
if current_user.role == "admin":
|
| 67 |
return
|
|
|
|
| 297 |
async def list_matches(current_user=Depends(get_current_user)):
|
| 298 |
_ = current_user
|
| 299 |
matches = list_docs(COLL.matches, sort_key="created_at", reverse=True, limit=50)
|
| 300 |
+
normalized = []
|
| 301 |
+
for row in matches:
|
| 302 |
+
item = _normalize_match_for_response(row)
|
| 303 |
+
if item is not None:
|
| 304 |
+
normalized.append(as_obj(item))
|
| 305 |
+
return normalized
|
| 306 |
|
| 307 |
|
| 308 |
@router.get("/{match_id}", response_model=MatchDetailResponse)
|
backend/app/routes/performance.py
CHANGED
|
@@ -9,8 +9,22 @@ from app.utils.logger import log_action
|
|
| 9 |
router = APIRouter(prefix="/performance", tags=["Performance"])
|
| 10 |
|
| 11 |
|
| 12 |
-
def
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
matches = len(logs)
|
| 16 |
runs = sum(int(log.get("runs_scored", 0)) for log in logs)
|
|
@@ -141,7 +155,7 @@ async def get_my_performance_logs(
|
|
| 141 |
):
|
| 142 |
logs = list_docs(
|
| 143 |
COLL.performance_logs,
|
| 144 |
-
predicate=lambda row:
|
| 145 |
sort_key="match_date",
|
| 146 |
reverse=True,
|
| 147 |
offset=skip,
|
|
@@ -158,7 +172,7 @@ async def get_my_match_history(
|
|
| 158 |
):
|
| 159 |
logs = list_docs(
|
| 160 |
COLL.performance_logs,
|
| 161 |
-
predicate=lambda row:
|
| 162 |
sort_key="match_date",
|
| 163 |
reverse=True,
|
| 164 |
offset=skip,
|
|
@@ -203,7 +217,7 @@ async def update_performance_log(
|
|
| 203 |
):
|
| 204 |
perf_log = first_doc(
|
| 205 |
COLL.performance_logs,
|
| 206 |
-
predicate=lambda row: row.get("id")
|
| 207 |
)
|
| 208 |
|
| 209 |
if not perf_log:
|
|
@@ -230,7 +244,7 @@ async def delete_performance_log(
|
|
| 230 |
):
|
| 231 |
perf_log = first_doc(
|
| 232 |
COLL.performance_logs,
|
| 233 |
-
predicate=lambda row: row.get("id")
|
| 234 |
)
|
| 235 |
|
| 236 |
if not perf_log:
|
|
@@ -249,13 +263,13 @@ async def get_player_performance_logs(
|
|
| 249 |
skip: int = 0,
|
| 250 |
limit: int = 20,
|
| 251 |
):
|
| 252 |
-
player = first_doc(COLL.users, predicate=lambda row:
|
| 253 |
if not player:
|
| 254 |
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Player not found")
|
| 255 |
|
| 256 |
logs = list_docs(
|
| 257 |
COLL.performance_logs,
|
| 258 |
-
predicate=lambda row:
|
| 259 |
sort_key="match_date",
|
| 260 |
reverse=True,
|
| 261 |
offset=skip,
|
|
@@ -267,7 +281,7 @@ async def get_player_performance_logs(
|
|
| 267 |
|
| 268 |
@router.get("/stats/{player_id}")
|
| 269 |
async def get_player_stats(player_id: Union[int, str]):
|
| 270 |
-
player = first_doc(COLL.users, predicate=lambda row:
|
| 271 |
|
| 272 |
if not player:
|
| 273 |
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Player not found")
|
|
@@ -287,14 +301,14 @@ async def get_player_stats(player_id: Union[int, str]):
|
|
| 287 |
|
| 288 |
@router.get("/ai-insights/{player_id}")
|
| 289 |
async def get_player_ai_insights(player_id: Union[int, str]):
|
| 290 |
-
player = first_doc(COLL.users, predicate=lambda row:
|
| 291 |
|
| 292 |
if not player:
|
| 293 |
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Player not found")
|
| 294 |
|
| 295 |
logs = list_docs(
|
| 296 |
COLL.performance_logs,
|
| 297 |
-
predicate=lambda row:
|
| 298 |
sort_key="match_date",
|
| 299 |
reverse=True,
|
| 300 |
limit=10,
|
|
|
|
| 9 |
router = APIRouter(prefix="/performance", tags=["Performance"])
|
| 10 |
|
| 11 |
|
| 12 |
+
def _same_id(left, right) -> bool:
|
| 13 |
+
if left is None or right is None:
|
| 14 |
+
return False
|
| 15 |
+
return str(left) == str(right)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _matches_user_identity(row: dict, value: Union[int, str]) -> bool:
|
| 19 |
+
return _same_id(row.get("id"), value) or _same_id(row.get("uid"), value)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _matches_log_user(log_row: dict, value: Union[int, str]) -> bool:
|
| 23 |
+
return _same_id(log_row.get("user_id"), value) or _same_id(log_row.get("uid"), value)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def recalculate_user_career_stats(user_id: Union[int, str]) -> None:
|
| 27 |
+
logs = list_docs(COLL.performance_logs, predicate=lambda row: _matches_log_user(row, user_id))
|
| 28 |
|
| 29 |
matches = len(logs)
|
| 30 |
runs = sum(int(log.get("runs_scored", 0)) for log in logs)
|
|
|
|
| 155 |
):
|
| 156 |
logs = list_docs(
|
| 157 |
COLL.performance_logs,
|
| 158 |
+
predicate=lambda row: _matches_log_user(row, current_user.id),
|
| 159 |
sort_key="match_date",
|
| 160 |
reverse=True,
|
| 161 |
offset=skip,
|
|
|
|
| 172 |
):
|
| 173 |
logs = list_docs(
|
| 174 |
COLL.performance_logs,
|
| 175 |
+
predicate=lambda row: _matches_log_user(row, current_user.id),
|
| 176 |
sort_key="match_date",
|
| 177 |
reverse=True,
|
| 178 |
offset=skip,
|
|
|
|
| 217 |
):
|
| 218 |
perf_log = first_doc(
|
| 219 |
COLL.performance_logs,
|
| 220 |
+
predicate=lambda row: _same_id(row.get("id"), log_id) and _same_id(row.get("user_id"), current_user.id),
|
| 221 |
)
|
| 222 |
|
| 223 |
if not perf_log:
|
|
|
|
| 244 |
):
|
| 245 |
perf_log = first_doc(
|
| 246 |
COLL.performance_logs,
|
| 247 |
+
predicate=lambda row: _same_id(row.get("id"), log_id) and _same_id(row.get("user_id"), current_user.id),
|
| 248 |
)
|
| 249 |
|
| 250 |
if not perf_log:
|
|
|
|
| 263 |
skip: int = 0,
|
| 264 |
limit: int = 20,
|
| 265 |
):
|
| 266 |
+
player = first_doc(COLL.users, predicate=lambda row: _matches_user_identity(row, player_id))
|
| 267 |
if not player:
|
| 268 |
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Player not found")
|
| 269 |
|
| 270 |
logs = list_docs(
|
| 271 |
COLL.performance_logs,
|
| 272 |
+
predicate=lambda row: _matches_log_user(row, player_id),
|
| 273 |
sort_key="match_date",
|
| 274 |
reverse=True,
|
| 275 |
offset=skip,
|
|
|
|
| 281 |
|
| 282 |
@router.get("/stats/{player_id}")
|
| 283 |
async def get_player_stats(player_id: Union[int, str]):
|
| 284 |
+
player = first_doc(COLL.users, predicate=lambda row: _matches_user_identity(row, player_id))
|
| 285 |
|
| 286 |
if not player:
|
| 287 |
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Player not found")
|
|
|
|
| 301 |
|
| 302 |
@router.get("/ai-insights/{player_id}")
|
| 303 |
async def get_player_ai_insights(player_id: Union[int, str]):
|
| 304 |
+
player = first_doc(COLL.users, predicate=lambda row: _matches_user_identity(row, player_id))
|
| 305 |
|
| 306 |
if not player:
|
| 307 |
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Player not found")
|
| 308 |
|
| 309 |
logs = list_docs(
|
| 310 |
COLL.performance_logs,
|
| 311 |
+
predicate=lambda row: _matches_log_user(row, player_id),
|
| 312 |
sort_key="match_date",
|
| 313 |
reverse=True,
|
| 314 |
limit=10,
|
backend/app/routes/players.py
CHANGED
|
@@ -8,6 +8,16 @@ from app.utils.logger import log_action
|
|
| 8 |
router = APIRouter(prefix="/players", tags=["Players"])
|
| 9 |
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
def _check_and_downgrade_premium(user: dict) -> dict:
|
| 12 |
from datetime import datetime, timezone
|
| 13 |
|
|
@@ -35,7 +45,7 @@ def _check_and_downgrade_premium(user: dict) -> dict:
|
|
| 35 |
@router.get("/me", response_model=UserResponse)
|
| 36 |
async def get_current_player(current_user=Depends(get_current_user)):
|
| 37 |
"""Get current logged-in player's profile"""
|
| 38 |
-
user = first_doc(COLL.users, predicate=lambda row:
|
| 39 |
if not user:
|
| 40 |
raise HTTPException(status_code=404, detail="Player not found")
|
| 41 |
user = _check_and_downgrade_premium(user)
|
|
@@ -73,7 +83,7 @@ async def update_career_stats(
|
|
| 73 |
):
|
| 74 |
"""Update current player's career statistics"""
|
| 75 |
|
| 76 |
-
user = first_doc(COLL.users, predicate=lambda row:
|
| 77 |
if not user:
|
| 78 |
raise HTTPException(status_code=404, detail="Player not found")
|
| 79 |
|
|
@@ -184,7 +194,7 @@ async def get_top_wicket_takers(limit: int = 10):
|
|
| 184 |
async def get_player(player_id: Union[int, str]):
|
| 185 |
"""Get player profile by ID"""
|
| 186 |
|
| 187 |
-
player = first_doc(COLL.users, predicate=lambda row:
|
| 188 |
|
| 189 |
if not player:
|
| 190 |
raise HTTPException(
|
|
|
|
| 8 |
router = APIRouter(prefix="/players", tags=["Players"])
|
| 9 |
|
| 10 |
|
| 11 |
+
def _same_id(left, right) -> bool:
|
| 12 |
+
if left is None or right is None:
|
| 13 |
+
return False
|
| 14 |
+
return str(left) == str(right)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _matches_user_identity(row: dict, value: Union[int, str]) -> bool:
|
| 18 |
+
return _same_id(row.get("id"), value) or _same_id(row.get("uid"), value)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
def _check_and_downgrade_premium(user: dict) -> dict:
|
| 22 |
from datetime import datetime, timezone
|
| 23 |
|
|
|
|
| 45 |
@router.get("/me", response_model=UserResponse)
|
| 46 |
async def get_current_player(current_user=Depends(get_current_user)):
|
| 47 |
"""Get current logged-in player's profile"""
|
| 48 |
+
user = first_doc(COLL.users, predicate=lambda row: _matches_user_identity(row, current_user.id))
|
| 49 |
if not user:
|
| 50 |
raise HTTPException(status_code=404, detail="Player not found")
|
| 51 |
user = _check_and_downgrade_premium(user)
|
|
|
|
| 83 |
):
|
| 84 |
"""Update current player's career statistics"""
|
| 85 |
|
| 86 |
+
user = first_doc(COLL.users, predicate=lambda row: _matches_user_identity(row, current_user.id))
|
| 87 |
if not user:
|
| 88 |
raise HTTPException(status_code=404, detail="Player not found")
|
| 89 |
|
|
|
|
| 194 |
async def get_player(player_id: Union[int, str]):
|
| 195 |
"""Get player profile by ID"""
|
| 196 |
|
| 197 |
+
player = first_doc(COLL.users, predicate=lambda row: _matches_user_identity(row, player_id))
|
| 198 |
|
| 199 |
if not player:
|
| 200 |
raise HTTPException(
|
backend/app/utils/firestore_data.py
CHANGED
|
@@ -5,11 +5,11 @@ from datetime import datetime, timezone
|
|
| 5 |
from types import SimpleNamespace
|
| 6 |
from typing import Any, Callable
|
| 7 |
|
| 8 |
-
import
|
| 9 |
-
from
|
|
|
|
| 10 |
|
| 11 |
from app.config import settings
|
| 12 |
-
from app.utils.auth import _init_firebase_if_needed
|
| 13 |
|
| 14 |
|
| 15 |
@dataclass
|
|
@@ -27,57 +27,107 @@ class CollectionNames:
|
|
| 27 |
|
| 28 |
COLL = CollectionNames()
|
| 29 |
|
|
|
|
| 30 |
|
| 31 |
-
def _client():
|
| 32 |
-
if not settings.FIREBASE_AUTH_ENABLED:
|
| 33 |
-
raise RuntimeError("FIREBASE_AUTH_ENABLED must be True for Firestore mode")
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
raise RuntimeError("Firebase Admin is not initialized. Check service account config.")
|
| 38 |
|
| 39 |
-
return firestore.client()
|
| 40 |
|
|
|
|
|
|
|
| 41 |
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
return f"counter::{collection}"
|
| 44 |
|
| 45 |
|
| 46 |
def next_int_id(collection: str) -> int:
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
ref.set({"value": new_value}, merge=True)
|
| 55 |
-
return new_value
|
| 56 |
|
| 57 |
|
| 58 |
def now_utc() -> datetime:
|
| 59 |
return datetime.now(timezone.utc)
|
| 60 |
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
def create_doc(collection: str, data: dict[str, Any], doc_id: str | None = None) -> dict[str, Any]:
|
| 63 |
-
|
| 64 |
-
payload = dict(data)
|
|
|
|
| 65 |
if doc_id is None:
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
| 69 |
return payload
|
| 70 |
|
| 71 |
|
| 72 |
def get_doc(collection: str, doc_id: str | int) -> dict[str, Any] | None:
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
return None
|
| 77 |
-
|
| 78 |
-
if "id" not in data:
|
| 79 |
-
data["id"] = int(str(doc_id)) if str(doc_id).isdigit() else str(doc_id)
|
| 80 |
-
return data
|
| 81 |
|
| 82 |
|
| 83 |
def update_doc(collection: str, doc_id: str | int, patch: dict[str, Any]) -> dict[str, Any] | None:
|
|
@@ -85,18 +135,24 @@ def update_doc(collection: str, doc_id: str | int, patch: dict[str, Any]) -> dic
|
|
| 85 |
if not existing:
|
| 86 |
return None
|
| 87 |
merged = dict(existing)
|
| 88 |
-
merged.update(patch)
|
| 89 |
create_doc(collection, merged, str(doc_id))
|
| 90 |
return merged
|
| 91 |
|
| 92 |
|
| 93 |
def delete_doc(collection: str, doc_id: str | int) -> bool:
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
return False
|
| 98 |
-
|
| 99 |
-
|
|
|
|
| 100 |
|
| 101 |
def _parse_datetime(value: Any) -> datetime | None:
|
| 102 |
"""Parse a value to datetime if it's a datetime string. Always returns timezone-aware UTC."""
|
|
@@ -150,18 +206,10 @@ def list_docs(
|
|
| 150 |
limit: int | None = None,
|
| 151 |
offset: int = 0,
|
| 152 |
) -> list[dict[str, Any]]:
|
| 153 |
-
|
| 154 |
rows: list[dict[str, Any]] = []
|
| 155 |
-
for
|
| 156 |
-
row =
|
| 157 |
-
doc_id = snap.id
|
| 158 |
-
|
| 159 |
-
# Always track the actual Firestore document ID
|
| 160 |
-
row["_doc_id"] = doc_id
|
| 161 |
-
|
| 162 |
-
# If no id field, use the Firestore document ID
|
| 163 |
-
if "id" not in row:
|
| 164 |
-
row["id"] = int(doc_id) if doc_id.isdigit() else doc_id
|
| 165 |
if predicate and not predicate(row):
|
| 166 |
continue
|
| 167 |
rows.append(row)
|
|
@@ -193,9 +241,9 @@ def as_obj(data: dict[str, Any]) -> Any:
|
|
| 193 |
def normalize_user(user: dict[str, Any]) -> dict[str, Any]:
|
| 194 |
"""Ensure all required user fields exist with defaults."""
|
| 195 |
created_at = user.get("created_at") or user.get("createdAt") or now_utc()
|
| 196 |
-
|
| 197 |
-
#
|
| 198 |
-
user_id = user.get("
|
| 199 |
|
| 200 |
defaults = {
|
| 201 |
"id": user_id,
|
|
|
|
| 5 |
from types import SimpleNamespace
|
| 6 |
from typing import Any, Callable
|
| 7 |
|
| 8 |
+
from bson import ObjectId
|
| 9 |
+
from pymongo import MongoClient, ReturnDocument
|
| 10 |
+
from pymongo.collection import Collection
|
| 11 |
|
| 12 |
from app.config import settings
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
@dataclass
|
|
|
|
| 27 |
|
| 28 |
COLL = CollectionNames()
|
| 29 |
|
| 30 |
+
_mongo_client: MongoClient | None = None
|
| 31 |
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
+
def _mongo_db_name() -> str:
|
| 34 |
+
return settings.MONGODB_DB_NAME or "ssc"
|
|
|
|
| 35 |
|
|
|
|
| 36 |
|
| 37 |
+
def _client() -> MongoClient:
|
| 38 |
+
global _mongo_client
|
| 39 |
|
| 40 |
+
if _mongo_client is not None:
|
| 41 |
+
return _mongo_client
|
| 42 |
+
|
| 43 |
+
if not settings.MONGODB_URI:
|
| 44 |
+
raise RuntimeError("MONGODB_URI is not configured")
|
| 45 |
+
|
| 46 |
+
_mongo_client = MongoClient(settings.MONGODB_URI, tz_aware=True)
|
| 47 |
+
return _mongo_client
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _collection(name: str) -> Collection:
|
| 51 |
+
db = _client()[_mongo_db_name()]
|
| 52 |
+
return db[name]
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _meta_collection() -> Collection:
|
| 56 |
+
db = _client()[_mongo_db_name()]
|
| 57 |
+
return db["_meta"]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _counter_doc_key(collection: str) -> str:
|
| 61 |
return f"counter::{collection}"
|
| 62 |
|
| 63 |
|
| 64 |
def next_int_id(collection: str) -> int:
|
| 65 |
+
doc = _meta_collection().find_one_and_update(
|
| 66 |
+
{"key": _counter_doc_key(collection)},
|
| 67 |
+
{"$inc": {"value": 1}},
|
| 68 |
+
upsert=True,
|
| 69 |
+
return_document=ReturnDocument.AFTER,
|
| 70 |
+
)
|
| 71 |
+
return int((doc or {}).get("value", 1))
|
|
|
|
|
|
|
| 72 |
|
| 73 |
|
| 74 |
def now_utc() -> datetime:
|
| 75 |
return datetime.now(timezone.utc)
|
| 76 |
|
| 77 |
|
| 78 |
+
def _coerce_doc_id(value: str | int) -> str | int:
|
| 79 |
+
value_str = str(value)
|
| 80 |
+
return int(value_str) if value_str.isdigit() else value_str
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _serialize_for_mongo(value: Any) -> Any:
|
| 84 |
+
if isinstance(value, datetime):
|
| 85 |
+
return value if value.tzinfo is not None else value.replace(tzinfo=timezone.utc)
|
| 86 |
+
return value
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def _prepare_payload(data: dict[str, Any]) -> dict[str, Any]:
|
| 90 |
+
payload: dict[str, Any] = {}
|
| 91 |
+
for key, value in data.items():
|
| 92 |
+
payload[key] = _serialize_for_mongo(value)
|
| 93 |
+
return payload
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _row_from_doc(doc: dict[str, Any]) -> dict[str, Any]:
|
| 97 |
+
row = dict(doc)
|
| 98 |
+
mongo_id = row.pop("_id", None)
|
| 99 |
+
if mongo_id is not None:
|
| 100 |
+
row["_mongo_id"] = str(mongo_id)
|
| 101 |
+
if "id" not in row:
|
| 102 |
+
row["id"] = row.get("_mongo_id", "")
|
| 103 |
+
row.setdefault("_doc_id", row.get("id"))
|
| 104 |
+
return row
|
| 105 |
+
|
| 106 |
+
|
| 107 |
def create_doc(collection: str, data: dict[str, Any], doc_id: str | None = None) -> dict[str, Any]:
|
| 108 |
+
coll = _collection(collection)
|
| 109 |
+
payload = _prepare_payload(dict(data))
|
| 110 |
+
|
| 111 |
if doc_id is None:
|
| 112 |
+
payload["id"] = payload.get("id") or next_int_id(collection)
|
| 113 |
+
else:
|
| 114 |
+
payload["id"] = _coerce_doc_id(doc_id)
|
| 115 |
+
|
| 116 |
+
coll.update_one({"id": payload["id"]}, {"$set": payload}, upsert=True)
|
| 117 |
+
payload.setdefault("_doc_id", payload["id"])
|
| 118 |
return payload
|
| 119 |
|
| 120 |
|
| 121 |
def get_doc(collection: str, doc_id: str | int) -> dict[str, Any] | None:
|
| 122 |
+
coll = _collection(collection)
|
| 123 |
+
coerced = _coerce_doc_id(doc_id)
|
| 124 |
+
|
| 125 |
+
doc = coll.find_one({"id": coerced})
|
| 126 |
+
if doc is None and ObjectId.is_valid(str(doc_id)):
|
| 127 |
+
doc = coll.find_one({"_id": ObjectId(str(doc_id))})
|
| 128 |
+
if doc is None:
|
| 129 |
return None
|
| 130 |
+
return _row_from_doc(doc)
|
|
|
|
|
|
|
|
|
|
| 131 |
|
| 132 |
|
| 133 |
def update_doc(collection: str, doc_id: str | int, patch: dict[str, Any]) -> dict[str, Any] | None:
|
|
|
|
| 135 |
if not existing:
|
| 136 |
return None
|
| 137 |
merged = dict(existing)
|
| 138 |
+
merged.update(_prepare_payload(patch))
|
| 139 |
create_doc(collection, merged, str(doc_id))
|
| 140 |
return merged
|
| 141 |
|
| 142 |
|
| 143 |
def delete_doc(collection: str, doc_id: str | int) -> bool:
|
| 144 |
+
coll = _collection(collection)
|
| 145 |
+
coerced = _coerce_doc_id(doc_id)
|
| 146 |
+
|
| 147 |
+
result = coll.delete_one({"id": coerced})
|
| 148 |
+
if result.deleted_count:
|
| 149 |
+
return True
|
| 150 |
+
|
| 151 |
+
if not ObjectId.is_valid(str(doc_id)):
|
| 152 |
return False
|
| 153 |
+
|
| 154 |
+
oid_result = coll.delete_one({"_id": ObjectId(str(doc_id))})
|
| 155 |
+
return bool(oid_result.deleted_count)
|
| 156 |
|
| 157 |
def _parse_datetime(value: Any) -> datetime | None:
|
| 158 |
"""Parse a value to datetime if it's a datetime string. Always returns timezone-aware UTC."""
|
|
|
|
| 206 |
limit: int | None = None,
|
| 207 |
offset: int = 0,
|
| 208 |
) -> list[dict[str, Any]]:
|
| 209 |
+
coll = _collection(collection)
|
| 210 |
rows: list[dict[str, Any]] = []
|
| 211 |
+
for doc in coll.find({}):
|
| 212 |
+
row = _row_from_doc(doc)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
if predicate and not predicate(row):
|
| 214 |
continue
|
| 215 |
rows.append(row)
|
|
|
|
| 241 |
def normalize_user(user: dict[str, Any]) -> dict[str, Any]:
|
| 242 |
"""Ensure all required user fields exist with defaults."""
|
| 243 |
created_at = user.get("created_at") or user.get("createdAt") or now_utc()
|
| 244 |
+
|
| 245 |
+
# Keep canonical numeric/string user id stable for API routes and links.
|
| 246 |
+
user_id = user.get("id") if user.get("id") is not None else user.get("uid", "")
|
| 247 |
|
| 248 |
defaults = {
|
| 249 |
"id": user_id,
|
backend/migrate_firestore_to_mongo.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Migrate Firebase Auth users and Firestore collections into MongoDB.
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
python migrate_firestore_to_mongo.py
|
| 6 |
+
python migrate_firestore_to_mongo.py --email user@example.com
|
| 7 |
+
python migrate_firestore_to_mongo.py --collections users,performance_logs
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
from datetime import datetime, timezone
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from typing import Any
|
| 18 |
+
|
| 19 |
+
import firebase_admin
|
| 20 |
+
from firebase_admin import auth, credentials, firestore
|
| 21 |
+
from dotenv import load_dotenv
|
| 22 |
+
from pymongo import MongoClient
|
| 23 |
+
|
| 24 |
+
DEFAULT_COLLECTIONS = [
|
| 25 |
+
"users",
|
| 26 |
+
"payments",
|
| 27 |
+
"performance_logs",
|
| 28 |
+
"notifications",
|
| 29 |
+
"finance_transactions",
|
| 30 |
+
"admin_chat_messages",
|
| 31 |
+
"matches",
|
| 32 |
+
"match_players",
|
| 33 |
+
"ball_events",
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def parse_args() -> argparse.Namespace:
|
| 38 |
+
parser = argparse.ArgumentParser(
|
| 39 |
+
description="Migrate Firebase Auth and Firestore data to MongoDB",
|
| 40 |
+
)
|
| 41 |
+
parser.add_argument(
|
| 42 |
+
"--collections",
|
| 43 |
+
default=",".join(DEFAULT_COLLECTIONS),
|
| 44 |
+
help="Comma-separated Firestore collection names to migrate",
|
| 45 |
+
)
|
| 46 |
+
parser.add_argument(
|
| 47 |
+
"--email",
|
| 48 |
+
default="",
|
| 49 |
+
help="Migrate only this user by email (for users and auth users)",
|
| 50 |
+
)
|
| 51 |
+
parser.add_argument(
|
| 52 |
+
"--dry-run",
|
| 53 |
+
action="store_true",
|
| 54 |
+
help="Show what would be migrated without writing to MongoDB",
|
| 55 |
+
)
|
| 56 |
+
return parser.parse_args()
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def load_environment(script_dir: Path) -> None:
|
| 60 |
+
env_path = script_dir / ".env"
|
| 61 |
+
if env_path.exists():
|
| 62 |
+
load_dotenv(env_path)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def init_firebase(script_dir: Path) -> None:
|
| 66 |
+
if firebase_admin._apps:
|
| 67 |
+
return
|
| 68 |
+
|
| 69 |
+
service_account_json = os.getenv("FIREBASE_SERVICE_ACCOUNT_JSON", "").strip()
|
| 70 |
+
service_account_path = os.getenv("FIREBASE_SERVICE_ACCOUNT_PATH", "firebase-service-account.json").strip()
|
| 71 |
+
|
| 72 |
+
if service_account_json:
|
| 73 |
+
cred = credentials.Certificate(json.loads(service_account_json))
|
| 74 |
+
firebase_admin.initialize_app(cred)
|
| 75 |
+
return
|
| 76 |
+
|
| 77 |
+
cred_path = Path(service_account_path)
|
| 78 |
+
if not cred_path.is_absolute():
|
| 79 |
+
cred_path = script_dir / cred_path
|
| 80 |
+
|
| 81 |
+
if not cred_path.exists():
|
| 82 |
+
raise FileNotFoundError(f"Service account file not found: {cred_path}")
|
| 83 |
+
|
| 84 |
+
cred = credentials.Certificate(str(cred_path))
|
| 85 |
+
firebase_admin.initialize_app(cred)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def get_mongo() -> tuple[MongoClient, str]:
|
| 89 |
+
mongo_uri = os.getenv("MONGODB_URI", "").strip()
|
| 90 |
+
db_name = os.getenv("MONGODB_DB_NAME", "ssc").strip() or "ssc"
|
| 91 |
+
|
| 92 |
+
if not mongo_uri:
|
| 93 |
+
raise RuntimeError("MONGODB_URI is required in backend/.env")
|
| 94 |
+
|
| 95 |
+
client = MongoClient(mongo_uri, tz_aware=True, serverSelectionTimeoutMS=10000)
|
| 96 |
+
client.admin.command("ping")
|
| 97 |
+
return client, db_name
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def to_serializable(value: Any) -> Any:
|
| 101 |
+
if isinstance(value, datetime):
|
| 102 |
+
return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
|
| 103 |
+
|
| 104 |
+
if hasattr(value, "path"):
|
| 105 |
+
return str(value.path)
|
| 106 |
+
|
| 107 |
+
if isinstance(value, dict):
|
| 108 |
+
return {k: to_serializable(v) for k, v in value.items()}
|
| 109 |
+
|
| 110 |
+
if isinstance(value, list):
|
| 111 |
+
return [to_serializable(v) for v in value]
|
| 112 |
+
|
| 113 |
+
return value
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def migrate_auth_users(mongo_db, email_filter: str, dry_run: bool) -> int:
|
| 117 |
+
auth_collection = mongo_db["firebase_auth_users"]
|
| 118 |
+
users_collection = mongo_db["users"]
|
| 119 |
+
|
| 120 |
+
migrated = 0
|
| 121 |
+
for user in auth.list_users().iterate_all():
|
| 122 |
+
if email_filter and user.email != email_filter:
|
| 123 |
+
continue
|
| 124 |
+
|
| 125 |
+
payload = {
|
| 126 |
+
"uid": user.uid,
|
| 127 |
+
"email": user.email,
|
| 128 |
+
"display_name": user.display_name,
|
| 129 |
+
"phone_number": user.phone_number,
|
| 130 |
+
"email_verified": user.email_verified,
|
| 131 |
+
"disabled": user.disabled,
|
| 132 |
+
"provider_data": [
|
| 133 |
+
{
|
| 134 |
+
"uid": p.uid,
|
| 135 |
+
"provider_id": p.provider_id,
|
| 136 |
+
"email": p.email,
|
| 137 |
+
"display_name": p.display_name,
|
| 138 |
+
}
|
| 139 |
+
for p in (user.provider_data or [])
|
| 140 |
+
],
|
| 141 |
+
"created_at": datetime.fromtimestamp(user.user_metadata.creation_timestamp / 1000, tz=timezone.utc)
|
| 142 |
+
if user.user_metadata and user.user_metadata.creation_timestamp
|
| 143 |
+
else None,
|
| 144 |
+
"last_sign_in_at": datetime.fromtimestamp(user.user_metadata.last_sign_in_timestamp / 1000, tz=timezone.utc)
|
| 145 |
+
if user.user_metadata and user.user_metadata.last_sign_in_timestamp
|
| 146 |
+
else None,
|
| 147 |
+
"source": "firebase_auth",
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
if not dry_run:
|
| 151 |
+
auth_collection.update_one({"uid": user.uid}, {"$set": payload}, upsert=True)
|
| 152 |
+
|
| 153 |
+
if user.email:
|
| 154 |
+
users_collection.update_one(
|
| 155 |
+
{"email": user.email},
|
| 156 |
+
{"$set": {"uid": user.uid, "firebase_email_verified": user.email_verified}},
|
| 157 |
+
upsert=False,
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
migrated += 1
|
| 161 |
+
|
| 162 |
+
return migrated
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def migrate_firestore_collections(mongo_db, collections: list[str], email_filter: str, dry_run: bool) -> dict[str, int]:
|
| 166 |
+
db = firestore.client()
|
| 167 |
+
stats: dict[str, int] = {}
|
| 168 |
+
|
| 169 |
+
for collection_name in collections:
|
| 170 |
+
target = mongo_db[collection_name]
|
| 171 |
+
count = 0
|
| 172 |
+
|
| 173 |
+
for snap in db.collection(collection_name).stream():
|
| 174 |
+
data = snap.to_dict() or {}
|
| 175 |
+
payload = to_serializable(data)
|
| 176 |
+
|
| 177 |
+
if "id" not in payload:
|
| 178 |
+
payload["id"] = int(snap.id) if snap.id.isdigit() else snap.id
|
| 179 |
+
|
| 180 |
+
payload["_doc_id"] = snap.id
|
| 181 |
+
payload["_source"] = "firestore"
|
| 182 |
+
|
| 183 |
+
if email_filter and collection_name == "users" and payload.get("email") != email_filter:
|
| 184 |
+
continue
|
| 185 |
+
|
| 186 |
+
if not dry_run:
|
| 187 |
+
target.update_one({"id": payload["id"]}, {"$set": payload}, upsert=True)
|
| 188 |
+
|
| 189 |
+
count += 1
|
| 190 |
+
|
| 191 |
+
stats[collection_name] = count
|
| 192 |
+
|
| 193 |
+
return stats
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def main() -> None:
|
| 197 |
+
args = parse_args()
|
| 198 |
+
script_dir = Path(__file__).resolve().parent
|
| 199 |
+
|
| 200 |
+
load_environment(script_dir)
|
| 201 |
+
init_firebase(script_dir)
|
| 202 |
+
mongo_client, db_name = get_mongo()
|
| 203 |
+
|
| 204 |
+
mongo_db = mongo_client[db_name]
|
| 205 |
+
collections = [item.strip() for item in args.collections.split(",") if item.strip()]
|
| 206 |
+
|
| 207 |
+
print("=" * 72)
|
| 208 |
+
print("FIRESTORE -> MONGODB MIGRATION")
|
| 209 |
+
print("=" * 72)
|
| 210 |
+
print(f"Mongo DB: {db_name}")
|
| 211 |
+
print(f"Collections: {', '.join(collections)}")
|
| 212 |
+
if args.email:
|
| 213 |
+
print(f"Email filter: {args.email}")
|
| 214 |
+
print(f"Dry run: {args.dry_run}")
|
| 215 |
+
|
| 216 |
+
auth_count = migrate_auth_users(mongo_db, args.email, args.dry_run)
|
| 217 |
+
collection_stats = migrate_firestore_collections(mongo_db, collections, args.email, args.dry_run)
|
| 218 |
+
|
| 219 |
+
print("\nMigration complete")
|
| 220 |
+
print("-" * 72)
|
| 221 |
+
print(f"Firebase Auth users migrated: {auth_count}")
|
| 222 |
+
for name, count in collection_stats.items():
|
| 223 |
+
print(f"Firestore collection {name}: {count} docs")
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
if __name__ == "__main__":
|
| 227 |
+
main()
|
backend/requirements.txt
CHANGED
|
@@ -12,3 +12,4 @@ python-multipart==0.0.6
|
|
| 12 |
slowapi==0.1.9
|
| 13 |
pytz==2023.3
|
| 14 |
firebase-admin==6.8.0
|
|
|
|
|
|
| 12 |
slowapi==0.1.9
|
| 13 |
pytz==2023.3
|
| 14 |
firebase-admin==6.8.0
|
| 15 |
+
pymongo[srv]==4.10.1
|
backend/tempCodeRunnerFile.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Password@123
|
frontend/public/env.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
window.__ENV__ = window.__ENV__ || {};
|
frontend/public/service-worker.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
const CACHE_NAME = 'ssc-app-
|
| 2 |
const urlsToCache = [
|
| 3 |
'/',
|
| 4 |
'/index.html',
|
|
@@ -44,6 +44,12 @@ self.addEventListener('fetch', (event) => {
|
|
| 44 |
const { request } = event;
|
| 45 |
const url = new URL(request.url);
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
// Skip cross-origin requests and non-GET requests
|
| 48 |
if (url.origin !== location.origin || request.method !== 'GET') {
|
| 49 |
return;
|
|
|
|
| 1 |
+
const CACHE_NAME = 'ssc-app-v2';
|
| 2 |
const urlsToCache = [
|
| 3 |
'/',
|
| 4 |
'/index.html',
|
|
|
|
| 44 |
const { request } = event;
|
| 45 |
const url = new URL(request.url);
|
| 46 |
|
| 47 |
+
// Runtime env file must always come fresh and should never be cached.
|
| 48 |
+
if (url.pathname === '/env.js') {
|
| 49 |
+
event.respondWith(fetch(request, { cache: 'no-store' }));
|
| 50 |
+
return;
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
// Skip cross-origin requests and non-GET requests
|
| 54 |
if (url.origin !== location.origin || request.method !== 'GET') {
|
| 55 |
return;
|
frontend/src/App.jsx
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
import React, { useState, useEffect } from 'react';
|
| 2 |
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
|
| 3 |
import { Navbar } from './components/Navbar';
|
| 4 |
-
import { PWAInstallGuide } from './components/PWAInstallGuide';
|
| 5 |
import { HomePage } from './pages/Home';
|
| 6 |
import { LoginPage, RegisterPage } from './pages/Auth';
|
| 7 |
import { DashboardPage } from './pages/Dashboard';
|
|
@@ -87,7 +86,6 @@ function App() {
|
|
| 87 |
)}
|
| 88 |
</Routes>
|
| 89 |
</BrowserRouter>
|
| 90 |
-
<PWAInstallGuide />
|
| 91 |
</>
|
| 92 |
);
|
| 93 |
}
|
|
|
|
| 1 |
import React, { useState, useEffect } from 'react';
|
| 2 |
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
|
| 3 |
import { Navbar } from './components/Navbar';
|
|
|
|
| 4 |
import { HomePage } from './pages/Home';
|
| 5 |
import { LoginPage, RegisterPage } from './pages/Auth';
|
| 6 |
import { DashboardPage } from './pages/Dashboard';
|
|
|
|
| 86 |
)}
|
| 87 |
</Routes>
|
| 88 |
</BrowserRouter>
|
|
|
|
| 89 |
</>
|
| 90 |
);
|
| 91 |
}
|
frontend/src/main.jsx
CHANGED
|
@@ -11,94 +11,21 @@ ReactDOM.createRoot(document.getElementById('root')).render(
|
|
| 11 |
|
| 12 |
// Register Service Worker for PWA
|
| 13 |
if ('serviceWorker' in navigator) {
|
| 14 |
-
|
| 15 |
-
navigator.serviceWorker.
|
| 16 |
-
.
|
| 17 |
-
|
| 18 |
-
})
|
| 19 |
-
.catch((error) => {
|
| 20 |
-
console.log('[PWA] Service Worker registration failed:', error);
|
| 21 |
});
|
| 22 |
-
|
| 23 |
-
}
|
| 24 |
-
|
| 25 |
-
/
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
right: 20px;
|
| 34 |
-
background: linear-gradient(135deg, #0f6f62 0%, #12927f 100%);
|
| 35 |
-
color: white;
|
| 36 |
-
padding: 16px;
|
| 37 |
-
border-radius: 12px;
|
| 38 |
-
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
|
| 39 |
-
display: none;
|
| 40 |
-
z-index: 9999;
|
| 41 |
-
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
|
| 42 |
-
`;
|
| 43 |
-
|
| 44 |
-
installPromptDiv.innerHTML = `
|
| 45 |
-
<div style="display: flex; justify-content: space-between; align-items: center; gap: 12px;">
|
| 46 |
-
<div style="flex: 1;">
|
| 47 |
-
<strong style="font-size: 16px; display: block; margin-bottom: 4px;">Install SSC App</strong>
|
| 48 |
-
<span style="font-size: 14px; opacity: 0.9;">Get instant access to cricket scoring</span>
|
| 49 |
-
</div>
|
| 50 |
-
<div style="display: flex; gap: 8px; white-space: nowrap;">
|
| 51 |
-
<button id="pwa-install-btn" style="
|
| 52 |
-
background: white;
|
| 53 |
-
color: #0f6f62;
|
| 54 |
-
border: none;
|
| 55 |
-
padding: 8px 16px;
|
| 56 |
-
border-radius: 6px;
|
| 57 |
-
font-weight: 600;
|
| 58 |
-
cursor: pointer;
|
| 59 |
-
font-size: 14px;
|
| 60 |
-
">Install</button>
|
| 61 |
-
<button id="pwa-dismiss-btn" style="
|
| 62 |
-
background: transparent;
|
| 63 |
-
color: white;
|
| 64 |
-
border: 1px solid rgba(255, 255, 255, 0.3);
|
| 65 |
-
padding: 8px 16px;
|
| 66 |
-
border-radius: 6px;
|
| 67 |
-
font-weight: 600;
|
| 68 |
-
cursor: pointer;
|
| 69 |
-
font-size: 14px;
|
| 70 |
-
">Later</button>
|
| 71 |
-
</div>
|
| 72 |
-
</div>
|
| 73 |
-
`;
|
| 74 |
-
|
| 75 |
-
document.body.appendChild(installPromptDiv);
|
| 76 |
-
|
| 77 |
-
window.addEventListener('beforeinstallprompt', (e) => {
|
| 78 |
-
e.preventDefault();
|
| 79 |
-
deferredPrompt = e;
|
| 80 |
-
installPromptDiv.style.display = 'block';
|
| 81 |
-
console.log('[PWA] Install prompt is available');
|
| 82 |
-
});
|
| 83 |
-
|
| 84 |
-
document.getElementById('pwa-install-btn').addEventListener('click', async () => {
|
| 85 |
-
if (deferredPrompt) {
|
| 86 |
-
deferredPrompt.prompt();
|
| 87 |
-
const { outcome } = await deferredPrompt.userChoice;
|
| 88 |
-
console.log(`[PWA] User response to install prompt: ${outcome}`);
|
| 89 |
-
deferredPrompt = null;
|
| 90 |
-
installPromptDiv.style.display = 'none';
|
| 91 |
}
|
| 92 |
-
}
|
| 93 |
-
|
| 94 |
-
document.getElementById('pwa-dismiss-btn').addEventListener('click', () => {
|
| 95 |
-
deferredPrompt = null;
|
| 96 |
-
installPromptDiv.style.display = 'none';
|
| 97 |
-
});
|
| 98 |
-
|
| 99 |
-
// Hide install prompt if app is already installed
|
| 100 |
-
window.addEventListener('appinstalled', () => {
|
| 101 |
-
console.log('[PWA] App installed successfully');
|
| 102 |
-
installPromptDiv.style.display = 'none';
|
| 103 |
-
deferredPrompt = null;
|
| 104 |
-
});
|
|
|
|
| 11 |
|
| 12 |
// Register Service Worker for PWA
|
| 13 |
if ('serviceWorker' in navigator) {
|
| 14 |
+
if (import.meta.env.DEV) {
|
| 15 |
+
navigator.serviceWorker.getRegistrations().then((registrations) => {
|
| 16 |
+
registrations.forEach((registration) => {
|
| 17 |
+
registration.unregister();
|
|
|
|
|
|
|
|
|
|
| 18 |
});
|
| 19 |
+
});
|
| 20 |
+
} else {
|
| 21 |
+
window.addEventListener('load', () => {
|
| 22 |
+
navigator.serviceWorker.register('/service-worker.js')
|
| 23 |
+
.then((registration) => {
|
| 24 |
+
console.log('[PWA] Service Worker registered:', registration);
|
| 25 |
+
})
|
| 26 |
+
.catch((error) => {
|
| 27 |
+
console.log('[PWA] Service Worker registration failed:', error);
|
| 28 |
+
});
|
| 29 |
+
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
}
|
| 31 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
frontend/src/pages/Profile.jsx
CHANGED
|
@@ -44,27 +44,39 @@ export function ProfilePage() {
|
|
| 44 |
const fetchData = async () => {
|
| 45 |
try {
|
| 46 |
const currentUser = JSON.parse(localStorage.getItem('user'));
|
| 47 |
-
|
| 48 |
const isOwn = !playerId || String(playerId) === String(currentUser?.id);
|
| 49 |
setIsOwnProfile(isOwn);
|
| 50 |
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
];
|
| 57 |
|
| 58 |
if (isOwn) {
|
| 59 |
-
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
|
| 69 |
setUser(playerRes.data);
|
| 70 |
setStats(statsRes.data);
|
|
|
|
| 44 |
const fetchData = async () => {
|
| 45 |
try {
|
| 46 |
const currentUser = JSON.parse(localStorage.getItem('user'));
|
| 47 |
+
let profileId = playerId || currentUser?.id;
|
| 48 |
const isOwn = !playerId || String(playerId) === String(currentUser?.id);
|
| 49 |
setIsOwnProfile(isOwn);
|
| 50 |
|
| 51 |
+
let playerRes;
|
| 52 |
+
let statsRes;
|
| 53 |
+
let logsRes;
|
| 54 |
+
let aiRes;
|
| 55 |
+
let chatRes;
|
|
|
|
| 56 |
|
| 57 |
if (isOwn) {
|
| 58 |
+
// Always resolve own profile from backend identity instead of localStorage id.
|
| 59 |
+
playerRes = await playerService.getCurrentPlayer();
|
| 60 |
+
if (playerRes?.data?.id !== undefined && playerRes?.data?.id !== null) {
|
| 61 |
+
profileId = playerRes.data.id;
|
| 62 |
+
localStorage.setItem('user', JSON.stringify(playerRes.data));
|
| 63 |
+
window.dispatchEvent(new Event('authchange'));
|
| 64 |
+
}
|
| 65 |
|
| 66 |
+
[statsRes, logsRes, aiRes, chatRes] = await Promise.all([
|
| 67 |
+
performanceService.getPlayerStats(profileId),
|
| 68 |
+
performanceService.getPlayerLogs(profileId),
|
| 69 |
+
performanceService.getAiInsights(profileId),
|
| 70 |
+
adminService.getMyChat(),
|
| 71 |
+
]);
|
| 72 |
+
} else {
|
| 73 |
+
[playerRes, statsRes, logsRes, aiRes] = await Promise.all([
|
| 74 |
+
playerService.getPlayer(profileId),
|
| 75 |
+
performanceService.getPlayerStats(profileId),
|
| 76 |
+
performanceService.getPlayerLogs(profileId),
|
| 77 |
+
performanceService.getAiInsights(profileId),
|
| 78 |
+
]);
|
| 79 |
+
}
|
| 80 |
|
| 81 |
setUser(playerRes.data);
|
| 82 |
setStats(statsRes.data);
|
frontend/src/utils/api.js
CHANGED
|
@@ -27,6 +27,43 @@ const api = axios.create({
|
|
| 27 |
}
|
| 28 |
});
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
// Add token to requests
|
| 31 |
api.interceptors.request.use(async (config) => {
|
| 32 |
let token = localStorage.getItem('token');
|
|
@@ -45,6 +82,46 @@ api.interceptors.request.use(async (config) => {
|
|
| 45 |
return config;
|
| 46 |
});
|
| 47 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
const hydrateLocalUserFromBackend = async (accessToken) => {
|
| 49 |
if (accessToken) {
|
| 50 |
localStorage.setItem('token', accessToken);
|
|
@@ -119,7 +196,7 @@ export const authService = {
|
|
| 119 |
const accessToken = await cred.user.getIdToken();
|
| 120 |
return { data: await hydrateLocalUserFromBackend(accessToken) };
|
| 121 |
} catch (error) {
|
| 122 |
-
const message = error?.message || 'Registration failed';
|
| 123 |
throw { response: { data: { detail: message } } };
|
| 124 |
}
|
| 125 |
|
|
@@ -135,7 +212,13 @@ export const authService = {
|
|
| 135 |
const accessToken = await cred.user.getIdToken();
|
| 136 |
return { data: await hydrateLocalUserFromBackend(accessToken) };
|
| 137 |
} catch (error) {
|
| 138 |
-
throw {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
}
|
| 140 |
},
|
| 141 |
|
|
@@ -164,7 +247,13 @@ export const authService = {
|
|
| 164 |
const accessToken = await cred.user.getIdToken();
|
| 165 |
return { data: await hydrateLocalUserFromBackend(accessToken) };
|
| 166 |
} catch (error) {
|
| 167 |
-
throw {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
}
|
| 169 |
},
|
| 170 |
|
|
|
|
| 27 |
}
|
| 28 |
});
|
| 29 |
|
| 30 |
+
const clearClientAuthState = () => {
|
| 31 |
+
localStorage.removeItem('token');
|
| 32 |
+
localStorage.removeItem('user');
|
| 33 |
+
window.dispatchEvent(new Event('authchange'));
|
| 34 |
+
};
|
| 35 |
+
|
| 36 |
+
const getFirebaseAuthErrorMessage = (error, fallbackMessage) => {
|
| 37 |
+
const code = error?.code || '';
|
| 38 |
+
|
| 39 |
+
if (
|
| 40 |
+
code === 'auth/invalid-credential' ||
|
| 41 |
+
code === 'auth/wrong-password' ||
|
| 42 |
+
code === 'auth/user-not-found' ||
|
| 43 |
+
code === 'auth/invalid-login-credentials'
|
| 44 |
+
) {
|
| 45 |
+
return 'Invalid email or password';
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
if (code === 'auth/invalid-email') {
|
| 49 |
+
return 'Please enter a valid email address';
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
if (code === 'auth/email-already-in-use') {
|
| 53 |
+
return 'This email is already registered';
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
if (code === 'auth/weak-password') {
|
| 57 |
+
return 'Password is too weak. Use at least 6 characters';
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
if (code === 'auth/popup-closed-by-user') {
|
| 61 |
+
return 'Google sign-in was cancelled';
|
| 62 |
+
}
|
| 63 |
+
|
| 64 |
+
return fallbackMessage;
|
| 65 |
+
};
|
| 66 |
+
|
| 67 |
// Add token to requests
|
| 68 |
api.interceptors.request.use(async (config) => {
|
| 69 |
let token = localStorage.getItem('token');
|
|
|
|
| 82 |
return config;
|
| 83 |
});
|
| 84 |
|
| 85 |
+
api.interceptors.response.use(
|
| 86 |
+
(response) => response,
|
| 87 |
+
async (error) => {
|
| 88 |
+
const originalRequest = error.config || {};
|
| 89 |
+
const status = error?.response?.status;
|
| 90 |
+
|
| 91 |
+
if (status === 401 && !originalRequest._retry) {
|
| 92 |
+
originalRequest._retry = true;
|
| 93 |
+
|
| 94 |
+
if (isFirebaseConfigured && firebaseAuth?.currentUser) {
|
| 95 |
+
try {
|
| 96 |
+
const refreshedToken = await firebaseAuth.currentUser.getIdToken(true);
|
| 97 |
+
if (refreshedToken) {
|
| 98 |
+
localStorage.setItem('token', refreshedToken);
|
| 99 |
+
originalRequest.headers = {
|
| 100 |
+
...(originalRequest.headers || {}),
|
| 101 |
+
Authorization: `Bearer ${refreshedToken}`,
|
| 102 |
+
};
|
| 103 |
+
return api(originalRequest);
|
| 104 |
+
}
|
| 105 |
+
} catch (_refreshError) {
|
| 106 |
+
// Fall through to clear stale client auth state.
|
| 107 |
+
}
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
if (isFirebaseConfigured && firebaseAuth) {
|
| 111 |
+
try {
|
| 112 |
+
await signOut(firebaseAuth);
|
| 113 |
+
} catch (_signOutError) {
|
| 114 |
+
// Ignore signOut errors; local state reset below is enough.
|
| 115 |
+
}
|
| 116 |
+
}
|
| 117 |
+
|
| 118 |
+
clearClientAuthState();
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
return Promise.reject(error);
|
| 122 |
+
}
|
| 123 |
+
);
|
| 124 |
+
|
| 125 |
const hydrateLocalUserFromBackend = async (accessToken) => {
|
| 126 |
if (accessToken) {
|
| 127 |
localStorage.setItem('token', accessToken);
|
|
|
|
| 196 |
const accessToken = await cred.user.getIdToken();
|
| 197 |
return { data: await hydrateLocalUserFromBackend(accessToken) };
|
| 198 |
} catch (error) {
|
| 199 |
+
const message = getFirebaseAuthErrorMessage(error, error?.message || 'Registration failed');
|
| 200 |
throw { response: { data: { detail: message } } };
|
| 201 |
}
|
| 202 |
|
|
|
|
| 212 |
const accessToken = await cred.user.getIdToken();
|
| 213 |
return { data: await hydrateLocalUserFromBackend(accessToken) };
|
| 214 |
} catch (error) {
|
| 215 |
+
throw {
|
| 216 |
+
response: {
|
| 217 |
+
data: {
|
| 218 |
+
detail: getFirebaseAuthErrorMessage(error, error?.message || 'Login failed'),
|
| 219 |
+
},
|
| 220 |
+
},
|
| 221 |
+
};
|
| 222 |
}
|
| 223 |
},
|
| 224 |
|
|
|
|
| 247 |
const accessToken = await cred.user.getIdToken();
|
| 248 |
return { data: await hydrateLocalUserFromBackend(accessToken) };
|
| 249 |
} catch (error) {
|
| 250 |
+
throw {
|
| 251 |
+
response: {
|
| 252 |
+
data: {
|
| 253 |
+
detail: getFirebaseAuthErrorMessage(error, error?.message || 'Google login failed'),
|
| 254 |
+
},
|
| 255 |
+
},
|
| 256 |
+
};
|
| 257 |
}
|
| 258 |
},
|
| 259 |
|