kiwi-vpn/api/kiwi_vpn_api/routers/user.py

53 lines
1.5 KiB
Python

from __future__ import annotations
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, status
from jose import JWTError, jwt
from kiwi_vpn_api.routers.auth import SCHEME
from kiwi_vpn_api.config import ALGORITHM, SECRET_KEY
from kiwi_vpn_api.db.model import User as db_User
from pydantic import BaseModel
router = APIRouter(prefix="/user")
class User(BaseModel):
name: str
capabilities: list[str]
@classmethod
def from_db(cls, username: str) -> Optional[User]:
user = db_User.get_by_name(username)
if not user:
return None
return cls(
name=user.name,
capabilities=[cap.capability for cap in user.capabilities],
)
async def get_current_user(token: str = Depends(SCHEME)):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
except JWTError:
raise credentials_exception
user = User.from_db(username)
if user is None:
raise credentials_exception
return user
@router.get("/current", response_model=User)
async def get_current_user(current_user: User = Depends(get_current_user)):
return current_user