feat(api): implement secure API key management with encryption and CRUD operations

This commit is contained in:
Davidson Gomes
2025-05-07 13:08:59 -03:00
parent 72f666aca1
commit 17b4c20a4c
15 changed files with 773 additions and 141 deletions
+17 -14
View File
@@ -16,64 +16,67 @@ from dotenv import load_dotenv
from src.models.models import User
from src.utils.security import get_password_hash
# Configurar logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
def create_admin_user():
"""Create an initial admin user in the system"""
try:
# Load environment variables
load_dotenv()
# Get database settings
db_url = os.getenv("POSTGRES_CONNECTION_STRING")
if not db_url:
logger.error("Environment variable POSTGRES_CONNECTION_STRING not defined")
return False
# Get admin password
admin_password = os.getenv("ADMIN_INITIAL_PASSWORD")
if not admin_password:
logger.error("Environment variable ADMIN_INITIAL_PASSWORD not defined")
return False
# Admin email configuration
admin_email = os.getenv("ADMIN_EMAIL", "admin@evoai.com")
# Connect to the database
engine = create_engine(db_url)
Session = sessionmaker(bind=engine)
session = Session()
# Verificar se o administrador já existe
# Verify if the admin already exists
existing_admin = session.query(User).filter(User.email == admin_email).first()
if existing_admin:
logger.info(f"Admin with email {admin_email} already exists")
return True
# Create admin
admin_user = User(
email=admin_email,
password_hash=get_password_hash(admin_password),
is_admin=True,
is_active=True,
email_verified=True
email_verified=True,
)
# Add and commit
session.add(admin_user)
session.commit()
logger.info(f"Admin created successfully: {admin_email}")
return True
except Exception as e:
logger.error(f"Error creating admin: {str(e)}")
return False
finally:
session.close()
if __name__ == "__main__":
success = create_admin_user()
sys.exit(0 if success else 1)
sys.exit(0 if success else 1)
-1
View File
@@ -19,7 +19,6 @@ from dotenv import load_dotenv
from src.models.models import User, Client
from src.utils.security import get_password_hash
# Configurar logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
-1
View File
@@ -16,7 +16,6 @@ from sqlalchemy.exc import SQLAlchemyError
from dotenv import load_dotenv
from src.models.models import MCPServer
# Configure logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
+18 -14
View File
@@ -14,64 +14,68 @@ from dotenv import load_dotenv
from src.models.models import Tool
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
def create_tools():
"""Cria ferramentas padrão no sistema"""
"""Create default tools in the system"""
try:
# Load environment variables
load_dotenv()
# Get database settings
db_url = os.getenv("POSTGRES_CONNECTION_STRING")
if not db_url:
logger.error("Environment variable POSTGRES_CONNECTION_STRING not defined")
return False
# Connect to the database
engine = create_engine(db_url)
Session = sessionmaker(bind=engine)
session = Session()
try:
# Check if there are already tools
existing_tools = session.query(Tool).all()
if existing_tools:
logger.info(f"There are already {len(existing_tools)} tools registered")
return True
# Tools definitions
tools = []
# Create the tools
for tool_data in tools:
tool = Tool(
name=tool_data["name"],
description=tool_data["description"],
config_json=tool_data["config_json"],
environments=tool_data["environments"]
environments=tool_data["environments"],
)
session.add(tool)
logger.info(f"Tool '{tool_data['name']}' created successfully")
session.commit()
logger.info("All tools were created successfully")
return True
except SQLAlchemyError as e:
session.rollback()
logger.error(f"Database error when creating tools: {str(e)}")
return False
except Exception as e:
logger.error(f"Error when creating tools: {str(e)}")
return False
finally:
session.close()
if __name__ == "__main__":
success = create_tools()
sys.exit(0 if success else 1)
sys.exit(0 if success else 1)