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

65 lines
1.5 KiB
Python
Raw Normal View History

2022-03-18 18:22:17 +00:00
from secrets import token_hex
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
2022-03-18 22:43:02 +00:00
from ..config import Config
2022-03-18 23:45:09 +00:00
from ..db import Connection, schemas
2022-03-18 18:22:17 +00:00
router = APIRouter(prefix="/admin")
@router.put(
"/config",
responses={
status.HTTP_200_OK: {
"content": None,
},
status.HTTP_403_FORBIDDEN: {
"description": "Must be admin",
"content": None,
},
},
)
async def set_config(
2022-03-18 22:43:02 +00:00
new_config: Config,
2022-03-19 02:38:32 +00:00
current_config: Config | None = Depends(Config.load),
2022-03-18 18:22:17 +00:00
):
if current_config is not None:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
if new_config.jwt.secret is None:
new_config.jwt.secret = token_hex(32)
2022-03-19 02:38:32 +00:00
await new_config.save()
2022-03-19 02:28:18 +00:00
Connection.connect(await new_config.db.db_engine)
2022-03-18 18:22:17 +00:00
@router.post(
"/user",
responses={
status.HTTP_200_OK: {
"content": None,
},
status.HTTP_400_BAD_REQUEST: {
"description": "Database doesn't exist",
"content": None,
},
},
)
async def add_user(
2022-03-19 03:31:41 +00:00
user: schemas.UserCreate,
2022-03-19 02:38:32 +00:00
current_config: Config | None = Depends(Config.load),
2022-03-18 23:04:28 +00:00
db: Session | None = Depends(Connection.get),
2022-03-18 18:22:17 +00:00
):
if current_config is None:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
2022-03-19 03:31:41 +00:00
user.capabilities.append("admin")
2022-03-18 23:45:09 +00:00
schemas.User.create(
2022-03-18 18:22:17 +00:00
db=db,
2022-03-19 03:31:41 +00:00
user=user,
2022-03-19 02:28:18 +00:00
crypt_context=await current_config.crypto.crypt_context,
2022-03-18 18:22:17 +00:00
)