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

69 lines
1.6 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 18:24:09 +00:00
from ..db import connection, crud, 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,
current_config: Config | None = Depends(Config.get),
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)
connection.reconnect(new_config.db_engine)
2022-03-18 22:43:02 +00:00
Config.set(new_config)
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(
user_name: str,
user_password: str,
2022-03-18 22:43:02 +00:00
current_config: Config | None = Depends(Config.get),
2022-03-18 18:22:17 +00:00
db: Session | None = Depends(connection.get),
):
if current_config is None:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
crud.create_user(
db=db,
user=schemas.UserCreate(
name=user_name,
password=user_password,
),
2022-03-18 19:15:45 +00:00
capabilities=["admin"],
2022-03-18 18:22:17 +00:00
crypt_context=current_config.crypt_context,
)