69 lines
2.2 KiB
Python
69 lines
2.2 KiB
Python
import os
|
|
import sys
|
|
import hmac
|
|
import hashlib
|
|
import secrets
|
|
import string
|
|
|
|
# Add the project root to the Python path
|
|
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
|
|
# Get the API key secret from environment
|
|
from src.core.config import settings
|
|
|
|
def generate_api_key(team_id="dev-team", user_id="dev-admin"):
|
|
"""
|
|
Generate a secure API key and its hashed value
|
|
|
|
Args:
|
|
team_id: Team ID for which the key is generated
|
|
user_id: User ID for which the key is generated
|
|
|
|
Returns:
|
|
Tuple of (raw_api_key, hashed_api_key)
|
|
"""
|
|
# Generate a random key prefix (visible part)
|
|
prefix = ''.join(secrets.choice(string.ascii_letters + string.digits) for _ in range(8))
|
|
|
|
# Generate a secure random token for the key
|
|
random_part = secrets.token_hex(16)
|
|
|
|
# Format: prefix.random_part
|
|
raw_api_key = f"{prefix}.{random_part}"
|
|
|
|
# Hash the API key for storage
|
|
hashed_api_key = hash_api_key(raw_api_key)
|
|
|
|
return raw_api_key, hashed_api_key
|
|
|
|
def hash_api_key(api_key: str) -> str:
|
|
"""
|
|
Create a secure hash of the API key for storage
|
|
|
|
Args:
|
|
api_key: The raw API key
|
|
|
|
Returns:
|
|
Hashed API key
|
|
"""
|
|
return hmac.new(
|
|
settings.API_KEY_SECRET.encode(),
|
|
api_key.encode(),
|
|
hashlib.sha256
|
|
).hexdigest()
|
|
|
|
if __name__ == "__main__":
|
|
# Generate a development API key
|
|
api_key, key_hash = generate_api_key()
|
|
|
|
print("\n====== DEVELOPMENT API KEY ======")
|
|
print(f"API Key: {api_key}")
|
|
print(f"Key Hash: {key_hash}")
|
|
print("\nCOPY THIS API KEY AND USE IT IN YOUR SWAGGER UI!")
|
|
print("Header Name: X-API-Key")
|
|
print("Header Value: <the API key value above>")
|
|
print("===============================")
|
|
print("\nNote: This is a generated key, but since there's no database setup,")
|
|
print("you won't be able to use it with the API until the key is added to the database.")
|
|
print("This would be useful if you developed a bypass_auth mode for development.")
|
|
print("For now, please check with the development team for API key access.") |