Spaces:
Runtime error
Runtime error
File size: 18,147 Bytes
ed86a97 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 | """
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
@property
def is_admin(self) -> bool:
return self.role in {"admin", "superadmin"}
@property
def is_superadmin(self) -> bool:
return self.role == "superadmin"
@property
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"
@property
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
|