kiwi-vpn/api/kiwi_vpn_api/routers/admin.py
2022-03-24 23:45:01 +00:00

81 lines
2.1 KiB
Python

"""
/admin endpoints.
"""
from fastapi import APIRouter, Depends, HTTPException, status
from ..config import Config
from ..db import Connection
from ..db.schemas import User, UserCapability, UserCreate
from ._common import Responses, get_current_user
router = APIRouter(prefix="/admin", tags=["admin"])
@router.put(
"/install",
responses={
status.HTTP_200_OK: Responses.OK,
status.HTTP_400_BAD_REQUEST: Responses.INSTALLED,
},
)
async def install(
config: Config,
admin_user: UserCreate,
current_config: Config | None = Depends(Config.load),
):
"""
PUT ./install: Install `kiwi-vpn`.
"""
# fail if already installed
if current_config is not None:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
# create config file, connect to database
await config.save()
Connection.connect(await config.db.db_engine)
# create an administrative user
with Connection.use() as db:
new_user = User.create(
db=db,
user=admin_user,
crypt_context=await config.crypto.crypt_context,
)
new_user.capabilities.append(UserCapability.admin)
new_user.update(db)
@router.put(
"/config",
responses={
status.HTTP_200_OK: Responses.OK,
status.HTTP_400_BAD_REQUEST: Responses.NOT_INSTALLED,
status.HTTP_401_UNAUTHORIZED: Responses.NEEDS_USER,
status.HTTP_403_FORBIDDEN: Responses.NEEDS_ADMIN,
},
)
async def set_config(
new_config: Config,
current_config: Config | None = Depends(Config.load),
current_user: User | None = Depends(get_current_user),
):
"""
PUT ./config: Edit `kiwi-vpn` main config.
"""
# fail if not installed
if current_config is None:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
# fail if not requested by an admin
if (current_user is None
or UserCapability.admin not in current_user.capabilities):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
# update config file, reconnect to database
await new_config.save()
Connection.connect(await new_config.db.db_engine)