image_management_api/scripts/verify_api_key.py
2025-05-24 12:06:57 +02:00

80 lines
2.7 KiB
Python

#!/usr/bin/env python3
"""
Script to verify an API key against the database.
"""
import os
import sys
import asyncio
import logging
import argparse
from datetime import datetime
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Add the parent directory to the path so we can import from src
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from src.db.providers.firestore_provider import firestore_db
from src.db.repositories.firestore_api_key_repository import firestore_api_key_repository
from src.db.repositories.firestore_user_repository import firestore_user_repository
from src.auth.security import hash_api_key, verify_api_key
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
)
logger = logging.getLogger(__name__)
async def verify_key(api_key):
"""Verify an API key against the database"""
try:
# Connect to Firestore
firestore_db.connect()
# Hash the API key for database lookup
key_hash = hash_api_key(api_key)
logger.info(f"Looking up key with hash: {key_hash}")
# Get all API keys to test manually
all_keys = await firestore_api_key_repository.get_all()
print(f"Found {len(all_keys)} API keys in the database.")
for idx, key in enumerate(all_keys):
print(f"Key {idx+1}: name={key.name}, hash={key.key_hash}")
is_match = verify_api_key(api_key, key.key_hash)
print(f" Match with input key: {is_match}")
if is_match:
print(f" Found matching key: {key.name} (ID: {key.id})")
user = await firestore_user_repository.get_by_id(key.user_id)
if user:
print(f" User: {user.name} (ID: {user.id})")
print(f" User is admin: {user.is_admin}")
print("\nTesting key hash calculation:")
test_hash = hash_api_key(api_key)
print(f"Input key: {api_key}")
print(f"Calculated hash: {test_hash}")
except Exception as e:
logger.error(f"Error verifying API key: {e}")
raise
finally:
# Disconnect from Firestore
firestore_db.disconnect()
def main():
"""Main entry point"""
parser = argparse.ArgumentParser(description="Verify an API key against the database")
parser.add_argument("api_key", help="API key to verify")
args = parser.parse_args()
asyncio.run(verify_key(args.api_key))
if __name__ == "__main__":
main()