From 30fea07fe4d35a0ff1a0e8f674a013bc86701ed9 Mon Sep 17 00:00:00 2001 From: profitroll Date: Mon, 16 Jan 2023 15:22:51 +0100 Subject: [PATCH] Keys management improved --- extensions/apikey.py | 30 ++++++++++++++++++++++++++++++ models/apikey.py | 4 ++++ 2 files changed, 34 insertions(+) create mode 100644 extensions/apikey.py create mode 100644 models/apikey.py diff --git a/extensions/apikey.py b/extensions/apikey.py new file mode 100644 index 0000000..70fcada --- /dev/null +++ b/extensions/apikey.py @@ -0,0 +1,30 @@ +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}) \ No newline at end of file diff --git a/models/apikey.py b/models/apikey.py new file mode 100644 index 0000000..500c3bc --- /dev/null +++ b/models/apikey.py @@ -0,0 +1,4 @@ +from pydantic import BaseModel + +class APIKeyUpdated(BaseModel): + apikey: str \ No newline at end of file