Ba7ath-Project commited on
Commit
0dfd7f9
·
1 Parent(s): e4c1b67

Fix: Auth corrigé

Browse files
app/middleware/jwt_middleware.py CHANGED
@@ -17,11 +17,19 @@ class JWTMiddleware(BaseHTTPMiddleware):
17
  if SUPABASE_JWT_SECRET:
18
  payload = jwt.decode(token, SUPABASE_JWT_SECRET, algorithms=["HS256"], options={"verify_aud": False})
19
  else:
20
- # Decode without verification for ECC keys (public key verification not performed here)
21
- payload = jwt.get_unverified_claims(token)
 
 
 
 
 
 
 
 
22
  request.state.user = {
23
  "uid": payload.get("sub"),
24
- "is_admin": payload.get("app_metadata", {}).get("is_admin", False),
25
  "jwt": token,
26
  }
27
  except JWTError:
 
17
  if SUPABASE_JWT_SECRET:
18
  payload = jwt.decode(token, SUPABASE_JWT_SECRET, algorithms=["HS256"], options={"verify_aud": False})
19
  else:
20
+ # If secret is missing, we cannot verify. Returning 401 as per strict security.
21
+ return JSONResponse(
22
+ status_code=status.HTTP_401_UNAUTHORIZED,
23
+ content={"detail": "SUPABASE_JWT_SECRET not configured"}
24
+ )
25
+
26
+ app_metadata = payload.get("app_metadata", {})
27
+ user_metadata = payload.get("user_metadata", {})
28
+ is_admin = app_metadata.get("is_admin", False) or user_metadata.get("is_admin", False)
29
+
30
  request.state.user = {
31
  "uid": payload.get("sub"),
32
+ "is_admin": is_admin,
33
  "jwt": token,
34
  }
35
  except JWTError:
