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

71 lines
1.8 KiB
Python
Raw Normal View History

2022-03-20 03:45:40 +00:00
"""
/admin endpoints.
"""
2022-03-18 18:22:17 +00:00
from fastapi import APIRouter, Depends, HTTPException, status
2022-03-18 22:43:02 +00:00
from ..config import Config
from ..db_new import Capability, Connection, User, UserCreate
from ._common import Responses, get_current_user_if_admin
2022-03-18 18:22:17 +00:00
2022-03-24 23:45:01 +00:00
router = APIRouter(prefix="/admin", tags=["admin"])
2022-03-18 18:22:17 +00:00
@router.put(
2022-03-19 17:11:52 +00:00
"/install",
2022-03-18 18:22:17 +00:00
responses={
2022-03-20 03:45:40 +00:00
status.HTTP_200_OK: Responses.OK,
status.HTTP_400_BAD_REQUEST: Responses.INSTALLED,
2022-03-18 18:22:17 +00:00
},
)
2022-03-19 17:11:52 +00:00
async def install(
config: Config,
# admin_user: UserCreate,
2022-03-19 02:38:32 +00:00
current_config: Config | None = Depends(Config.load),
2022-03-18 18:22:17 +00:00
):
2022-03-20 03:45:40 +00:00
"""
PUT ./install: Install `kiwi-vpn`.
"""
# fail if already installed
2022-03-18 18:22:17 +00:00
if current_config is not None:
2022-03-19 17:11:52 +00:00
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
2022-03-18 18:22:17 +00:00
2022-03-20 03:45:40 +00:00
# create config file, connect to database
2022-03-19 17:11:52 +00:00
await config.save()
Connection.connect("sqlite:///tmp/v2.db")
2022-03-18 18:22:17 +00:00
# # create an administrative user
# new_user = User.create(**admin_user)
# assert new_user is not None
# new_user.set_capabilities([Capability.login, Capability.admin])
# new_user.update()
2022-03-20 13:14:12 +00:00
2022-03-19 17:11:52 +00:00
@router.put(
"/config",
2022-03-18 18:22:17 +00:00
responses={
2022-03-20 03:45:40 +00:00
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,
2022-03-18 18:22:17 +00:00
},
)
2022-03-19 17:11:52 +00:00
async def set_config(
new_config: Config,
2022-03-19 02:38:32 +00:00
current_config: Config | None = Depends(Config.load),
_: User | None = Depends(get_current_user_if_admin),
2022-03-18 18:22:17 +00:00
):
2022-03-20 03:45:40 +00:00
"""
PUT ./config: Edit `kiwi-vpn` main config.
"""
# fail if not installed
2022-03-18 18:22:17 +00:00
if current_config is None:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
2022-03-20 03:45:40 +00:00
# update config file, reconnect to database
2022-03-19 17:11:52 +00:00
await new_config.save()
Connection.connect("sqlite:///tmp/v2.db")