Spaces:
Runtime error
Runtime error
Download src/api/auth.py from BattleFiven/ai-tester-platform: direct link, hf CLI and curl.
- Browser
- Download file 18.1 kB
-
https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/api/auth.py
- Command line
-
hf download hf://spaces/BattleFiven/ai-tester-platform/src/api/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/BattleFiven/ai-tester-platform/resolve/main/src/api/auth.py
18.1 kB
| """ | |
| Authentication module using Supabase | |
| Handles user management, roles (admin/user), and session management | |
| """ | |
| import os | |
| from datetime import datetime, timezone | |
| from typing import Optional | |
| from fastapi import Depends, HTTPException | |
| from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer | |
| from src.api.supabase_client import get_db | |
| from src.utils.logging import get_logger | |
| logger = get_logger(__name__) | |
| # Security scheme | |
| security = HTTPBearer() | |
| class User: | |
| """User model with roles""" | |
| def __init__(self, id: str, email: str, role: str = "user", | |
| full_name: str = None, avatar_url: str = None): | |
| self.id = id | |
| self.email = email | |
| self.role = role # "admin" or "user" | |
| self.full_name = full_name | |
| self.avatar_url = avatar_url | |
| def is_admin(self) -> bool: | |
| return self.role in {"admin", "superadmin"} | |
| def is_superadmin(self) -> bool: | |
| return self.role == "superadmin" | |
| def is_viewer(self) -> bool: | |
| """Viewer = read-only role: vede solo /reports, /sessions e i | |
| report dettaglio di una session. Nessuna azione di modifica/creazione.""" | |
| return self.role == "viewer" | |
| def initials(self) -> str: | |
| if self.full_name: | |
| return "".join([n[0] for n in self.full_name.split()[:2]]).upper() | |
| return self.email[0].upper() if self.email else "U" | |
| def _superadmin_email() -> str: | |
| return (os.getenv("SUPERADMIN_EMAIL", "") or "").strip().lower() | |
| def _superadmin_user_id() -> str: | |
| return (os.getenv("SUPERADMIN_USER_ID", "") or "").strip() | |
| def _auth_redirect_url() -> Optional[str]: | |
| """Resolve auth redirect URL for Supabase emails (if enabled).""" | |
| explicit = (os.getenv("SUPABASE_AUTH_REDIRECT_URL", "") or "").strip() | |
| if explicit: | |
| return explicit | |
| public_base = (os.getenv("PUBLIC_BASE_URL", "") or "").strip().rstrip("/") | |
| if public_base.startswith(("http://", "https://")): | |
| return f"{public_base}/auth/login" | |
| return None | |
| def _normalize_role(raw_role: Optional[str], email: Optional[str], user_id: Optional[str]) -> str: | |
| role = (raw_role or "user").strip().lower() | |
| # Match contro l'enum allargato 2026-05: viewer (read-only) + | |
| # user/admin/superadmin esistenti. Default su "user" se sconosciuto. | |
| valid_roles = {"viewer", "user", "admin", "superadmin"} | |
| if role not in valid_roles: | |
| role = "user" | |
| if role == "superadmin": | |
| return "superadmin" | |
| super_email = _superadmin_email() | |
| super_id = _superadmin_user_id() | |
| normalized_email = (email or "").strip().lower() | |
| normalized_user_id = (user_id or "").strip() | |
| if (super_email and normalized_email == super_email) or (super_id and normalized_user_id == super_id): | |
| return "superadmin" | |
| return role | |
| def resolve_role(raw_role: Optional[str], email: Optional[str], user_id: Optional[str]) -> str: | |
| """Public helper to normalize effective role (user/admin/superadmin).""" | |
| return _normalize_role(raw_role, email, user_id) | |
| def _get_profile_by_id(user_id: str) -> Optional[dict]: | |
| supabase = get_db() | |
| response = supabase.table("profiles").select("*").eq("id", user_id).limit(1).execute() | |
| if not response or not response.data: | |
| return None | |
| return response.data[0] | |
| def _is_protected_superadmin_profile(profile: Optional[dict]) -> bool: | |
| if not profile: | |
| return False | |
| role = _normalize_role(profile.get("role"), profile.get("email"), profile.get("id")) | |
| return role == "superadmin" | |
| async def get_current_user( | |
| credentials: HTTPAuthorizationCredentials = Depends(security) | |
| ) -> User: | |
| """ | |
| Dependency to get current authenticated user | |
| Validates JWT token with Supabase | |
| """ | |
| try: | |
| supabase = get_db() | |
| # Verify JWT token | |
| auth_response = supabase.auth.get_user(credentials.credentials) | |
| if not auth_response or not auth_response.user: | |
| raise HTTPException(status_code=401, detail="Invalid authentication credentials") | |
| supabase_user = auth_response.user | |
| # Get user profile with role from database | |
| try: | |
| profile_response = supabase.table("profiles").select("*").eq("id", supabase_user.id).execute() | |
| profile = profile_response.data[0] if profile_response.data else {} | |
| except Exception: | |
| profile = {} | |
| return User( | |
| id=supabase_user.id, | |
| email=supabase_user.email, | |
| role=_normalize_role(profile.get("role"), supabase_user.email, supabase_user.id), | |
| full_name=profile.get("full_name"), | |
| avatar_url=profile.get("avatar_url") | |
| ) | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| raise HTTPException(status_code=401, detail=f"Authentication failed: {str(e)}") | |
| async def get_current_admin(user: User = Depends(get_current_user)) -> User: | |
| """Dependency to ensure user is admin""" | |
| if not user.is_admin: | |
| raise HTTPException(status_code=403, detail="Admin access required") | |
| return user | |
| def require_auth(): | |
| """Decorator for protected routes""" | |
| return Depends(get_current_user) | |
| # Stable pseudo-id used in dev (ENFORCE_AUTH=false) so per-user features | |
| # (saved tokens, preferences, ...) work without a Supabase login. | |
| _DEV_LOCAL_USER_ID = "dev-local-user" | |
| def current_user_id(request) -> Optional[str]: | |
| """Return the calling user's id (Supabase) or a stable dev fallback. | |
| - In production (ENFORCE_AUTH=true) this is the Supabase user id. | |
| - In dev/single-user mode it returns ``"dev-local-user"`` so that | |
| features keyed by user_id keep working. | |
| """ | |
| user = getattr(getattr(request, "state", None), "user", None) | |
| if user is not None: | |
| return getattr(user, "id", None) or getattr(user, "email", None) | |
| # No authenticated user — only acceptable when auth isn't enforced. | |
| from src.utils.env import env_bool | |
| if env_bool("ENFORCE_AUTH", default=False): | |
| return None | |
| return _DEV_LOCAL_USER_ID | |
| def require_admin(): | |
| """Decorator for admin-only routes""" | |
| return Depends(get_current_admin) | |
| # Auth helper functions | |
| async def sign_up(email: str, password: str, full_name: str) -> dict: | |
| """Register new user""" | |
| supabase = get_db() | |
| signup_options = { | |
| "data": { | |
| "full_name": full_name | |
| } | |
| } | |
| redirect_to = _auth_redirect_url() | |
| if redirect_to: | |
| signup_options["email_redirect_to"] = redirect_to | |
| # Create auth user | |
| auth_response = supabase.auth.sign_up({ | |
| "email": email, | |
| "password": password, | |
| "options": signup_options | |
| }) | |
| if auth_response.user: | |
| # Create profile | |
| try: | |
| supabase.table("profiles").insert({ | |
| "id": auth_response.user.id, | |
| "email": email, | |
| "full_name": full_name, | |
| "role": "user", # Default role | |
| "created_at": "now()" | |
| }).execute() | |
| except Exception: | |
| # Profile row creation is best-effort: a Supabase trigger usually | |
| # provisions it. Log at warning since manual recovery may be needed. | |
| logger.exception( | |
| "auth: profile creation failed", | |
| extra={"user_id": getattr(auth_response.user, "id", None)}, | |
| ) | |
| return { | |
| "user": auth_response.user, | |
| "session": auth_response.session | |
| } | |
| async def create_user_admin(email: str, password: str, full_name: str, role: str = "user") -> dict: | |
| """ | |
| Create user from backend admin context (no email confirmation required). | |
| Uses Supabase Admin API with email confirmed at creation time. | |
| """ | |
| supabase = get_db() | |
| normalized_email = (email or "").strip().lower() | |
| normalized_name = (full_name or "").strip() | |
| normalized_role = (role or "user").strip().lower() | |
| auth_response = supabase.auth.admin.create_user({ | |
| "email": normalized_email, | |
| "password": password, | |
| "email_confirm": True, | |
| "user_metadata": { | |
| "full_name": normalized_name | |
| }, | |
| "app_metadata": { | |
| "role": normalized_role | |
| }, | |
| }) | |
| if not auth_response or not auth_response.user: | |
| raise HTTPException(status_code=400, detail="Failed to create auth user") | |
| user = auth_response.user | |
| now_iso = datetime.now(timezone.utc).isoformat() | |
| profile_payload = { | |
| "email": normalized_email, | |
| "full_name": normalized_name, | |
| "role": normalized_role, | |
| "updated_at": now_iso, | |
| } | |
| try: | |
| updated = supabase.table("profiles").update(profile_payload).eq("id", user.id).execute() | |
| has_row = bool(updated and updated.data) | |
| if not has_row: | |
| supabase.table("profiles").insert({ | |
| "id": user.id, | |
| "email": normalized_email, | |
| "full_name": normalized_name, | |
| "role": normalized_role, | |
| "created_at": now_iso, | |
| "updated_at": now_iso, | |
| }).execute() | |
| except Exception: | |
| # Do not fail auth creation if profile sync has transient issues. | |
| pass | |
| return { | |
| "user": user, | |
| "session": None | |
| } | |
| async def sign_in(email: str, password: str) -> dict: | |
| """Authenticate user""" | |
| supabase = get_db() | |
| auth_response = supabase.auth.sign_in_with_password({ | |
| "email": email, | |
| "password": password | |
| }) | |
| return { | |
| "user": auth_response.user, | |
| "session": auth_response.session, | |
| "access_token": auth_response.session.access_token if auth_response.session else None | |
| } | |
| async def sign_out(jwt_token: str): | |
| """Sign out user""" | |
| supabase = get_db() | |
| supabase.auth.sign_out() | |
| async def reset_password(email: str): | |
| """Send password reset email""" | |
| supabase = get_db() | |
| options = {} | |
| redirect_to = _auth_redirect_url() | |
| if redirect_to: | |
| options["redirect_to"] = redirect_to | |
| supabase.auth.reset_password_email(email, options or None) | |
| # User management (admin only) | |
| async def list_users(admin_user: User) -> list: | |
| """List all users (admin only)""" | |
| if not admin_user.is_admin: | |
| raise HTTPException(status_code=403, detail="Admin access required") | |
| supabase = get_db() | |
| # Get all profiles | |
| response = supabase.table("profiles").select("*").order("created_at", desc=True).execute() | |
| users = response.data if response else [] | |
| for user in users: | |
| user["role"] = _normalize_role(user.get("role"), user.get("email"), user.get("id")) | |
| return users | |
| async def update_user_role(admin_user: User, user_id: str, new_role: str): | |
| """Update user role (admin only)""" | |
| if not admin_user.is_admin: | |
| raise HTTPException(status_code=403, detail="Admin access required") | |
| normalized_role = str(new_role or "").strip().lower() | |
| if normalized_role not in ["superadmin", "admin", "user"]: | |
| raise HTTPException(status_code=400, detail="Invalid role") | |
| target_profile = _get_profile_by_id(user_id) | |
| if not target_profile: | |
| raise HTTPException(status_code=404, detail="User not found") | |
| if _is_protected_superadmin_profile(target_profile): | |
| raise HTTPException(status_code=403, detail="Superadmin account cannot be modified") | |
| if not admin_user.is_superadmin and normalized_role == "superadmin": | |
| raise HTTPException(status_code=403, detail="Only superadmin can assign superadmin role") | |
| if user_id == admin_user.id and normalized_role == "user": | |
| raise HTTPException(status_code=400, detail="You cannot remove your own admin role") | |
| supabase = get_db() | |
| response = supabase.table("profiles").update({ | |
| "role": normalized_role, | |
| "updated_at": "now()" | |
| }).eq("id", user_id).execute() | |
| return response.data | |
| async def update_user( | |
| requesting_user: User, | |
| user_id: str, | |
| *, | |
| email: Optional[str] = None, | |
| full_name: Optional[str] = None, | |
| role: Optional[str] = None, | |
| password: Optional[str] = None, | |
| ): | |
| """Update user profile/auth fields with role-based restrictions.""" | |
| is_self = user_id == requesting_user.id | |
| if not requesting_user.is_admin and not is_self: | |
| raise HTTPException(status_code=403, detail="You can only update your own account") | |
| target_profile = _get_profile_by_id(user_id) | |
| if not target_profile: | |
| raise HTTPException(status_code=404, detail="User not found") | |
| if _is_protected_superadmin_profile(target_profile): | |
| raise HTTPException(status_code=403, detail="Superadmin account cannot be modified") | |
| current_email = str(target_profile.get("email") or "").strip().lower() | |
| current_name = str(target_profile.get("full_name") or "").strip() | |
| current_role = _normalize_role( | |
| target_profile.get("role"), | |
| target_profile.get("email"), | |
| target_profile.get("id"), | |
| ) | |
| requested_role = (role or "").strip().lower() if role is not None else None | |
| if requested_role is not None and requested_role not in ["superadmin", "admin", "user"]: | |
| raise HTTPException(status_code=400, detail="Invalid role") | |
| normalized_role = ( | |
| requested_role | |
| if requested_role is not None and requested_role != current_role | |
| else None | |
| ) | |
| if normalized_role is not None: | |
| if not requesting_user.is_admin: | |
| raise HTTPException(status_code=403, detail="Admin access required to change user roles") | |
| if not requesting_user.is_superadmin and normalized_role == "superadmin": | |
| raise HTTPException(status_code=403, detail="Only superadmin can assign superadmin role") | |
| if user_id == requesting_user.id and requesting_user.is_admin and normalized_role == "user": | |
| raise HTTPException(status_code=400, detail="You cannot remove your own admin role") | |
| normalized_email = (email or "").strip().lower() if email is not None else None | |
| if normalized_email == current_email: | |
| normalized_email = None | |
| normalized_name = (full_name or "").strip() if full_name is not None else None | |
| if normalized_name == current_name: | |
| normalized_name = None | |
| normalized_password = (password or "").strip() if password is not None else None | |
| if normalized_password is not None and len(normalized_password) < 8: | |
| raise HTTPException(status_code=400, detail="Password must be at least 8 characters") | |
| if ( | |
| normalized_email is None | |
| and normalized_name is None | |
| and normalized_role is None | |
| and normalized_password is None | |
| ): | |
| raise HTTPException(status_code=400, detail="No changes detected") | |
| supabase = get_db() | |
| # Auth-layer update (email/password only). | |
| auth_payload = {} | |
| if normalized_email is not None: | |
| auth_payload["email"] = normalized_email | |
| auth_payload["email_confirm"] = True | |
| if normalized_password is not None: | |
| auth_payload["password"] = normalized_password | |
| if auth_payload: | |
| try: | |
| supabase.auth.admin.update_user_by_id(user_id, auth_payload) | |
| except Exception as exc: | |
| # Keep auth/profile consistency for email and password changes. | |
| if normalized_email is not None or normalized_password is not None: | |
| raise HTTPException(status_code=400, detail=f"Failed to update auth user: {str(exc)}") | |
| profile_updates = {"updated_at": datetime.now(timezone.utc).isoformat()} | |
| if normalized_email is not None: | |
| profile_updates["email"] = normalized_email | |
| if normalized_name is not None: | |
| profile_updates["full_name"] = normalized_name | |
| if normalized_role is not None: | |
| profile_updates["role"] = normalized_role | |
| if len(profile_updates.keys()) > 1: | |
| response = supabase.table("profiles").update(profile_updates).eq("id", user_id).execute() | |
| if not response or not response.data: | |
| raise HTTPException(status_code=404, detail="User not found") | |
| updated_profile = response.data[0] | |
| else: | |
| refreshed = _get_profile_by_id(user_id) | |
| if not refreshed: | |
| raise HTTPException(status_code=404, detail="User not found") | |
| updated_profile = refreshed | |
| updated_profile["role"] = _normalize_role( | |
| updated_profile.get("role"), | |
| updated_profile.get("email"), | |
| updated_profile.get("id"), | |
| ) | |
| return updated_profile | |
| async def delete_user(requesting_user: User, user_id: str): | |
| """Delete user with superadmin protection.""" | |
| if not requesting_user.is_admin: | |
| raise HTTPException(status_code=403, detail="Admin access required") | |
| if user_id == requesting_user.id: | |
| raise HTTPException(status_code=400, detail="You cannot delete your own account") | |
| target_profile = _get_profile_by_id(user_id) | |
| if not target_profile: | |
| raise HTTPException(status_code=404, detail="User not found") | |
| if _is_protected_superadmin_profile(target_profile): | |
| raise HTTPException(status_code=403, detail="Superadmin account cannot be deleted") | |
| supabase = get_db() | |
| # Delete profile first | |
| supabase.table("profiles").delete().eq("id", user_id).execute() | |
| try: | |
| supabase.auth.admin.delete_user(user_id) | |
| except Exception: | |
| # Keep profile deletion successful even if auth cleanup fails. | |
| pass | |
| return {"message": "User deleted successfully"} | |
| # Permission checks | |
| def can_manage_bots(user: User) -> bool: | |
| """Both admin and user can manage bots""" | |
| return True | |
| def can_manage_personas(user: User) -> bool: | |
| """Both admin and user can manage personas""" | |
| return True | |
| def can_manage_scenarios(user: User) -> bool: | |
| """Both admin and user can manage scenarios""" | |
| return True | |
| def can_run_tests(user: User) -> bool: | |
| """Both admin and user can run tests""" | |
| return True | |
| def can_manage_users(user: User) -> bool: | |
| """Only admin can manage users""" | |
| return user.is_admin | |