SyncAPI/extensions/apikey.py

30 lines
1.2 KiB
Python

from os import path
from uuid import uuid4
from shutil import move
from models.apikey import APIKeyUpdated
from modules.app import app, get_api_key
from modules.utils import configGet, jsonLoad, jsonSave
from fastapi import Depends
from fastapi.responses import UJSONResponse
from fastapi.openapi.models import APIKey
@app.put("/apikey", response_class=UJSONResponse, response_model=APIKeyUpdated, description="Update API key")
async def apikey_put(apikey: APIKey = Depends(get_api_key)):
keys_valid = jsonLoad(path.join(configGet("data", "locations"), "api_keys.json"))
keys_expired = jsonLoad(path.join(configGet("data", "locations"), "expired_keys.json"))
new_key = str(uuid4())
keys_valid.remove(apikey)
keys_valid.append(new_key)
keys_expired.append(apikey)
jsonSave(keys_valid, path.join(configGet("data", "locations"), "api_keys.json"))
jsonSave(keys_expired, path.join(configGet("data", "locations"), "expired_keys.json"))
if path.exists(path.join(configGet("data", "locations"), apikey)): # type: ignore
move(path.join(configGet("data", "locations"), apikey), path.join(configGet("data", "locations"), new_key)) # type: ignore
return UJSONResponse({"apikey": new_key})