aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/src/meshbay_hub/api/deps.py
blob: addba308d84092cc11eda1f7418cf46115f20db3 (plain) (blame)
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
"""
FastAPI shared dependencies — injected via Depends().
"""

from fastapi import Depends, Header, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select

from meshbay_hub.auth import decode_access_token
from meshbay_hub.db.engine import get_db
from meshbay_hub.db.models import User

_admin_usernames: set[str] = set()


def set_admin_usernames(usernames: list[str]) -> None:
    global _admin_usernames
    _admin_usernames = set(usernames)


async def get_current_user(
    authorization: str = Header(...),
    db: AsyncSession = Depends(get_db),
) -> User:
    """
    Verify the JWT bearer token and return the User from the database.
    Node clients: verified locally with hub PK — no DB round-trip needed.
    Hub API (web): must confirm user still exists and is active.
    """
    try:
        scheme, token = authorization.split(None, 1)
        if scheme.lower() != "bearer":
            raise ValueError
        payload = decode_access_token(token)
    except Exception:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid or expired token",
            headers={"WWW-Authenticate": "Bearer"},
        )

    result = await db.execute(
        select(User).where(User.id == payload["sub"]))
    user = result.scalar_one_or_none()

    if user is None:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,
                            detail="User not found")
    if user.status != "active":
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,
                            detail=f"Account {user.status}")
    return user


async def require_moderator(
    current_user: User = Depends(get_current_user),
) -> User:
    if current_user.role not in ("moderator", "admin") \
       and current_user.username not in _admin_usernames:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,
                            detail="Moderator access required")
    return current_user


async def require_admin(
    current_user: User = Depends(get_current_user),
) -> User:
    if current_user.role != "admin" \
       and current_user.username not in _admin_usernames:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN,
                            detail="Admin access required")
    return current_user