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-19 04:07:19 +00:00
|
|
|
from . import _deps
|
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-19 04:07:19 +00:00
|
|
|
current_user: schemas.User | None = Depends(_deps.get_current_user),
|
2022-03-18 18:22:17 +00:00
|
|
|
):
|
2022-03-19 04:07:19 +00:00
|
|
|
print(current_config, current_user)
|
|
|
|
|
2022-03-18 18:22:17 +00:00
|
|
|
if current_config is not None:
|
2022-03-19 04:07:19 +00:00
|
|
|
# server is configured, needs authorization
|
|
|
|
if current_user is None or "admin" not in current_user.capabilities:
|
|
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
|
2022-03-18 18:22:17 +00:00
|
|
|
|
|
|
|
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: {
|
2022-03-19 04:07:19 +00:00
|
|
|
"description": "Server is not configured",
|
2022-03-18 18:22:17 +00:00
|
|
|
"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
|
|
|
)
|