from secrets import token_hex from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.orm import Session from ..config import Config from ..db import connection, crud, schemas 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( new_config: Config, current_config: Config | None = Depends(Config.get), ): 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) Config.set(new_config) @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, current_config: Config | None = Depends(Config.get), 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, ), capabilities=["admin"], crypt_context=current_config.crypt_context, )