from datetime import datetime, timedelta from typing import Optional from uuid import UUID from jose import JWTError, jwt from passlib.context import CryptContext from fastapi import Depends, HTTPException, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import select from app.config import get_settings from app.database import get_db from app.models.models import User settings = get_settings() pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") security = HTTPBearer() def hash_password(password: str) -> str: return pwd_context.hash(password) def verify_password(plain: str, hashed: str) -> bool: return pwd_context.verify(plain, hashed) def create_access_token(user_id: UUID, role: str, expires_delta: Optional[timedelta] = None) -> str: expire = datetime.utcnow() + (expires_delta or timedelta(minutes=settings.JWT_EXPIRATION_MINUTES)) payload = { "sub": str(user_id), "role": role, "exp": expire, } return jwt.encode(payload, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM) def decode_token(token: str) -> dict: try: return jwt.decode(token, settings.JWT_SECRET, algorithms=[settings.JWT_ALGORITHM]) except JWTError: raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") async def get_current_user( credentials: HTTPAuthorizationCredentials = Depends(security), db: AsyncSession = Depends(get_db), ) -> User: payload = decode_token(credentials.credentials) user_id = payload.get("sub") result = await db.execute(select(User).where(User.id == UUID(user_id))) user = result.scalar_one_or_none() if not user or user.deleted_at: raise HTTPException(status_code=401, detail="User not found") return user class RequireRole: def __init__(self, *allowed_roles: str): self.allowed_roles = allowed_roles async def __call__(self, user: User = Depends(get_current_user)) -> User: if user.role not in self.allowed_roles: raise HTTPException(status_code=403, detail="Insufficient permissions") return user require_admin = RequireRole("admin") require_editor = RequireRole("admin", "editor") require_viewer = RequireRole("admin", "editor", "viewer")