from fastapi import APIRouter from shared.firebase import get_db from auth.models import LoginRequest, TokenResponse from auth.utils import verify_password, create_access_token from shared.exceptions import AuthenticationError router = APIRouter(prefix="/api/auth", tags=["auth"]) @router.post("/login", response_model=TokenResponse) async def login(body: LoginRequest): db = get_db() if not db: raise AuthenticationError("Service unavailable") users_ref = db.collection("admin_users") query = users_ref.where("email", "==", body.email).limit(1).get() if not query: raise AuthenticationError("Invalid email or password") doc = query[0] user_data = doc.to_dict() if not user_data.get("is_active", True): raise AuthenticationError("Account is disabled") if not verify_password(body.password, user_data["hashed_password"]): raise AuthenticationError("Invalid email or password") token = create_access_token({ "sub": doc.id, "email": user_data["email"], "role": user_data["role"], "name": user_data["name"], }) return TokenResponse( access_token=token, role=user_data["role"], name=user_data["name"], )