Spaces:
Runtime error
Runtime error
Download app/core/auth.py from dedalys-civ/dedalys-api: direct link, hf CLI and curl.
- Browser
- Download file 4.69 kB
-
https://huggingface.co/spaces/dedalys-civ/dedalys-api/resolve/main/app/core/auth.py
- Command line
-
hf download hf://spaces/dedalys-civ/dedalys-api/app/core/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/dedalys-civ/dedalys-api/resolve/main/app/core/auth.py
4.69 kB
| """ | |
| Dedalys Backend — Authentification | |
| Dépendances FastAPI pour la gestion des utilisateurs et permissions. | |
| """ | |
| from typing import Optional | |
| from uuid import UUID | |
| from dataclasses import dataclass | |
| from fastapi import Depends, HTTPException, status | |
| from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials | |
| from app.core.supabase import supabase, supabase_admin | |
| from app.core.permissions import RoleCabinet, has_permission, ESPACE_ADMIN_ROLES | |
| security = HTTPBearer() | |
| class CurrentUser: | |
| """Représentation de l'utilisateur authentifié.""" | |
| id: str | |
| email: str | |
| nom: str | |
| prenom: str | |
| espace_id: str | |
| role_cabinet: RoleCabinet | |
| is_superadmin: bool = False | |
| async def get_current_user( | |
| credentials: HTTPAuthorizationCredentials = Depends(security), | |
| ) -> CurrentUser: | |
| """ | |
| Extrait et valide l'utilisateur depuis le token JWT. | |
| Retourne les informations de l'utilisateur connecté. | |
| """ | |
| token = credentials.credentials | |
| try: | |
| # Valider le token via Supabase Auth | |
| user_response = supabase.auth.get_user(token) | |
| if not user_response or not user_response.user: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Token invalide ou expiré", | |
| ) | |
| supabase_user = user_response.user | |
| # Récupérer le profil utilisateur depuis la table utilisateurs | |
| profile_response = ( | |
| supabase_admin.table("utilisateurs") | |
| .select("*") | |
| .eq("id", supabase_user.id) | |
| .maybe_single() | |
| .execute() | |
| ) | |
| if not profile_response.data: | |
| raise HTTPException( | |
| status_code=status.HTTP_404_NOT_FOUND, | |
| detail="Profil utilisateur introuvable", | |
| ) | |
| profile = profile_response.data | |
| return CurrentUser( | |
| id=profile["id"], | |
| email=profile["email"], | |
| nom=profile["nom"], | |
| prenom=profile["prenom"], | |
| espace_id=profile["espace_id"], | |
| role_cabinet=RoleCabinet(profile["role_cabinet"]), | |
| is_superadmin=profile.get("is_superadmin", False), | |
| ) | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Erreur d'authentification", | |
| ) | |
| async def require_superadmin( | |
| current_user: CurrentUser = Depends(get_current_user), | |
| ) -> CurrentUser: | |
| """Vérifie que l'utilisateur est superadmin.""" | |
| if not current_user.is_superadmin: | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="Accès réservé aux superadmins", | |
| ) | |
| return current_user | |
| async def get_espace_user( | |
| current_user: CurrentUser = Depends(get_current_user), | |
| ) -> CurrentUser: | |
| """ | |
| Vérifie que l'utilisateur appartient à un espace. | |
| Alias de get_current_user avec vérification explicite. | |
| """ | |
| if not current_user.espace_id: | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="Utilisateur non rattaché à un espace", | |
| ) | |
| return current_user | |
| async def require_espace_admin( | |
| current_user: CurrentUser = Depends(get_espace_user), | |
| ) -> CurrentUser: | |
| """Vérifie que l'utilisateur est admin de son espace (associé gérant ou office manager).""" | |
| if current_user.role_cabinet not in ESPACE_ADMIN_ROLES: | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="Accès réservé aux administrateurs de l'espace", | |
| ) | |
| return current_user | |
| def require_permission(permission: str): | |
| """ | |
| Factory pour créer une dépendance de vérification de permission. | |
| Usage: | |
| @router.get("/", dependencies=[Depends(require_permission("client:read"))]) | |
| async def list_clients(...): | |
| ... | |
| Ou: | |
| @router.get("/") | |
| async def list_clients( | |
| espace_user: CurrentUser = Depends(require_permission("client:read")), | |
| ): | |
| ... | |
| """ | |
| async def _check_permission( | |
| current_user: CurrentUser = Depends(get_espace_user), | |
| ) -> CurrentUser: | |
| # Les superadmins ont toutes les permissions | |
| if current_user.is_superadmin: | |
| return current_user | |
| if not has_permission(current_user.role_cabinet, permission): | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail=f"Permission '{permission}' requise", | |
| ) | |
| return current_user | |
| return _check_permission | |