70 lines
1.8 KiB
Python
70 lines
1.8 KiB
Python
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, schemas
|
|
from . import _deps
|
|
|
|
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.load),
|
|
current_user: schemas.User | None = Depends(_deps.get_current_user),
|
|
):
|
|
print(current_config, current_user)
|
|
|
|
if current_config is not None:
|
|
# 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)
|
|
|
|
if new_config.jwt.secret is None:
|
|
new_config.jwt.secret = token_hex(32)
|
|
|
|
await new_config.save()
|
|
Connection.connect(await new_config.db.db_engine)
|
|
|
|
|
|
@router.post(
|
|
"/user",
|
|
responses={
|
|
status.HTTP_200_OK: {
|
|
"content": None,
|
|
},
|
|
status.HTTP_400_BAD_REQUEST: {
|
|
"description": "Server is not configured",
|
|
"content": None,
|
|
},
|
|
},
|
|
)
|
|
async def add_user(
|
|
user: schemas.UserCreate,
|
|
current_config: Config | None = Depends(Config.load),
|
|
db: Session | None = Depends(Connection.get),
|
|
):
|
|
if current_config is None:
|
|
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST)
|
|
|
|
user.capabilities.append("admin")
|
|
|
|
schemas.User.create(
|
|
db=db,
|
|
user=user,
|
|
crypt_context=await current_config.crypto.crypt_context,
|
|
)
|