from __future__ import annotations import uuid from fastapi import APIRouter, Depends, HTTPException, status from core.api.schemas import LoginIn, RefreshIn, SignupIn, StepUpIn, TokenPair from core.auth.deps import Principal, current_principal, get_db from core.auth.jwt import TokenError, decode_token, issue_token from core.auth.stepup import issue_stepup_token, new_totp_secret, verify_totp from core.db.session import Database from core.tenancy.models import User from core.tenancy.service import AuthError, authenticate, memberships_for, signup router = APIRouter(prefix="/auth", tags=["auth"]) def _pair(user_id: uuid.UUID, tenant_id: uuid.UUID) -> TokenPair: return TokenPair( access_token=issue_token(user_id, tenant_id, "access"), refresh_token=issue_token(user_id, tenant_id, "refresh"), tenant_id=tenant_id, ) @router.post("/signup", response_model=TokenPair, status_code=201) async def signup_route(body: SignupIn, db: Database = Depends(get_db)) -> TokenPair: try: res = await signup( db, business_name=body.business_name, email=body.email, password=body.password ) except AuthError as exc: raise HTTPException(status.HTTP_409_CONFLICT, str(exc)) from exc return _pair(res.user_id, res.tenant_id) @router.post("/login", response_model=TokenPair) async def login(body: LoginIn, db: Database = Depends(get_db)) -> TokenPair: try: user = await authenticate(db, body.email, body.password) except AuthError as exc: raise HTTPException(status.HTTP_401_UNAUTHORIZED, "invalid credentials") from exc tenants = [m.tenant_id for m in await memberships_for(db, user.id)] if not tenants: raise HTTPException(status.HTTP_403_FORBIDDEN, "no workspace") tenant_id = body.tenant_id or tenants[0] if tenant_id not in tenants: raise HTTPException(status.HTTP_403_FORBIDDEN, "not a member of this tenant") return _pair(user.id, tenant_id) @router.post("/refresh", response_model=TokenPair) async def refresh(body: RefreshIn, db: Database = Depends(get_db)) -> TokenPair: try: payload = decode_token(body.refresh_token, "refresh") except TokenError as exc: raise HTTPException(status.HTTP_401_UNAUTHORIZED, "invalid token") from exc user_id, tenant_id = uuid.UUID(payload["sub"]), uuid.UUID(payload["tid"]) if tenant_id not in [m.tenant_id for m in await memberships_for(db, user_id)]: raise HTTPException(status.HTTP_403_FORBIDDEN, "membership revoked") return _pair(user_id, tenant_id) @router.post("/totp/enroll") async def enroll_totp( p: Principal = Depends(current_principal), db: Database = Depends(get_db) ) -> dict[str, str]: secret = new_totp_secret() async with db.session() as s, s.begin(): user = await s.get(User, p.user_id) if user is None: raise HTTPException(status.HTTP_404_NOT_FOUND, "user not found") user.totp_secret = secret return {"secret": secret} @router.post("/stepup") async def stepup( body: StepUpIn, p: Principal = Depends(current_principal), db: Database = Depends(get_db) ) -> dict[str, str]: async with db.session() as s: user = await s.get(User, p.user_id) if user is None or not user.totp_secret or not verify_totp(user.totp_secret, body.code): raise HTTPException(status.HTTP_401_UNAUTHORIZED, "invalid code") return {"stepup_token": issue_stepup_token(p.user_id, p.tenant_id)}