from secrets import token_hex from fastapi import APIRouter, Depends, HTTPException, status from sqlalchemy.orm import Session from ..config import (CONFIG_FILE, BaseConfig, connect_db, get_db, has_config, load_config) from ..db import crud, schemas router = APIRouter(prefix="/install") @router.get( "/config", response_model=BaseConfig, responses={ status.HTTP_403_FORBIDDEN: { "description": "Must be admin", "content": None, }, }, ) async def get_config( config: BaseConfig = Depends(load_config), has_config: bool = Depends(has_config), ): if has_config: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN) return config @router.put( "/config", responses={ status.HTTP_200_OK: { "content": None, }, status.HTTP_403_FORBIDDEN: { "description": "Must be admin", "content": None, }, }, ) async def set_config( config: BaseConfig, has_config: bool = Depends(has_config), ): if has_config: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN) if config.jwt.secret is None: config.jwt.secret = token_hex(32) await connect_db(config) with open(CONFIG_FILE, "w") as kv: kv.write(config.json(indent=2)) @router.get("/db", responses={ status.HTTP_200_OK: { "model": bool, }, }) async def check_db(): return True @router.put( "/db", responses={ status.HTTP_200_OK: { "content": None, }, status.HTTP_400_BAD_REQUEST: { "description": "Database exists", "content": None, }, }, ) async def create_db( admin_name: str, admin_password: str, db: Session = Depends(get_db), ): # if await has_tables(db): # raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST) # db.create_tables([Certificate, DistinguishedName, User, UserCapability]) # cryptContext = await config.crypto.cryptContext crud.create_user(db, schemas.UserCreate( name=admin_name, password=admin_password, )) crud.add_user_capability(db, user_name=admin_name, capability="admin")