[docs]classAPIKeyManager:def__init__(self,keys_dir:str="data/apikeys"):self.keys_dir=Path(keys_dir)self.keys_dir.mkdir(parents=True,exist_ok=True)self._load_keys()def_load_keys(self)->None:"""Load all API keys from storage"""self.keys={}forkey_fileinself.keys_dir.glob("*.json"):try:withopen(key_file,'r')asf:key_data=json.load(f)self.keys[key_data['key']]=key_dataexceptjson.JSONDecodeError:print(f"Warning: Invalid JSON in key file: {key_file}")exceptExceptionase:print(f"Error loading key file {key_file}: {e}")
[docs]defcreate_key(self,username:str,description:str="")->Dict:"""Create a new API key for a user Args: username: The username to associate with the key description: Optional description for the key Returns: Dict containing the key details """api_key=str(uuid.uuid4())key_data={"key":api_key,"username":username,"description":description,"created_at":datetime.utcnow().isoformat()}# Save to filekey_file=self.keys_dir/f"{api_key}.json"withopen(key_file,'w')asf:json.dump(key_data,f,indent=4)self.keys[api_key]=key_datareturnkey_data
[docs]defvalidate_key(self,api_key:str)->Optional[Dict]:"""Validate an API key and return associated data if valid Args: api_key: The API key to validate Returns: Dict containing the key details if valid, None otherwise """print(f"Validating key: {api_key}")print("My keys are",self.keys)returnself.keys.get(api_key)
[docs]defdelete_key(self,api_key:str)->bool:"""Delete an API key Args: api_key: The API key to delete Returns: bool: True if key was deleted, False if key not found """ifapi_keyinself.keys:key_file=self.keys_dir/f"{api_key}.json"try:key_file.unlink(missing_ok=True)delself.keys[api_key]returnTrueexceptExceptionase:print(f"Error deleting key file {key_file}: {e}")returnFalsereturnFalse
[docs]deflist_keys(self,username:Optional[str]=None)->List[Dict]:"""List all API keys or keys for specific user Args: username: Optional username to filter keys by Returns: List of key data dictionaries """ifusername:return[kforkinself.keys.values()ifk['username']==username]returnlist(self.keys.values())