Spaces:
Running

File size: 3,577 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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)}