kiwi-vpn/api/kiwi_vpn_api/routers/admin.py
2022-03-20 02:32:40 +00:00

64 lines
1.8 KiB
Python

from fastapi import APIRouter, Depends, HTTPException, status
from ..config import Config
from ..db import Connection
from ..db.schemas import User, UserCapability, UserCreate
from . import _deps
router = APIRouter(prefix="/admin")
@router.put(
"/install",
responses={
status.HTTP_200_OK: _deps.Responses.ok,
status.HTTP_400_BAD_REQUEST: _deps.Responses.installed,
},
)
async def install(
config: Config,
admin_user: UserCreate,
current_config: Config | None = Depends(Config.load),
):
if current_config is not None:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
await config.save()
Connection.connect(await config.db.db_engine)
with Connection.use() as db:
admin_user = User.create(
db=db,
user=admin_user,
crypt_context=await config.crypto.crypt_context,
)
admin_user.add_capabilities(
db=db,
capabilities=[UserCapability.admin],
)
@router.put(
"/config",
responses={
status.HTTP_200_OK: _deps.Responses.ok,
status.HTTP_400_BAD_REQUEST: _deps.Responses.not_installed,
status.HTTP_401_UNAUTHORIZED: _deps.Responses.needs_user,
status.HTTP_403_FORBIDDEN: _deps.Responses.needs_admin,
},
)
async def set_config(
new_config: Config,
current_config: Config | None = Depends(Config.load),
current_user: User | None = Depends(_deps.get_current_user),
):
if current_config is None:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
if (current_user is None
or UserCapability.admin not in current_user.capabilities):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
await new_config.save()
Connection.connect(await new_config.db.db_engine)