"""
Credential management utilities for Active Directory tools
"""
import json
import os
from datetime import datetime
from pathlib import Path
from typing import Dict, List, Optional, Any
from dataclasses import dataclass, asdict
@dataclass
class Credential:
"""Represents a discovered credential"""
username: str
secret: str
credential_type: str
source: str
metadata: Optional[Dict[str, Any]] = None
timestamp: Optional[str] = None
def __post_init__(self):
if self.timestamp is None:
self.timestamp = datetime.now().isoformat()
def store_credential(credential: Credential) -> bool:
"""
Store a credential in the credential database
"""
try:
cred_file = _get_cred_file()
credentials = _load_credentials()
credentials.append(asdict(credential))
with open(cred_file, 'w', encoding='utf-8') as f:
json.dump(credentials, f, indent=2, ensure_ascii=False)
return True
except Exception as e:
print(f"Error storing credential: {e}")
return False
def get_credentials(
credential_type: Optional[str] = None,
source: Optional[str] = None,
username: Optional[str] = None
) -> List[Dict[str, Any]]:
"""
Retrieve credentials from the database with optional filtering
"""
try:
credentials = _load_credentials()
filtered = credentials
if credential_type:
filtered = [c for c in filtered if c.get('credential_type') == credential_type]
if source:
filtered = [c for c in filtered if c.get('source') == source]
if username:
filtered = [c for c in filtered if c.get('username') == username]
return filtered
except Exception as e:
print(f"Error retrieving credentials: {e}")
return []
def _get_cred_file() -> Path:
"""Get the path to the credentials file"""
cred_dir = Path.home() / ".ad_tools"
cred_dir.mkdir(exist_ok=True)
return cred_dir / "credentials.json"
def _load_credentials() -> List[Dict[str, Any]]:
"""Load credentials from file"""
cred_file = _get_cred_file()
if not cred_file.exists():
return []
try:
with open(cred_file, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception:
return []