mirror of
https://github.com/not-lucky/GeminiKeyManagement.git
synced 2025-12-06 08:44:01 +05:30
better format; using ruff now
This commit is contained in:
@@ -6,23 +6,24 @@ Implements:
|
||||
- Key lifecycle tracking
|
||||
- Data versioning and backup
|
||||
"""
|
||||
|
||||
import os
|
||||
import json
|
||||
import logging
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
import jsonschema
|
||||
from . import config
|
||||
|
||||
|
||||
def load_schema(filename):
|
||||
"""Validates and loads JSON schema definition.
|
||||
|
||||
|
||||
Args:
|
||||
filename (str): Path to schema file
|
||||
|
||||
|
||||
Returns:
|
||||
dict: Parsed schema document
|
||||
|
||||
|
||||
Exits:
|
||||
SystemExit: On invalid schema file
|
||||
"""
|
||||
@@ -36,13 +37,11 @@ def load_schema(filename):
|
||||
logging.error(f"Could not decode JSON schema from {filename}.")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def load_keys_database(filename, schema):
|
||||
"""Loads and validates the JSON database of API keys."""
|
||||
if not os.path.exists(filename):
|
||||
return {
|
||||
"schema_version": "1.0.0",
|
||||
"accounts": []
|
||||
}
|
||||
return {"schema_version": "1.0.0", "accounts": []}
|
||||
with open(filename, "r") as f:
|
||||
try:
|
||||
data = json.load(f)
|
||||
@@ -51,12 +50,12 @@ def load_keys_database(filename, schema):
|
||||
except json.JSONDecodeError:
|
||||
logging.warning(f"Could not decode JSON from {filename}. Starting fresh.")
|
||||
except jsonschema.ValidationError as e:
|
||||
logging.warning(f"Database file '{filename}' is not valid. {e.message}. Starting fresh.")
|
||||
|
||||
return {
|
||||
"schema_version": "1.0.0",
|
||||
"accounts": []
|
||||
}
|
||||
logging.warning(
|
||||
f"Database file '{filename}' is not valid. {e.message}. Starting fresh."
|
||||
)
|
||||
|
||||
return {"schema_version": "1.0.0", "accounts": []}
|
||||
|
||||
|
||||
def save_keys_to_json(data, filename, schema):
|
||||
"""Validates and saves the API key data to a single JSON file."""
|
||||
@@ -73,20 +72,28 @@ def save_keys_to_json(data, filename, schema):
|
||||
logging.error(f"Validation Error: {e.message}")
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def add_key_to_database(account_entry, project, key_object):
|
||||
"""Adds a new API key's details to the data structure."""
|
||||
project_id = project.project_id
|
||||
|
||||
project_entry = next((p for p in account_entry["projects"] if p.get("project_info", {}).get("project_id") == project_id), None)
|
||||
project_entry = next(
|
||||
(
|
||||
p
|
||||
for p in account_entry["projects"]
|
||||
if p.get("project_info", {}).get("project_id") == project_id
|
||||
),
|
||||
None,
|
||||
)
|
||||
if not project_entry:
|
||||
project_entry = {
|
||||
"project_info": {
|
||||
"project_id": project_id,
|
||||
"project_name": project.display_name,
|
||||
"project_number": project.name.split('/')[-1],
|
||||
"state": str(project.state)
|
||||
"project_number": project.name.split("/")[-1],
|
||||
"state": str(project.state),
|
||||
},
|
||||
"api_keys": []
|
||||
"api_keys": [],
|
||||
}
|
||||
account_entry["projects"].append(project_entry)
|
||||
|
||||
@@ -104,31 +111,51 @@ def add_key_to_database(account_entry, project, key_object):
|
||||
"creation_timestamp_utc": key_object.create_time.isoformat(),
|
||||
"last_updated_timestamp_utc": key_object.update_time.isoformat(),
|
||||
},
|
||||
"restrictions": {
|
||||
"api_targets": api_targets
|
||||
},
|
||||
"state": "ACTIVE"
|
||||
"restrictions": {"api_targets": api_targets},
|
||||
"state": "ACTIVE",
|
||||
}
|
||||
|
||||
existing_key = next((k for k in project_entry["api_keys"] if k.get("key_details", {}).get("key_id") == key_object.uid), None)
|
||||
existing_key = next(
|
||||
(
|
||||
k
|
||||
for k in project_entry["api_keys"]
|
||||
if k.get("key_details", {}).get("key_id") == key_object.uid
|
||||
),
|
||||
None,
|
||||
)
|
||||
if not existing_key:
|
||||
project_entry["api_keys"].append(new_key_entry)
|
||||
logging.info(f" Added key {key_object.uid} to local database for project {project_id}")
|
||||
logging.info(
|
||||
f" Added key {key_object.uid} to local database for project {project_id}"
|
||||
)
|
||||
else:
|
||||
logging.warning(f" Key {key_object.uid} already exists in local database for project {project_id}")
|
||||
logging.warning(
|
||||
f" Key {key_object.uid} already exists in local database for project {project_id}"
|
||||
)
|
||||
|
||||
|
||||
def remove_keys_from_database(account_entry, project_id, deleted_keys_uids):
|
||||
"""Removes deleted API keys from the data structure."""
|
||||
project_entry = next((p for p in account_entry["projects"] if p.get("project_info", {}).get("project_id") == project_id), None)
|
||||
project_entry = next(
|
||||
(
|
||||
p
|
||||
for p in account_entry["projects"]
|
||||
if p.get("project_info", {}).get("project_id") == project_id
|
||||
),
|
||||
None,
|
||||
)
|
||||
if not project_entry:
|
||||
return
|
||||
|
||||
initial_key_count = len(project_entry["api_keys"])
|
||||
project_entry["api_keys"] = [
|
||||
key for key in project_entry["api_keys"]
|
||||
key
|
||||
for key in project_entry["api_keys"]
|
||||
if key.get("key_details", {}).get("key_id") not in deleted_keys_uids
|
||||
]
|
||||
final_key_count = len(project_entry["api_keys"])
|
||||
num_removed = initial_key_count - final_key_count
|
||||
if num_removed > 0:
|
||||
logging.info(f" Removed {num_removed} key(s) from local database for project {project_id}")
|
||||
logging.info(
|
||||
f" Removed {num_removed} key(s) from local database for project {project_id}"
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user