bLOQUE p1 BACKEND Y SEGURIDAD, AUTENTICACION CON SUPABASE. jwt. RBAC CRUD
This commit is contained in:
0
backend/app/core/__init__.py
Normal file
0
backend/app/core/__init__.py
Normal file
21
backend/app/core/config.py
Normal file
21
backend/app/core/config.py
Normal file
@@ -0,0 +1,21 @@
|
||||
from functools import lru_cache
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
||||
|
||||
SUPABASE_URL: str
|
||||
SUPABASE_ANON_KEY: str
|
||||
SUPABASE_SERVICE_ROLE_KEY: str
|
||||
|
||||
FIREBASE_CREDENTIALS_PATH: str = "app/data/secrets/recoleccion-app-firebase-adminsdk-fbsvc-3da79d2a4c.json"
|
||||
SIMULATION_TICK_SECONDS: int = 10
|
||||
|
||||
|
||||
@lru_cache
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
|
||||
|
||||
settings = get_settings()
|
||||
46
backend/app/core/deps.py
Normal file
46
backend/app/core/deps.py
Normal file
@@ -0,0 +1,46 @@
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from app.core.supabase_client import supabase, supabase_admin
|
||||
|
||||
security = HTTPBearer()
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
) -> dict:
|
||||
"""Valida el JWT de Supabase y devuelve {user_id, email, role}."""
|
||||
token = credentials.credentials
|
||||
try:
|
||||
resp = supabase.auth.get_user(token)
|
||||
auth_user = resp.user
|
||||
if auth_user is None:
|
||||
raise ValueError("usuario nulo")
|
||||
except Exception:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Token inválido o expirado",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
result = (
|
||||
supabase_admin.table("users")
|
||||
.select("role")
|
||||
.eq("id", str(auth_user.id))
|
||||
.maybe_single()
|
||||
.execute()
|
||||
)
|
||||
role = result.data["role"] if result.data else "citizen"
|
||||
|
||||
return {"user_id": str(auth_user.id), "email": auth_user.email, "role": role}
|
||||
|
||||
|
||||
def require_role(*roles: str):
|
||||
"""Factory: devuelve una dependencia que exige que el usuario tenga uno de los roles dados."""
|
||||
async def checker(current_user: dict = Depends(get_current_user)) -> dict:
|
||||
if current_user["role"] not in roles:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"Rol requerido: {' o '.join(roles)}",
|
||||
)
|
||||
return current_user
|
||||
return checker
|
||||
8
backend/app/core/supabase_client.py
Normal file
8
backend/app/core/supabase_client.py
Normal file
@@ -0,0 +1,8 @@
|
||||
from supabase import create_client, Client
|
||||
from app.core.config import settings
|
||||
|
||||
# Cliente con anon key — para operaciones de auth y llamadas ciudadanas
|
||||
supabase: Client = create_client(settings.SUPABASE_URL, settings.SUPABASE_ANON_KEY)
|
||||
|
||||
# Cliente con service_role — bypasea RLS; solo para operaciones de backend admin
|
||||
supabase_admin: Client = create_client(settings.SUPABASE_URL, settings.SUPABASE_SERVICE_ROLE_KEY)
|
||||
Reference in New Issue
Block a user