Spaces:
Running on Zero
Running on Zero
Download app/api/v1/auth.py from avijit28/tunechecker-api: direct link, hf CLI and curl.
- Browser
- Download file 11.9 kB
-
https://huggingface.co/spaces/avijit28/tunechecker-api/resolve/main/app/api/v1/auth.py
- Command line
-
hf download hf://spaces/avijit28/tunechecker-api/app/api/v1/auth.py
-
curl -L -o auth.py https://huggingface.co/spaces/avijit28/tunechecker-api/resolve/main/app/api/v1/auth.py
11.9 kB
| """Authentication & RBAC API Endpoints. | |
| Provides: | |
| - POST /api/v1/auth/login (JWT token issuance) | |
| - POST /api/v1/auth/refresh (Seamless refresh token rotation) | |
| - POST /api/v1/auth/register (Enterprise user provisioning) | |
| - GET /api/v1/auth/me (Authenticated user profile & active role) | |
| - POST /api/v1/auth/logout (Revocation of tokens via Redis) | |
| - GET /api/v1/auth/roles (Available RBAC system roles) | |
| """ | |
| from __future__ import annotations | |
| import logging | |
| from typing import Any, Dict, List, Optional | |
| from fastapi import APIRouter, Depends, HTTPException, Request, Response, status | |
| from fastapi.security import OAuth2PasswordRequestForm | |
| from pydantic import BaseModel | |
| from app.core.security import ( | |
| User, | |
| UserRole, | |
| Token, | |
| LoginRequest, | |
| RefreshTokenRequest, | |
| RegisterRequest, | |
| authenticate_user, | |
| create_access_token, | |
| create_refresh_token, | |
| decode_token, | |
| get_current_user, | |
| get_password_hash, | |
| is_token_revoked, | |
| revoke_token, | |
| require_role, | |
| ACCESS_TOKEN_MINUTES, | |
| DEMO_USERS, | |
| ) | |
| logger = logging.getLogger("tunechecker.api.auth") | |
| router = APIRouter(prefix="/auth", tags=["Authentication & RBAC"]) | |
| # ============================================================================= | |
| # Helper function to generate token response | |
| # ============================================================================= | |
| def _generate_token_response(user: User) -> Token: | |
| access_token = create_access_token( | |
| user_id=user.id, | |
| role=user.role, | |
| org_id=user.org_id, | |
| ) | |
| refresh_token = create_refresh_token( | |
| user_id=user.id, | |
| role=user.role, | |
| org_id=user.org_id, | |
| ) | |
| return Token( | |
| access_token=access_token, | |
| refresh_token=refresh_token, | |
| token_type="bearer", | |
| expires_in=ACCESS_TOKEN_MINUTES * 60, | |
| user=user, | |
| ) | |
| # ============================================================================= | |
| # Login Endpoint | |
| # ============================================================================= | |
| async def login( | |
| payload: Optional[LoginRequest] = None, | |
| form_data: Optional[OAuth2PasswordRequestForm] = Depends(lambda: None), | |
| ) -> Token: | |
| """Authenticates credentials against Enterprise DB / fallback and returns JWT access & refresh tokens.""" | |
| # Support both JSON payload and OAuth2 form_data | |
| email = "" | |
| password = "" | |
| if payload: | |
| email = payload.email | |
| password = payload.password | |
| elif form_data: | |
| email = form_data.username | |
| password = form_data.password | |
| if not email or not password: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail="Email/username and password are required.", | |
| ) | |
| user = await authenticate_user(email, password) | |
| if not user: | |
| logger.warning("Failed login attempt for: %s", email) | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid credentials. Verify your email and password.", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| if not user.is_active: | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="User account is deactivated.", | |
| ) | |
| logger.info("Successful authentication for user: %s (role: %s)", user.email, user.role.value) | |
| return _generate_token_response(user) | |
| # ============================================================================= | |
| # Refresh Token Rotation Endpoint | |
| # ============================================================================= | |
| async def refresh_token(payload: RefreshTokenRequest) -> Token: | |
| """Validates the refresh token, revokes the old one, and issues a fresh token pair. | |
| Implements true Refresh Token Rotation to prevent token reuse replay attacks. | |
| """ | |
| token_str = payload.refresh_token.strip() | |
| if not token_str: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail="Refresh token is required.", | |
| ) | |
| decoded = decode_token(token_str) | |
| token_type = decoded.get("type") | |
| if token_type != "refresh": | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Invalid token type: expected refresh token.", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| old_jti = decoded.get("jti") | |
| if old_jti and await is_token_revoked(old_jti): | |
| logger.error("Attempt to reuse revoked refresh token jti: %s", old_jti) | |
| raise HTTPException( | |
| status_code=status.HTTP_401_UNAUTHORIZED, | |
| detail="Refresh token has been revoked or already rotated.", | |
| headers={"WWW-Authenticate": "Bearer"}, | |
| ) | |
| # Invalidate the old refresh token (Token Rotation guarantee) | |
| if old_jti: | |
| await revoke_token(old_jti) | |
| user_id = decoded.get("sub") | |
| role_str = decoded.get("role", "SALES_REP") | |
| org_id = decoded.get("org_id", "org-default") | |
| user = User( | |
| id=user_id, | |
| email=f"{user_id}@tunechecker.io" if "@" not in user_id else user_id, | |
| full_name=user_id.capitalize(), | |
| role=UserRole.from_str(role_str), | |
| org_id=org_id, | |
| is_active=True, | |
| ) | |
| return _generate_token_response(user) | |
| # ============================================================================= | |
| # Registration / User Provisioning Endpoint | |
| # ============================================================================= | |
| async def register(payload: RegisterRequest) -> Token: | |
| """Registers a new user and returns authenticated JWT session.""" | |
| email = payload.email.strip().lower() | |
| hashed_pwd = get_password_hash(payload.password) | |
| role_enum = payload.role or UserRole.USER | |
| # Try inserting into Enterprise Postgres | |
| user_id = "" | |
| try: | |
| from app.db.enterprise.postgres import postgres_client | |
| if postgres_client: | |
| created = await postgres_client.create_user( | |
| email=email, | |
| hashed_password=hashed_pwd, | |
| full_name=payload.full_name, | |
| role=role_enum.value, | |
| org_id=payload.org_id or "org-default", | |
| ) | |
| user_id = created["id"] | |
| except ValueError as ve: | |
| raise HTTPException( | |
| status_code=status.HTTP_409_CONFLICT, | |
| detail=str(ve), | |
| ) | |
| except Exception as exc: | |
| logger.warning("Postgres register fallback to memory: %s", exc) | |
| if not user_id: | |
| if email in DEMO_USERS: | |
| raise HTTPException( | |
| status_code=status.HTTP_409_CONFLICT, | |
| detail="An account with this email already exists.", | |
| ) | |
| import uuid | |
| user_id = f"usr-{uuid.uuid4().hex[:12]}" | |
| # Add to DEMO_USERS memory cache | |
| DEMO_USERS[email] = { | |
| "id": user_id, | |
| "email": email, | |
| "full_name": payload.full_name, | |
| "role": role_enum, | |
| "org_id": payload.org_id or "org-default", | |
| "hashed_password": hashed_pwd, | |
| "is_active": True, | |
| } | |
| user = User( | |
| id=user_id, | |
| email=email, | |
| full_name=payload.full_name, | |
| role=role_enum, | |
| org_id=payload.org_id or "org-default", | |
| is_active=True, | |
| ) | |
| return _generate_token_response(user) | |
| # ============================================================================= | |
| # Current User Profile Endpoint | |
| # ============================================================================= | |
| async def get_me(current_user: User = Depends(get_current_user)) -> User: | |
| """Returns profile and role permissions of current user.""" | |
| return current_user | |
| # ============================================================================= | |
| # Logout & Revocation Endpoint | |
| # ============================================================================= | |
| class LogoutRequest(BaseModel): | |
| refresh_token: Optional[str] = None | |
| async def logout( | |
| request: Request, | |
| payload: Optional[LogoutRequest] = None, | |
| current_user: User = Depends(get_current_user), | |
| ) -> Dict[str, Any]: | |
| """Revokes access token and refresh token via Redis blacklisting.""" | |
| # Revoke access token | |
| auth_hdr = request.headers.get("Authorization", "") | |
| if auth_hdr.lower().startswith("bearer "): | |
| try: | |
| token = auth_hdr[7:].strip() | |
| decoded = decode_token(token) | |
| jti = decoded.get("jti") | |
| if jti: | |
| await revoke_token(jti, expires_in_sec=ACCESS_TOKEN_MINUTES * 60) | |
| except Exception: | |
| pass | |
| # Revoke refresh token if provided | |
| if payload and payload.refresh_token: | |
| try: | |
| r_decoded = decode_token(payload.refresh_token) | |
| r_jti = r_decoded.get("jti") | |
| if r_jti: | |
| await revoke_token(r_jti, expires_in_sec=86400 * 7) | |
| except Exception: | |
| pass | |
| return { | |
| "status": "success", | |
| "message": f"User {current_user.email} successfully logged out.", | |
| } | |
| # ============================================================================= | |
| # Available Roles Metadata Endpoint | |
| # ============================================================================= | |
| async def get_roles() -> Dict[str, Any]: | |
| """Returns the system RBAC permission matrix.""" | |
| return { | |
| "roles": [ | |
| { | |
| "name": UserRole.ADMIN.value, | |
| "description": "Full enterprise administrative access, user management, audit logs, configuration.", | |
| "permissions": ["all:read", "all:write", "admin:manage", "users:manage"], | |
| }, | |
| { | |
| "name": UserRole.MANAGER.value, | |
| "description": "Sales quality oversight, team reviews, coaching rule configuration, analytics.", | |
| "permissions": ["calls:read_all", "calls:review", "analytics:team", "coaching:manage"], | |
| }, | |
| { | |
| "name": UserRole.SALES_REP.value, | |
| "description": "Call upload, personal transcript review, feedback submission, performance telemetry.", | |
| "permissions": ["calls:upload", "calls:read_own", "feedback:submit", "telemetry:view"], | |
| }, | |
| ], | |
| "default_role": UserRole.SALES_REP.value, | |
| } | |
| # ============================================================================= | |
| # Role-Protected Verification Endpoint (For Testing RBAC Enforcement) | |
| # ============================================================================= | |
| async def admin_only_test(current_user: User = Depends(get_current_user)) -> Dict[str, Any]: | |
| return {"message": "Admin access granted", "user": current_user.email, "role": current_user.role} | |
| async def manager_only_test(current_user: User = Depends(get_current_user)) -> Dict[str, Any]: | |
| return {"message": "Manager access granted", "user": current_user.email, "role": current_user.role} | |