app/services/auth_service.py CHANGED
@@ -47,12 +47,16 @@ async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(s
47
 
48
  # In Supabase, custom claims or roles are often stored in app_metadata/user_metadata
49
  app_metadata = payload.get("app_metadata", {})
 
 
 
 
50
 
51
  return AuthenticatedUserInfo(
52
  user_id=user_id,
53
  email=payload.get("email"),
54
  jwt=token,
55
- is_admin=app_metadata.get("is_admin", False)
56
  )
57
  except JWTError as e:
58
  print(f"JWT Validation error: {e}")
@@ -71,6 +75,9 @@ async def get_current_active_user(current_user: AuthenticatedUserInfo = Depends(
71
  async def get_current_admin_user(current_user: AuthenticatedUserInfo = Depends(get_current_active_user)):
72
  """
73
  Verifies that the user has admin privileges.
 
 
 
74
  """
75
  if not current_user.is_admin:
76
  raise HTTPException(
 
47
 
48
  # In Supabase, custom claims or roles are often stored in app_metadata/user_metadata
49
  app_metadata = payload.get("app_metadata", {})
50
+ user_metadata = payload.get("user_metadata", {})
51
+
52
+ # Check both app_metadata and user_metadata for is_admin
53
+ is_admin = app_metadata.get("is_admin", False) or user_metadata.get("is_admin", False)
54
 
55
  return AuthenticatedUserInfo(
56
  user_id=user_id,
57
  email=payload.get("email"),
58
  jwt=token,
59
+ is_admin=is_admin
60
  )
61
  except JWTError as e:
62
  print(f"JWT Validation error: {e}")
 
75
  async def get_current_admin_user(current_user: AuthenticatedUserInfo = Depends(get_current_active_user)):
76
  """
77
  Verifies that the user has admin privileges.
78
+ NOTE: As per user instructions, backend endpoints should rely on RLS
79
+ policies when possible, but this dependency still serves as a high-level gate
80
+ for admin-only API routes.
81
  """
82
  if not current_user.is_admin:
83
  raise HTTPException(
create_admin.py DELETED
@@ -1,28 +0,0 @@
1
- from app.database import SessionLocal
2
- from app.models.user_models import User
3
- from passlib.context import CryptContext
4
-
5
- pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
6
-
7
- def create_initial_admin():
8
- db = SessionLocal()
9
- # Vérifie si l'admin existe déjà
10
- admin_email = "moezelbey@gmail.com"
11
- existing_user = db.query(User).filter(User.email == admin_email).first()
12
-
13
- if not existing_user:
14
- new_admin = User(
15
- email=admin_email,
16
- hashed_password=pwd_context.hash("Apostroph03*"), # <--- METS TON PASS ICI
17
- is_active=True,
18
- is_admin=True
19
- )
20
- db.add(new_admin)
21
- db.commit()
22
- print(f"Admin {admin_email} créé avec succès !")
23
- else:
24
- print("L'admin existe déjà.")
25
- db.close()
26
-
27
- if __name__ == "__main__":
28
- create_initial_admin()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
rebuild_database.py DELETED
@@ -1,173 +0,0 @@
1
- import csv
2
- import json
3
- import os
4
- import sys
5
- import uuid
6
- import pandas as pd
7
- import numpy as np
8
- from datetime import datetime
9
- from sqlalchemy.orm import Session
10
- from sqlalchemy import text
11
-
12
- # Configuration du répertoire de base pour Hugging Face
13
- backend_dir = "/app"
14
- if backend_dir not in sys.path:
15
- sys.path.append(backend_dir)
16
-
17
- from app.database import SessionLocal, engine, Base
18
- from app.models.user_models import User
19
- from app.models.enrichment_models import EnrichedCompany, WatchCompany
20
- from app.services.data_loader import (
21
- PATH_AHLYA_CSV,
22
- PATH_RNE_CSV,
23
- PATH_JORT_CSV,
24
- normalize_company_name
25
- )
26
-
27
- PATH_WATCHLIST_CSV = os.getenv("PATH_WATCHLIST_CSV", "ahlya_not_in_trovit_fuzzy.csv")
28
-
29
- def is_table_empty(db: Session, model):
30
- return db.query(model).first() is None
31
-
32
- # Les comptes admin et utilisateurs sont désormais gérés directement via Supabase Auth
33
- # Il n'est plus nécessaire de créer un utilisateur admin dans SQLite localement via Python
34
-
35
- def populate_enriched_companies_if_empty(db: Session):
36
- if not is_table_empty(db, EnrichedCompany):
37
- return
38
-
39
- print("📊 Populating EnrichedCompany from CSVs...")
40
-
41
- if not os.path.exists(PATH_AHLYA_CSV):
42
- return
43
-
44
- # 1. Chargement Ahlya
45
- df_ahlya = pd.read_csv(PATH_AHLYA_CSV)
46
- df_ahlya.rename(columns={
47
- "اسم_الشركة": "name", "الولاية": "wilaya", "المعتمدية": "delegation",
48
- "المنطقة": "locality", "النوع": "type", "الموضوع / النشاط": "activity_raw",
49
- "activité_normalisée": "activity_normalized", "activité_groupe": "activity_group"
50
- }, inplace=True)
51
- df_ahlya['name_normalized'] = df_ahlya['name'].apply(normalize_company_name)
52
-
53
- # 2. Enrichissement RNE
54
- if os.path.exists(PATH_RNE_CSV):
55
- df_rne = pd.read_csv(PATH_RNE_CSV)
56
- df_rne['name_normalized'] = df_rne['name'].apply(normalize_company_name)
57
- rne_cols = ['name_normalized', 'charika_id', 'tax_id', 'rc_number', 'founding_date_iso', 'legal_form', 'address', 'detail_url', 'capital']
58
- rne_subset = df_rne[[c for c in rne_cols if c in df_rne.columns]].copy()
59
- df_final = pd.merge(df_ahlya, rne_subset, on='name_normalized', how='left')
60
- else:
61
- df_final = df_ahlya.copy()
62
- df_final['charika_id'] = None
63
-
64
- # 3. Enrichissement JORT
65
- jort_dict = {}
66
- if os.path.exists(PATH_JORT_CSV):
67
- print("🔍 JORT Data found, processing...")
68
- df_jort = pd.read_csv(PATH_JORT_CSV).replace({np.nan: None})
69
- if 'Dénomination' in df_jort.columns:
70
- df_jort['name_normalized'] = df_jort['Dénomination'].apply(normalize_company_name)
71
- for _, r in df_jort.iterrows():
72
- n_norm = r['name_normalized']
73
- if n_norm not in jort_dict:
74
- jort_dict[n_norm] = []
75
- jort_dict[n_norm].append({
76
- "date": str(r.get('Date Annonce', '')) if r.get('Date Annonce') else "N/A",
77
- "type": "Annonce",
78
- "jort_number": str(r.get('Référence JORT', '')) if r.get('Référence JORT') else "N/A",
79
- "content": str(r.get('Texte Source Original', '')) if r.get('Texte Source Original') else ""
80
- })
81
-
82
- df_final = df_final.replace({np.nan: None})
83
- seen_ids = set()
84
- count = 0
85
-
86
- for _, row in df_final.iterrows():
87
- cid = str(row.get('charika_id')) if row.get('charika_id') else f"AHLYA_{uuid.uuid4().hex[:8]}"
88
- if cid in seen_ids: continue
89
- seen_ids.add(cid)
90
-
91
- try:
92
- cap_raw = row.get('capital')
93
- capital_val = float(cap_raw) if cap_raw is not None and pd.notna(cap_raw) else 0.0
94
- except:
95
- capital_val = 0.0
96
-
97
- # Récupération des annonces JORT pour cette entreprise spécifique
98
- announcements = jort_dict.get(row.get('name_normalized'), [])
99
-
100
- data_json = {
101
- "rne": {
102
- "charika_id": row.get('charika_id'),
103
- "tax_id": row.get('tax_id'),
104
- "rc_number": row.get('rc_number'),
105
- "founding_date_iso": row.get('founding_date_iso'),
106
- "legal_form": row.get('legal_form'),
107
- "address": row.get('address'),
108
- "detail_url": row.get('detail_url'),
109
- "capital": capital_val,
110
- "capital_social": capital_val
111
- },
112
- "jort": {"announcements": announcements}, # <--- L'INJECTION JORT EST ICI
113
- "marches": {"contracts": []},
114
- "raw": {k: (None if pd.isna(v) else v) for k, v in row.to_dict().items()}
115
- }
116
-
117
- metrics_json = {
118
- "total_contracts": 0,
119
- "total_contracts_value": 0.0,
120
- "capital_to_contracts_ratio": 0.0,
121
- "red_flags": []
122
- }
123
-
124
- enriched = EnrichedCompany(
125
- company_id=cid,
126
- company_name=row['name'],
127
- wilaya=row['wilaya'] or "Inconnue",
128
- data=data_json,
129
- metrics=metrics_json,
130
- enriched_by="rebuild_script"
131
- )
132
- db.add(enriched)
133
- count += 1
134
- if count % 100 == 0: db.commit()
135
-
136
- db.commit()
137
- print(f"✅ EnrichedCompany finished: {count} records.")
138
-
139
- def populate_watchlist_if_empty(db: Session):
140
- if not is_table_empty(db, WatchCompany): return
141
- if not os.path.exists(PATH_WATCHLIST_CSV): return
142
-
143
- df_watch = pd.read_csv(PATH_WATCHLIST_CSV).replace({np.nan: None})
144
- for _, row in df_watch.iterrows():
145
- name_ar = row.get("name_ar") or row.get("اسم_الشركة")
146
- if not name_ar: continue
147
- db.add(WatchCompany(
148
- id=str(uuid.uuid4()),
149
- name_ar=name_ar.strip(),
150
- wilaya=row.get("wilaya", ""),
151
- delegation=row.get("delegation", ""),
152
- activity=row.get("activity", ""),
153
- type=row.get("type", ""),
154
- date_annonce=row.get("date_annonce") or row.get("date"),
155
- etat_enregistrement="watch",
156
- created_at=datetime.utcnow()
157
- ))
158
- db.commit()
159
-
160
- def run_rebuild():
161
- Base.metadata.create_all(bind=engine)
162
- db = SessionLocal()
163
- try:
164
- populate_enriched_companies_if_empty(db)
165
- populate_watchlist_if_empty(db)
166
- except Exception as e:
167
- print(f"🔥 CRITICAL ERROR: {e}")
168
- db.rollback()
169
- finally:
170
- db.close()
171
-
172
- if __name__ == "__main__":
173
- run_rebuild()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test_auth_flow.py DELETED
@@ -1,52 +0,0 @@
1
- import requests
2
- import sys
3
-
4
- BASE_URL = "http://localhost:8000/api/v1"
5
- EMAIL = "admin@ba7ath.com"
6
- PASSWORD = "admin123"
7
-
8
- def test_auth():
9
- print(f"Testing auth on {BASE_URL}...")
10
-
11
- # 1. Login
12
- print("\n1. Logging in...")
13
- try:
14
- response = requests.post(f"{BASE_URL}/auth/login", data={"username": EMAIL, "password": PASSWORD})
15
- if response.status_code != 200:
16
- print(f"Login failed: {response.status_code} - {response.text}")
17
- return
18
-
19
- token_data = response.json()
20
- access_token = token_data.get("access_token")
21
- print(f"Login successful! Token: {access_token[:20]}...")
22
- except Exception as e:
23
- print(f"Login failed: {e}")
24
- return
25
-
26
- # 2. Access protected endpoint (Auth Me)
27
- print("\n2. Accessing /auth/me (Protected)...")
28
- headers = {"Authorization": f"Bearer {access_token}"}
29
- response = requests.get(f"{BASE_URL}/auth/me", headers=headers)
30
- if response.status_code == 200:
31
- print(f"Success! User: {response.json().get('email')}")
32
- else:
33
- print(f"Failed: {response.status_code} - {response.text}")
34
-
35
- # 3. Access protected endpoint (Stats)
36
- print("\n3. Accessing /stats/national (Protected)...")
37
- response = requests.get(f"{BASE_URL}/stats/national", headers=headers)
38
- if response.status_code == 200:
39
- print("Success! Stats retrieved.")
40
- else:
41
- print(f"Failed: {response.status_code} - {response.text}")
42
-
43
- # 4. Access without token (Expected Failure)
44
- print("\n4. Accessing /stats/national WITHOUT token...")
45
- response = requests.get(f"{BASE_URL}/stats/national")
46
- if response.status_code == 401:
47
- print("Success! Request rejected as expected (401 Unauthorized).")
48
- else:
49
- print(f"Failed! Expected 401, got {response.status_code}")
50
-
51
- if __name__ == "__main__":
52
- test_auth()