Compare commits
11 commits
a7457c3979
...
437ecd0ed3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
437ecd0ed3 | ||
|
|
c057a085ed | ||
|
|
23a94f5558 | ||
|
|
797aed0240 | ||
|
|
5f40c677a8 | ||
|
|
8a22e285df | ||
|
|
92597a1143 | ||
|
|
c1f4c66e8c | ||
|
|
43da1b09ed | ||
|
|
6d5f8594d0 | ||
|
|
4b686c4544 |
5 changed files with 741 additions and 395 deletions
|
|
@ -152,7 +152,7 @@ templates_signature_email = {
|
||||||
</table>
|
</table>
|
||||||
|
|
||||||
<p style="color: #718096; font-size: 13px; line-height: 1.5; margin: 0;">
|
<p style="color: #718096; font-size: 13px; line-height: 1.5; margin: 0;">
|
||||||
<strong>🔒 Signature électronique sécurisée</strong><br>
|
<strong> Signature électronique sécurisée</strong><br>
|
||||||
Votre signature est protégée par notre partenaire de confiance <strong>Universign</strong>,
|
Votre signature est protégée par notre partenaire de confiance <strong>Universign</strong>,
|
||||||
certifié eIDAS et conforme au RGPD. Votre identité sera vérifiée et le document sera
|
certifié eIDAS et conforme au RGPD. Votre identité sera vérifiée et le document sera
|
||||||
horodaté de manière infalsifiable.
|
horodaté de manière infalsifiable.
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,6 @@
|
||||||
from sqlalchemy import Column, String, Boolean, DateTime, Integer, Text
|
from sqlalchemy import Column, String, Boolean, DateTime, Integer, Text
|
||||||
|
from typing import Optional, List
|
||||||
|
import json
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import uuid
|
import uuid
|
||||||
|
|
||||||
|
|
@ -49,8 +51,23 @@ class SwaggerUser(Base):
|
||||||
|
|
||||||
is_active = Column(Boolean, default=True, nullable=False)
|
is_active = Column(Boolean, default=True, nullable=False)
|
||||||
|
|
||||||
|
allowed_tags = Column(Text, nullable=True)
|
||||||
|
|
||||||
created_at = Column(DateTime, default=datetime.now, nullable=False)
|
created_at = Column(DateTime, default=datetime.now, nullable=False)
|
||||||
last_login = Column(DateTime, nullable=True)
|
last_login = Column(DateTime, nullable=True)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def allowed_tags_list(self) -> Optional[List[str]]:
|
||||||
|
if self.allowed_tags:
|
||||||
|
try:
|
||||||
|
return json.loads(self.allowed_tags)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return None
|
||||||
|
return None
|
||||||
|
|
||||||
|
@allowed_tags_list.setter
|
||||||
|
def allowed_tags_list(self, tags: Optional[List[str]]):
|
||||||
|
self.allowed_tags = json.dumps(tags) if tags is not None else None
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return f"<SwaggerUser(username='{self.username}', active={self.is_active})>"
|
return f"<SwaggerUser(username='{self.username}', active={self.is_active})>"
|
||||||
|
|
|
||||||
|
|
@ -2,12 +2,13 @@ from fastapi import Request, status
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
||||||
from starlette.middleware.base import BaseHTTPMiddleware
|
from starlette.middleware.base import BaseHTTPMiddleware
|
||||||
from starlette.types import ASGIApp
|
from starlette.types import ASGIApp, Receive, Send
|
||||||
from sqlalchemy import select
|
from sqlalchemy import select
|
||||||
from typing import Callable
|
from typing import Callable, Optional
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
import logging
|
import logging
|
||||||
import base64
|
import base64
|
||||||
|
import json
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
@ -20,7 +21,7 @@ class SwaggerAuthMiddleware:
|
||||||
def __init__(self, app: ASGIApp):
|
def __init__(self, app: ASGIApp):
|
||||||
self.app = app
|
self.app = app
|
||||||
|
|
||||||
async def __call__(self, scope, receive, send):
|
async def __call__(self, scope, receive: Receive, send: Send):
|
||||||
if scope["type"] != "http":
|
if scope["type"] != "http":
|
||||||
await self.app(scope, receive, send)
|
await self.app(scope, receive, send)
|
||||||
return
|
return
|
||||||
|
|
@ -50,7 +51,9 @@ class SwaggerAuthMiddleware:
|
||||||
|
|
||||||
credentials = HTTPBasicCredentials(username=username, password=password)
|
credentials = HTTPBasicCredentials(username=username, password=password)
|
||||||
|
|
||||||
if not await self._verify_credentials(credentials):
|
swagger_user = await self._verify_credentials(credentials)
|
||||||
|
|
||||||
|
if not swagger_user:
|
||||||
response = JSONResponse(
|
response = JSONResponse(
|
||||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
content={"detail": "Identifiants invalides"},
|
content={"detail": "Identifiants invalides"},
|
||||||
|
|
@ -59,6 +62,15 @@ class SwaggerAuthMiddleware:
|
||||||
await response(scope, receive, send)
|
await response(scope, receive, send)
|
||||||
return
|
return
|
||||||
|
|
||||||
|
if "state" not in scope:
|
||||||
|
scope["state"] = {}
|
||||||
|
|
||||||
|
scope["state"]["swagger_user"] = swagger_user
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
f"✓ Swagger auth: {swagger_user['username']} - tags: {swagger_user.get('allowed_tags', 'ALL')}"
|
||||||
|
)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f" Erreur parsing auth header: {e}")
|
logger.error(f" Erreur parsing auth header: {e}")
|
||||||
response = JSONResponse(
|
response = JSONResponse(
|
||||||
|
|
@ -71,8 +83,9 @@ class SwaggerAuthMiddleware:
|
||||||
|
|
||||||
await self.app(scope, receive, send)
|
await self.app(scope, receive, send)
|
||||||
|
|
||||||
async def _verify_credentials(self, credentials: HTTPBasicCredentials) -> bool:
|
async def _verify_credentials(
|
||||||
"""Vérifie les identifiants dans la base de données"""
|
self, credentials: HTTPBasicCredentials
|
||||||
|
) -> Optional[dict]:
|
||||||
from database.db_config import async_session_factory
|
from database.db_config import async_session_factory
|
||||||
from database.models.api_key import SwaggerUser
|
from database.models.api_key import SwaggerUser
|
||||||
from security.auth import verify_password
|
from security.auth import verify_password
|
||||||
|
|
@ -92,15 +105,22 @@ class SwaggerAuthMiddleware:
|
||||||
):
|
):
|
||||||
swagger_user.last_login = datetime.now()
|
swagger_user.last_login = datetime.now()
|
||||||
await session.commit()
|
await session.commit()
|
||||||
|
|
||||||
logger.info(f"✓ Accès Swagger autorisé: {credentials.username}")
|
logger.info(f"✓ Accès Swagger autorisé: {credentials.username}")
|
||||||
return True
|
|
||||||
|
return {
|
||||||
|
"id": swagger_user.id,
|
||||||
|
"username": swagger_user.username,
|
||||||
|
"allowed_tags": swagger_user.allowed_tags_list,
|
||||||
|
"is_active": swagger_user.is_active,
|
||||||
|
}
|
||||||
|
|
||||||
logger.warning(f"✗ Accès Swagger refusé: {credentials.username}")
|
logger.warning(f"✗ Accès Swagger refusé: {credentials.username}")
|
||||||
return False
|
return None
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Erreur vérification credentials: {e}")
|
logger.error(f" Erreur vérification credentials: {e}", exc_info=True)
|
||||||
return False
|
return None
|
||||||
|
|
||||||
|
|
||||||
class ApiKeyMiddlewareHTTP(BaseHTTPMiddleware):
|
class ApiKeyMiddlewareHTTP(BaseHTTPMiddleware):
|
||||||
|
|
@ -116,7 +136,7 @@ class ApiKeyMiddlewareHTTP(BaseHTTPMiddleware):
|
||||||
]
|
]
|
||||||
|
|
||||||
def _is_excluded_path(self, path: str) -> bool:
|
def _is_excluded_path(self, path: str) -> bool:
|
||||||
"""Vérifie si le chemin est exclu de l'authentification"""
|
"""Vérifie si le chemin est exclu de l'authentification API Key"""
|
||||||
if path == "/":
|
if path == "/":
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
@ -139,7 +159,7 @@ class ApiKeyMiddlewareHTTP(BaseHTTPMiddleware):
|
||||||
api_key_header = request.headers.get("X-API-Key")
|
api_key_header = request.headers.get("X-API-Key")
|
||||||
|
|
||||||
if api_key_header:
|
if api_key_header:
|
||||||
logger.debug(f"🔑 API Key détectée pour {method} {path}")
|
logger.debug(f" API Key détectée pour {method} {path}")
|
||||||
return await self._handle_api_key_auth(
|
return await self._handle_api_key_auth(
|
||||||
request, api_key_header, path, method, call_next
|
request, api_key_header, path, method, call_next
|
||||||
)
|
)
|
||||||
|
|
@ -149,7 +169,7 @@ class ApiKeyMiddlewareHTTP(BaseHTTPMiddleware):
|
||||||
|
|
||||||
if token.startswith("sdk_live_"):
|
if token.startswith("sdk_live_"):
|
||||||
logger.warning(
|
logger.warning(
|
||||||
" API Key envoyée dans Authorization au lieu de X-API-Key"
|
"⚠️ API Key envoyée dans Authorization au lieu de X-API-Key"
|
||||||
)
|
)
|
||||||
return await self._handle_api_key_auth(
|
return await self._handle_api_key_auth(
|
||||||
request, token, path, method, call_next
|
request, token, path, method, call_next
|
||||||
|
|
@ -159,7 +179,7 @@ class ApiKeyMiddlewareHTTP(BaseHTTPMiddleware):
|
||||||
request.state.authenticated_via = "jwt"
|
request.state.authenticated_via = "jwt"
|
||||||
return await call_next(request)
|
return await call_next(request)
|
||||||
|
|
||||||
logger.debug(f" Aucune auth pour {method} {path} → délégation à FastAPI")
|
logger.debug(f"❓ Aucune auth pour {method} {path} → délégation à FastAPI")
|
||||||
return await call_next(request)
|
return await call_next(request)
|
||||||
|
|
||||||
async def _handle_api_key_auth(
|
async def _handle_api_key_auth(
|
||||||
|
|
@ -170,7 +190,6 @@ class ApiKeyMiddlewareHTTP(BaseHTTPMiddleware):
|
||||||
method: str,
|
method: str,
|
||||||
call_next: Callable,
|
call_next: Callable,
|
||||||
):
|
):
|
||||||
"""Gère l'authentification par API Key avec vérification STRICTE"""
|
|
||||||
try:
|
try:
|
||||||
from database.db_config import async_session_factory
|
from database.db_config import async_session_factory
|
||||||
from services.api_key import ApiKeyService
|
from services.api_key import ApiKeyService
|
||||||
|
|
@ -192,7 +211,7 @@ class ApiKeyMiddlewareHTTP(BaseHTTPMiddleware):
|
||||||
|
|
||||||
is_allowed, rate_info = await service.check_rate_limit(api_key_obj)
|
is_allowed, rate_info = await service.check_rate_limit(api_key_obj)
|
||||||
if not is_allowed:
|
if not is_allowed:
|
||||||
logger.warning(f" Rate limit: {api_key_obj.name}")
|
logger.warning(f"⏱️ Rate limit: {api_key_obj.name}")
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||||
content={"detail": "Rate limit dépassé"},
|
content={"detail": "Rate limit dépassé"},
|
||||||
|
|
@ -205,8 +224,6 @@ class ApiKeyMiddlewareHTTP(BaseHTTPMiddleware):
|
||||||
has_access = await service.check_endpoint_access(api_key_obj, path)
|
has_access = await service.check_endpoint_access(api_key_obj, path)
|
||||||
|
|
||||||
if not has_access:
|
if not has_access:
|
||||||
import json
|
|
||||||
|
|
||||||
allowed = (
|
allowed = (
|
||||||
json.loads(api_key_obj.allowed_endpoints)
|
json.loads(api_key_obj.allowed_endpoints)
|
||||||
if api_key_obj.allowed_endpoints
|
if api_key_obj.allowed_endpoints
|
||||||
|
|
@ -214,7 +231,7 @@ class ApiKeyMiddlewareHTTP(BaseHTTPMiddleware):
|
||||||
)
|
)
|
||||||
|
|
||||||
logger.warning(
|
logger.warning(
|
||||||
f" ACCÈS REFUSÉ: {api_key_obj.name}\n"
|
f"🚫 ACCÈS REFUSÉ: {api_key_obj.name}\n"
|
||||||
f" Endpoint demandé: {path}\n"
|
f" Endpoint demandé: {path}\n"
|
||||||
f" Endpoints autorisés: {allowed}"
|
f" Endpoints autorisés: {allowed}"
|
||||||
)
|
)
|
||||||
|
|
@ -226,7 +243,7 @@ class ApiKeyMiddlewareHTTP(BaseHTTPMiddleware):
|
||||||
"endpoint_requested": path,
|
"endpoint_requested": path,
|
||||||
"api_key_name": api_key_obj.name,
|
"api_key_name": api_key_obj.name,
|
||||||
"allowed_endpoints": allowed,
|
"allowed_endpoints": allowed,
|
||||||
"hint": "Cette clé API n'a pas accès à cet endpoint. Contactez l'administrateur.",
|
"hint": "Cette clé API n'a pas accès à cet endpoint.",
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -238,7 +255,7 @@ class ApiKeyMiddlewareHTTP(BaseHTTPMiddleware):
|
||||||
return await call_next(request)
|
return await call_next(request)
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f" Erreur validation API Key: {e}", exc_info=True)
|
logger.error(f"💥 Erreur validation API Key: {e}", exc_info=True)
|
||||||
return JSONResponse(
|
return JSONResponse(
|
||||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||||
content={"detail": f"Erreur interne: {str(e)}"},
|
content={"detail": f"Erreur interne: {str(e)}"},
|
||||||
|
|
@ -248,7 +265,7 @@ class ApiKeyMiddlewareHTTP(BaseHTTPMiddleware):
|
||||||
ApiKeyMiddleware = ApiKeyMiddlewareHTTP
|
ApiKeyMiddleware = ApiKeyMiddlewareHTTP
|
||||||
|
|
||||||
|
|
||||||
def get_api_key_from_request(request: Request):
|
def get_api_key_from_request(request: Request) -> Optional:
|
||||||
"""Récupère l'objet ApiKey depuis la requête si présent"""
|
"""Récupère l'objet ApiKey depuis la requête si présent"""
|
||||||
return getattr(request.state, "api_key", None)
|
return getattr(request.state, "api_key", None)
|
||||||
|
|
||||||
|
|
@ -258,10 +275,16 @@ def get_auth_method(request: Request) -> str:
|
||||||
return getattr(request.state, "authenticated_via", "none")
|
return getattr(request.state, "authenticated_via", "none")
|
||||||
|
|
||||||
|
|
||||||
|
def get_swagger_user_from_request(request: Request) -> Optional[dict]:
|
||||||
|
"""Récupère l'utilisateur Swagger depuis la requête"""
|
||||||
|
return getattr(request.state, "swagger_user", None)
|
||||||
|
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"SwaggerAuthMiddleware",
|
"SwaggerAuthMiddleware",
|
||||||
"ApiKeyMiddlewareHTTP",
|
"ApiKeyMiddlewareHTTP",
|
||||||
"ApiKeyMiddleware",
|
"ApiKeyMiddleware",
|
||||||
"get_api_key_from_request",
|
"get_api_key_from_request",
|
||||||
"get_auth_method",
|
"get_auth_method",
|
||||||
|
"get_swagger_user_from_request",
|
||||||
]
|
]
|
||||||
|
|
|
||||||
|
|
@ -1,65 +1,123 @@
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Script de gestion avancée des utilisateurs Swagger et API Keys
|
||||||
|
avec configuration des schémas d'authentification
|
||||||
|
"""
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
import os
|
import os
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
import asyncio
|
||||||
|
import argparse
|
||||||
|
import logging
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional, List
|
||||||
|
import json
|
||||||
|
from sqlalchemy import select
|
||||||
|
|
||||||
_current_file = Path(__file__).resolve()
|
_current_file = Path(__file__).resolve()
|
||||||
_script_dir = _current_file.parent
|
_script_dir = _current_file.parent
|
||||||
_app_dir = _script_dir.parent
|
_app_dir = _script_dir.parent
|
||||||
|
|
||||||
print(f"DEBUG: Script path: {_current_file}")
|
|
||||||
print(f"DEBUG: App dir: {_app_dir}")
|
|
||||||
print(f"DEBUG: Current working dir: {os.getcwd()}")
|
|
||||||
|
|
||||||
if str(_app_dir) in sys.path:
|
if str(_app_dir) in sys.path:
|
||||||
sys.path.remove(str(_app_dir))
|
sys.path.remove(str(_app_dir))
|
||||||
sys.path.insert(0, str(_app_dir))
|
sys.path.insert(0, str(_app_dir))
|
||||||
|
|
||||||
os.chdir(str(_app_dir))
|
os.chdir(str(_app_dir))
|
||||||
|
|
||||||
print(f"DEBUG: sys.path[0]: {sys.path[0]}")
|
|
||||||
print(f"DEBUG: New working dir: {os.getcwd()}")
|
|
||||||
|
|
||||||
_test_imports = [
|
|
||||||
"database",
|
|
||||||
"database.db_config",
|
|
||||||
"database.models",
|
|
||||||
"services",
|
|
||||||
"security",
|
|
||||||
]
|
|
||||||
|
|
||||||
print("\nDEBUG: Vérification des imports...")
|
|
||||||
for module in _test_imports:
|
|
||||||
try:
|
|
||||||
__import__(module)
|
|
||||||
print(f" {module}")
|
|
||||||
except ImportError as e:
|
|
||||||
print(f" {module}: {e}")
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import argparse
|
|
||||||
import logging
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
from sqlalchemy import select
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from database.db_config import async_session_factory
|
from database.db_config import async_session_factory
|
||||||
from database.models.user import User
|
|
||||||
from database.models.api_key import SwaggerUser, ApiKey
|
from database.models.api_key import SwaggerUser, ApiKey
|
||||||
from services.api_key import ApiKeyService
|
from services.api_key import ApiKeyService
|
||||||
from security.auth import hash_password
|
from security.auth import hash_password
|
||||||
except ImportError as e:
|
except ImportError as e:
|
||||||
print(f"\n ERREUR D'IMPORT: {e}")
|
print(f"\n ERREUR D'IMPORT: {e}")
|
||||||
print(f" Vérifiez que vous êtes dans /app")
|
print(" Vérifiez que vous êtes dans /app")
|
||||||
print(f" Commande correcte: cd /app && python scripts/manage_security.py ...")
|
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
|
|
||||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s - %(message)s")
|
logging.basicConfig(level=logging.INFO, format="%(levelname)s - %(message)s")
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
async def add_swagger_user(username: str, password: str, full_name: str = None):
|
AVAILABLE_TAGS = {
|
||||||
"""Ajouter un utilisateur Swagger"""
|
"Authentication": "🔐 Authentification et gestion des comptes",
|
||||||
|
"API Keys Management": " Gestion des clés API",
|
||||||
|
"Clients": "👥 Gestion des clients",
|
||||||
|
"Fournisseurs": "🏭 Gestion des fournisseurs",
|
||||||
|
"Prospects": "🎯 Gestion des prospects",
|
||||||
|
"Tiers": "📋 Gestion générale des tiers",
|
||||||
|
"Contacts": "📞 Contacts des tiers",
|
||||||
|
"Articles": "📦 Catalogue articles",
|
||||||
|
"Familles": "🏷️ Familles d'articles",
|
||||||
|
"Stock": "📊 Mouvements de stock",
|
||||||
|
"Devis": "📄 Devis",
|
||||||
|
"Commandes": "🛒 Commandes",
|
||||||
|
"Livraisons": "🚚 Bons de livraison",
|
||||||
|
"Factures": "💰 Factures",
|
||||||
|
"Avoirs": "↩️ Avoirs",
|
||||||
|
"Règlements": "💳 Règlements et encaissements",
|
||||||
|
"Workflows": "🔄 Transformations de documents",
|
||||||
|
"Documents": "📑 Gestion documents (PDF)",
|
||||||
|
"Emails": "📧 Envoi d'emails",
|
||||||
|
"Validation": " Validations métier",
|
||||||
|
"Collaborateurs": "👔 Collaborateurs internes",
|
||||||
|
"Société": "🏢 Informations société",
|
||||||
|
"Référentiels": " Données de référence",
|
||||||
|
"System": "⚙️ Système et santé",
|
||||||
|
"Admin": "🛠️ Administration",
|
||||||
|
"Debug": "🐛 Debug et diagnostics",
|
||||||
|
}
|
||||||
|
|
||||||
|
PRESET_PROFILES = {
|
||||||
|
"commercial": [
|
||||||
|
"Clients",
|
||||||
|
"Contacts",
|
||||||
|
"Devis",
|
||||||
|
"Commandes",
|
||||||
|
"Factures",
|
||||||
|
"Articles",
|
||||||
|
"Documents",
|
||||||
|
"Emails",
|
||||||
|
],
|
||||||
|
"comptable": [
|
||||||
|
"Clients",
|
||||||
|
"Fournisseurs",
|
||||||
|
"Factures",
|
||||||
|
"Avoirs",
|
||||||
|
"Règlements",
|
||||||
|
"Documents",
|
||||||
|
"Emails",
|
||||||
|
],
|
||||||
|
"logistique": [
|
||||||
|
"Articles",
|
||||||
|
"Stock",
|
||||||
|
"Commandes",
|
||||||
|
"Livraisons",
|
||||||
|
"Fournisseurs",
|
||||||
|
"Documents",
|
||||||
|
],
|
||||||
|
"readonly": ["Clients", "Articles", "Devis", "Commandes", "Factures", "Documents"],
|
||||||
|
"developer": [
|
||||||
|
"Authentication",
|
||||||
|
"API Keys Management",
|
||||||
|
"System",
|
||||||
|
"Clients",
|
||||||
|
"Articles",
|
||||||
|
"Devis",
|
||||||
|
"Commandes",
|
||||||
|
"Factures",
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def add_swagger_user(
|
||||||
|
username: str,
|
||||||
|
password: str,
|
||||||
|
full_name: str = None,
|
||||||
|
tags: Optional[List[str]] = None,
|
||||||
|
preset: Optional[str] = None,
|
||||||
|
):
|
||||||
|
"""Ajouter un utilisateur Swagger avec configuration avancée"""
|
||||||
async with async_session_factory() as session:
|
async with async_session_factory() as session:
|
||||||
result = await session.execute(
|
result = await session.execute(
|
||||||
select(SwaggerUser).where(SwaggerUser.username == username)
|
select(SwaggerUser).where(SwaggerUser.username == username)
|
||||||
|
|
@ -70,11 +128,21 @@ async def add_swagger_user(username: str, password: str, full_name: str = None):
|
||||||
logger.error(f" L'utilisateur '{username}' existe déjà")
|
logger.error(f" L'utilisateur '{username}' existe déjà")
|
||||||
return
|
return
|
||||||
|
|
||||||
|
if preset:
|
||||||
|
if preset not in PRESET_PROFILES:
|
||||||
|
logger.error(
|
||||||
|
f" Preset '{preset}' inconnu. Disponibles: {list(PRESET_PROFILES.keys())}"
|
||||||
|
)
|
||||||
|
return
|
||||||
|
tags = PRESET_PROFILES[preset]
|
||||||
|
logger.info(f"📋 Application du preset '{preset}': {len(tags)} tags")
|
||||||
|
|
||||||
swagger_user = SwaggerUser(
|
swagger_user = SwaggerUser(
|
||||||
username=username,
|
username=username,
|
||||||
hashed_password=hash_password(password),
|
hashed_password=hash_password(password),
|
||||||
full_name=full_name or username,
|
full_name=full_name or username,
|
||||||
is_active=True,
|
is_active=True,
|
||||||
|
allowed_tags=json.dumps(tags) if tags else None,
|
||||||
)
|
)
|
||||||
|
|
||||||
session.add(swagger_user)
|
session.add(swagger_user)
|
||||||
|
|
@ -83,9 +151,17 @@ async def add_swagger_user(username: str, password: str, full_name: str = None):
|
||||||
logger.info(f" Utilisateur Swagger créé: {username}")
|
logger.info(f" Utilisateur Swagger créé: {username}")
|
||||||
logger.info(f" Nom complet: {swagger_user.full_name}")
|
logger.info(f" Nom complet: {swagger_user.full_name}")
|
||||||
|
|
||||||
|
if tags:
|
||||||
|
logger.info(f" 🏷️ Tags autorisés ({len(tags)}):")
|
||||||
|
for tag in tags:
|
||||||
|
desc = AVAILABLE_TAGS.get(tag, "")
|
||||||
|
logger.info(f" • {tag} {desc}")
|
||||||
|
else:
|
||||||
|
logger.info(" 👑 Accès ADMIN COMPLET (tous les tags)")
|
||||||
|
|
||||||
|
|
||||||
async def list_swagger_users():
|
async def list_swagger_users():
|
||||||
"""Lister tous les utilisateurs Swagger"""
|
"""Lister tous les utilisateurs Swagger avec détails"""
|
||||||
async with async_session_factory() as session:
|
async with async_session_factory() as session:
|
||||||
result = await session.execute(select(SwaggerUser))
|
result = await session.execute(select(SwaggerUser))
|
||||||
users = result.scalars().all()
|
users = result.scalars().all()
|
||||||
|
|
@ -94,17 +170,139 @@ async def list_swagger_users():
|
||||||
logger.info("🔭 Aucun utilisateur Swagger")
|
logger.info("🔭 Aucun utilisateur Swagger")
|
||||||
return
|
return
|
||||||
|
|
||||||
logger.info(f"👥 {len(users)} utilisateur(s) Swagger:\n")
|
logger.info(f"\n👥 {len(users)} utilisateur(s) Swagger:\n")
|
||||||
|
logger.info("=" * 80)
|
||||||
|
|
||||||
for user in users:
|
for user in users:
|
||||||
status = "" if user.is_active else ""
|
status = " ACTIF" if user.is_active else " NON ACTIF"
|
||||||
logger.info(f" {status} {user.username}")
|
logger.info(f"\n{status} {user.username}")
|
||||||
logger.info(f" Nom: {user.full_name}")
|
logger.info(f"📛 Nom: {user.full_name}")
|
||||||
logger.info(f" Créé: {user.created_at}")
|
logger.info(f"🆔 ID: {user.id}")
|
||||||
logger.info(f" Dernière connexion: {user.last_login or 'Jamais'}\n")
|
logger.info(f"📅 Créé: {user.created_at}")
|
||||||
|
logger.info(f"🕐 Dernière connexion: {user.last_login or 'Jamais'}")
|
||||||
|
|
||||||
|
if user.allowed_tags:
|
||||||
|
try:
|
||||||
|
tags = json.loads(user.allowed_tags)
|
||||||
|
if tags:
|
||||||
|
logger.info(f"🏷️ Tags autorisés ({len(tags)}):")
|
||||||
|
for tag in tags:
|
||||||
|
desc = AVAILABLE_TAGS.get(tag, "")
|
||||||
|
logger.info(f" • {tag} {desc}")
|
||||||
|
|
||||||
|
auth_schemes = []
|
||||||
|
if "Authentication" in tags:
|
||||||
|
auth_schemes.append("JWT (Bearer)")
|
||||||
|
if "API Keys Management" in tags or len(tags) > 3:
|
||||||
|
auth_schemes.append("X-API-Key")
|
||||||
|
if not auth_schemes:
|
||||||
|
auth_schemes.append("JWT (Bearer)")
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
f"🔐 Authentification autorisée: {', '.join(auth_schemes)}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
logger.info("👑 Tags autorisés: ADMIN COMPLET (tous)")
|
||||||
|
logger.info("🔐 Authentification: JWT + X-API-Key (tout)")
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
logger.info("⚠️ Tags: Erreur format")
|
||||||
|
else:
|
||||||
|
logger.info("👑 Tags autorisés: ADMIN COMPLET (tous)")
|
||||||
|
logger.info("🔐 Authentification: JWT + X-API-Key (tout)")
|
||||||
|
|
||||||
|
logger.info("\n" + "=" * 80)
|
||||||
|
|
||||||
|
|
||||||
|
async def update_swagger_user(
|
||||||
|
username: str,
|
||||||
|
add_tags: Optional[List[str]] = None,
|
||||||
|
remove_tags: Optional[List[str]] = None,
|
||||||
|
set_tags: Optional[List[str]] = None,
|
||||||
|
preset: Optional[str] = None,
|
||||||
|
active: Optional[bool] = None,
|
||||||
|
):
|
||||||
|
"""Mettre à jour un utilisateur Swagger"""
|
||||||
|
async with async_session_factory() as session:
|
||||||
|
result = await session.execute(
|
||||||
|
select(SwaggerUser).where(SwaggerUser.username == username)
|
||||||
|
)
|
||||||
|
user = result.scalar_one_or_none()
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
logger.error(f" Utilisateur '{username}' introuvable")
|
||||||
|
return
|
||||||
|
|
||||||
|
modified = False
|
||||||
|
|
||||||
|
if preset:
|
||||||
|
if preset not in PRESET_PROFILES:
|
||||||
|
logger.error(f" Preset '{preset}' inconnu")
|
||||||
|
return
|
||||||
|
user.allowed_tags = json.dumps(PRESET_PROFILES[preset])
|
||||||
|
logger.info(f"📋 Preset '{preset}' appliqué")
|
||||||
|
modified = True
|
||||||
|
|
||||||
|
elif set_tags is not None:
|
||||||
|
user.allowed_tags = json.dumps(set_tags) if set_tags else None
|
||||||
|
logger.info(f"🔄 Tags remplacés: {len(set_tags) if set_tags else 0}")
|
||||||
|
modified = True
|
||||||
|
|
||||||
|
elif add_tags or remove_tags:
|
||||||
|
current_tags = []
|
||||||
|
if user.allowed_tags:
|
||||||
|
try:
|
||||||
|
current_tags = json.loads(user.allowed_tags)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
current_tags = []
|
||||||
|
|
||||||
|
if add_tags:
|
||||||
|
for tag in add_tags:
|
||||||
|
if tag not in current_tags:
|
||||||
|
current_tags.append(tag)
|
||||||
|
logger.info(f"➕ Tag ajouté: {tag}")
|
||||||
|
modified = True
|
||||||
|
|
||||||
|
if remove_tags:
|
||||||
|
for tag in remove_tags:
|
||||||
|
if tag in current_tags:
|
||||||
|
current_tags.remove(tag)
|
||||||
|
logger.info(f"➖ Tag retiré: {tag}")
|
||||||
|
modified = True
|
||||||
|
|
||||||
|
user.allowed_tags = json.dumps(current_tags) if current_tags else None
|
||||||
|
|
||||||
|
if active is not None:
|
||||||
|
user.is_active = active
|
||||||
|
logger.info(f"🔄 Statut: {'ACTIF' if active else 'INACTIF'}")
|
||||||
|
modified = True
|
||||||
|
|
||||||
|
if modified:
|
||||||
|
await session.commit()
|
||||||
|
logger.info(f" Utilisateur '{username}' mis à jour")
|
||||||
|
else:
|
||||||
|
logger.info("ℹ️ Aucune modification effectuée")
|
||||||
|
|
||||||
|
|
||||||
|
async def list_available_tags():
|
||||||
|
"""Liste tous les tags disponibles avec description"""
|
||||||
|
logger.info("\n TAGS DISPONIBLES:\n")
|
||||||
|
logger.info("=" * 80)
|
||||||
|
|
||||||
|
for tag, desc in AVAILABLE_TAGS.items():
|
||||||
|
logger.info(f" {desc}")
|
||||||
|
logger.info(f" Nom: {tag}\n")
|
||||||
|
|
||||||
|
logger.info("=" * 80)
|
||||||
|
logger.info("\n📦 PRESETS DISPONIBLES:\n")
|
||||||
|
|
||||||
|
for preset_name, tags in PRESET_PROFILES.items():
|
||||||
|
logger.info(f" {preset_name}:")
|
||||||
|
logger.info(f" {', '.join(tags)}\n")
|
||||||
|
|
||||||
|
logger.info("=" * 80)
|
||||||
|
|
||||||
|
|
||||||
async def delete_swagger_user(username: str):
|
async def delete_swagger_user(username: str):
|
||||||
"""Supprimer un utilisateur Swagger"""
|
|
||||||
async with async_session_factory() as session:
|
async with async_session_factory() as session:
|
||||||
result = await session.execute(
|
result = await session.execute(
|
||||||
select(SwaggerUser).where(SwaggerUser.username == username)
|
select(SwaggerUser).where(SwaggerUser.username == username)
|
||||||
|
|
@ -120,157 +318,39 @@ async def delete_swagger_user(username: str):
|
||||||
logger.info(f"🗑️ Utilisateur Swagger supprimé: {username}")
|
logger.info(f"🗑️ Utilisateur Swagger supprimé: {username}")
|
||||||
|
|
||||||
|
|
||||||
async def create_api_key(
|
|
||||||
name: str,
|
|
||||||
description: str = None,
|
|
||||||
expires_in_days: int = 365,
|
|
||||||
rate_limit: int = 60,
|
|
||||||
endpoints: list = None,
|
|
||||||
):
|
|
||||||
"""Créer une clé API"""
|
|
||||||
async with async_session_factory() as session:
|
|
||||||
service = ApiKeyService(session)
|
|
||||||
|
|
||||||
api_key_obj, api_key_plain = await service.create_api_key(
|
|
||||||
name=name,
|
|
||||||
description=description,
|
|
||||||
created_by="cli",
|
|
||||||
expires_in_days=expires_in_days,
|
|
||||||
rate_limit_per_minute=rate_limit,
|
|
||||||
allowed_endpoints=endpoints,
|
|
||||||
)
|
|
||||||
|
|
||||||
logger.info("=" * 70)
|
|
||||||
logger.info("🔑 Clé API créée avec succès")
|
|
||||||
logger.info("=" * 70)
|
|
||||||
logger.info(f" ID: {api_key_obj.id}")
|
|
||||||
logger.info(f" Nom: {api_key_obj.name}")
|
|
||||||
logger.info(f" Clé: {api_key_plain}")
|
|
||||||
logger.info(f" Préfixe: {api_key_obj.key_prefix}")
|
|
||||||
logger.info(f" Rate limit: {api_key_obj.rate_limit_per_minute} req/min")
|
|
||||||
logger.info(f" Expire le: {api_key_obj.expires_at}")
|
|
||||||
|
|
||||||
if api_key_obj.allowed_endpoints:
|
|
||||||
import json
|
|
||||||
|
|
||||||
try:
|
|
||||||
endpoints_list = json.loads(api_key_obj.allowed_endpoints)
|
|
||||||
logger.info(f" Endpoints: {', '.join(endpoints_list)}")
|
|
||||||
except:
|
|
||||||
logger.info(f" Endpoints: {api_key_obj.allowed_endpoints}")
|
|
||||||
else:
|
|
||||||
logger.info(" Endpoints: Tous (aucune restriction)")
|
|
||||||
|
|
||||||
logger.info("=" * 70)
|
|
||||||
logger.info(" SAUVEGARDEZ CETTE CLÉ - Elle ne sera plus affichée !")
|
|
||||||
logger.info("=" * 70)
|
|
||||||
|
|
||||||
|
|
||||||
async def list_api_keys():
|
|
||||||
"""Lister toutes les clés API"""
|
|
||||||
async with async_session_factory() as session:
|
|
||||||
service = ApiKeyService(session)
|
|
||||||
keys = await service.list_api_keys()
|
|
||||||
|
|
||||||
if not keys:
|
|
||||||
logger.info("🔭 Aucune clé API")
|
|
||||||
return
|
|
||||||
|
|
||||||
logger.info(f"🔑 {len(keys)} clé(s) API:\n")
|
|
||||||
|
|
||||||
for key in keys:
|
|
||||||
is_valid = key.is_active and (
|
|
||||||
not key.expires_at or key.expires_at > datetime.now()
|
|
||||||
)
|
|
||||||
status = "" if is_valid else ""
|
|
||||||
|
|
||||||
logger.info(f" {status} {key.name:<30} ({key.key_prefix}...)")
|
|
||||||
logger.info(f" ID: {key.id}")
|
|
||||||
logger.info(f" Rate limit: {key.rate_limit_per_minute} req/min")
|
|
||||||
logger.info(f" Requêtes: {key.total_requests}")
|
|
||||||
logger.info(f" Expire: {key.expires_at or 'Jamais'}")
|
|
||||||
logger.info(f" Dernière utilisation: {key.last_used_at or 'Jamais'}")
|
|
||||||
|
|
||||||
if key.allowed_endpoints:
|
|
||||||
import json
|
|
||||||
|
|
||||||
try:
|
|
||||||
endpoints = json.loads(key.allowed_endpoints)
|
|
||||||
display = ", ".join(endpoints[:4])
|
|
||||||
if len(endpoints) > 4:
|
|
||||||
display += f"... (+{len(endpoints) - 4})"
|
|
||||||
logger.info(f" Endpoints: {display}")
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
logger.info(" Endpoints: Tous")
|
|
||||||
logger.info("")
|
|
||||||
|
|
||||||
|
|
||||||
async def revoke_api_key(key_id: str):
|
|
||||||
"""Révoquer une clé API"""
|
|
||||||
async with async_session_factory() as session:
|
|
||||||
result = await session.execute(select(ApiKey).where(ApiKey.id == key_id))
|
|
||||||
key = result.scalar_one_or_none()
|
|
||||||
|
|
||||||
if not key:
|
|
||||||
logger.error(f" Clé API '{key_id}' introuvable")
|
|
||||||
return
|
|
||||||
|
|
||||||
key.is_active = False
|
|
||||||
key.revoked_at = datetime.now()
|
|
||||||
await session.commit()
|
|
||||||
|
|
||||||
logger.info(f"🗑️ Clé API révoquée: {key.name}")
|
|
||||||
logger.info(f" ID: {key.id}")
|
|
||||||
|
|
||||||
|
|
||||||
async def verify_api_key(api_key: str):
|
|
||||||
"""Vérifier une clé API"""
|
|
||||||
async with async_session_factory() as session:
|
|
||||||
service = ApiKeyService(session)
|
|
||||||
key = await service.verify_api_key(api_key)
|
|
||||||
|
|
||||||
if not key:
|
|
||||||
logger.error(" Clé API invalide ou expirée")
|
|
||||||
return
|
|
||||||
|
|
||||||
logger.info("=" * 60)
|
|
||||||
logger.info(" Clé API valide")
|
|
||||||
logger.info("=" * 60)
|
|
||||||
logger.info(f" Nom: {key.name}")
|
|
||||||
logger.info(f" ID: {key.id}")
|
|
||||||
logger.info(f" Rate limit: {key.rate_limit_per_minute} req/min")
|
|
||||||
logger.info(f" Requêtes totales: {key.total_requests}")
|
|
||||||
logger.info(f" Expire: {key.expires_at or 'Jamais'}")
|
|
||||||
|
|
||||||
if key.allowed_endpoints:
|
|
||||||
import json
|
|
||||||
|
|
||||||
try:
|
|
||||||
endpoints = json.loads(key.allowed_endpoints)
|
|
||||||
logger.info(f" Endpoints autorisés: {endpoints}")
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
logger.info(" Endpoints autorisés: Tous")
|
|
||||||
logger.info("=" * 60)
|
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
parser = argparse.ArgumentParser(
|
parser = argparse.ArgumentParser(
|
||||||
description="Gestion des utilisateurs Swagger et clés API",
|
description="Gestion avancée des utilisateurs Swagger et clés API",
|
||||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||||
epilog="""
|
epilog="""
|
||||||
Exemples:
|
EXEMPLES D'UTILISATION:
|
||||||
python scripts/manage_security.py swagger add admin MyP@ssw0rd
|
|
||||||
python scripts/manage_security.py swagger list
|
1. Créer un utilisateur avec preset:
|
||||||
python scripts/manage_security.py apikey create "Mon App" --days 365 --rate-limit 100
|
python scripts/manage_security.py swagger add commercial Pass123! --preset commercial
|
||||||
python scripts/manage_security.py apikey create "SDK-ReadOnly" --endpoints "/clients" "/clients/*" "/devis" "/devis/*"
|
|
||||||
python scripts/manage_security.py apikey list
|
2. Créer un admin complet:
|
||||||
python scripts/manage_security.py apikey verify sdk_live_xxxxx
|
python scripts/manage_security.py swagger add admin AdminPass
|
||||||
|
|
||||||
|
3. Créer avec tags spécifiques:
|
||||||
|
python scripts/manage_security.py swagger add client Pass123! --tags Clients Devis Factures
|
||||||
|
|
||||||
|
4. Mettre à jour un utilisateur (ajouter des tags):
|
||||||
|
python scripts/manage_security.py swagger update client --add-tags Commandes Livraisons
|
||||||
|
|
||||||
|
5. Changer complètement les tags:
|
||||||
|
python scripts/manage_security.py swagger update client --set-tags Clients Articles
|
||||||
|
|
||||||
|
6. Appliquer un preset:
|
||||||
|
python scripts/manage_security.py swagger update client --preset comptable
|
||||||
|
|
||||||
|
7. Lister les tags disponibles:
|
||||||
|
python scripts/manage_security.py swagger tags
|
||||||
|
|
||||||
|
8. Désactiver temporairement:
|
||||||
|
python scripts/manage_security.py swagger update client --inactive
|
||||||
""",
|
""",
|
||||||
)
|
)
|
||||||
|
|
||||||
subparsers = parser.add_subparsers(dest="command", help="Commandes")
|
subparsers = parser.add_subparsers(dest="command", help="Commandes")
|
||||||
|
|
||||||
swagger_parser = subparsers.add_parser("swagger", help="Gestion Swagger")
|
swagger_parser = subparsers.add_parser("swagger", help="Gestion Swagger")
|
||||||
|
|
@ -279,30 +359,38 @@ Exemples:
|
||||||
add_p = swagger_sub.add_parser("add", help="Ajouter utilisateur")
|
add_p = swagger_sub.add_parser("add", help="Ajouter utilisateur")
|
||||||
add_p.add_argument("username", help="Nom d'utilisateur")
|
add_p.add_argument("username", help="Nom d'utilisateur")
|
||||||
add_p.add_argument("password", help="Mot de passe")
|
add_p.add_argument("password", help="Mot de passe")
|
||||||
add_p.add_argument("--full-name", help="Nom complet")
|
add_p.add_argument("--full-name", help="Nom complet", default=None)
|
||||||
|
add_p.add_argument(
|
||||||
|
"--tags",
|
||||||
|
nargs="*",
|
||||||
|
help="Tags autorisés. Vide = admin complet",
|
||||||
|
default=None,
|
||||||
|
)
|
||||||
|
add_p.add_argument(
|
||||||
|
"--preset",
|
||||||
|
choices=list(PRESET_PROFILES.keys()),
|
||||||
|
help="Appliquer un preset de tags",
|
||||||
|
)
|
||||||
|
|
||||||
|
update_p = swagger_sub.add_parser("update", help="Mettre à jour utilisateur")
|
||||||
|
update_p.add_argument("username", help="Nom d'utilisateur")
|
||||||
|
update_p.add_argument("--add-tags", nargs="+", help="Ajouter des tags")
|
||||||
|
update_p.add_argument("--remove-tags", nargs="+", help="Retirer des tags")
|
||||||
|
update_p.add_argument("--set-tags", nargs="*", help="Définir les tags (remplace)")
|
||||||
|
update_p.add_argument(
|
||||||
|
"--preset", choices=list(PRESET_PROFILES.keys()), help="Appliquer preset"
|
||||||
|
)
|
||||||
|
update_p.add_argument("--active", action="store_true", help="Activer l'utilisateur")
|
||||||
|
update_p.add_argument(
|
||||||
|
"--inactive", action="store_true", help="Désactiver l'utilisateur"
|
||||||
|
)
|
||||||
|
|
||||||
swagger_sub.add_parser("list", help="Lister utilisateurs")
|
swagger_sub.add_parser("list", help="Lister utilisateurs")
|
||||||
|
|
||||||
del_p = swagger_sub.add_parser("delete", help="Supprimer utilisateur")
|
del_p = swagger_sub.add_parser("delete", help="Supprimer utilisateur")
|
||||||
del_p.add_argument("username", help="Nom d'utilisateur")
|
del_p.add_argument("username", help="Nom d'utilisateur")
|
||||||
|
|
||||||
apikey_parser = subparsers.add_parser("apikey", help="Gestion clés API")
|
swagger_sub.add_parser("tags", help="Lister les tags disponibles")
|
||||||
apikey_sub = apikey_parser.add_subparsers(dest="apikey_command")
|
|
||||||
|
|
||||||
create_p = apikey_sub.add_parser("create", help="Créer clé API")
|
|
||||||
create_p.add_argument("name", help="Nom de la clé")
|
|
||||||
create_p.add_argument("--description", help="Description")
|
|
||||||
create_p.add_argument("--days", type=int, default=365, help="Expiration (jours)")
|
|
||||||
create_p.add_argument("--rate-limit", type=int, default=60, help="Req/min")
|
|
||||||
create_p.add_argument("--endpoints", nargs="+", help="Endpoints autorisés")
|
|
||||||
|
|
||||||
apikey_sub.add_parser("list", help="Lister clés")
|
|
||||||
|
|
||||||
rev_p = apikey_sub.add_parser("revoke", help="Révoquer clé")
|
|
||||||
rev_p.add_argument("key_id", help="ID de la clé")
|
|
||||||
|
|
||||||
ver_p = apikey_sub.add_parser("verify", help="Vérifier clé")
|
|
||||||
ver_p.add_argument("api_key", help="Clé API complète")
|
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
|
@ -312,32 +400,37 @@ Exemples:
|
||||||
|
|
||||||
if args.command == "swagger":
|
if args.command == "swagger":
|
||||||
if args.swagger_command == "add":
|
if args.swagger_command == "add":
|
||||||
await add_swagger_user(args.username, args.password, args.full_name)
|
await add_swagger_user(
|
||||||
|
args.username,
|
||||||
|
args.password,
|
||||||
|
args.full_name,
|
||||||
|
args.tags,
|
||||||
|
args.preset,
|
||||||
|
)
|
||||||
|
elif args.swagger_command == "update":
|
||||||
|
active = None
|
||||||
|
if args.active:
|
||||||
|
active = True
|
||||||
|
elif args.inactive:
|
||||||
|
active = False
|
||||||
|
|
||||||
|
await update_swagger_user(
|
||||||
|
args.username,
|
||||||
|
add_tags=args.add_tags,
|
||||||
|
remove_tags=args.remove_tags,
|
||||||
|
set_tags=args.set_tags,
|
||||||
|
preset=args.preset,
|
||||||
|
active=active,
|
||||||
|
)
|
||||||
elif args.swagger_command == "list":
|
elif args.swagger_command == "list":
|
||||||
await list_swagger_users()
|
await list_swagger_users()
|
||||||
elif args.swagger_command == "delete":
|
elif args.swagger_command == "delete":
|
||||||
await delete_swagger_user(args.username)
|
await delete_swagger_user(args.username)
|
||||||
|
elif args.swagger_command == "tags":
|
||||||
|
await list_available_tags()
|
||||||
else:
|
else:
|
||||||
swagger_parser.print_help()
|
swagger_parser.print_help()
|
||||||
|
|
||||||
elif args.command == "apikey":
|
|
||||||
if args.apikey_command == "create":
|
|
||||||
await create_api_key(
|
|
||||||
name=args.name,
|
|
||||||
description=args.description,
|
|
||||||
expires_in_days=args.days,
|
|
||||||
rate_limit=args.rate_limit,
|
|
||||||
endpoints=args.endpoints,
|
|
||||||
)
|
|
||||||
elif args.apikey_command == "list":
|
|
||||||
await list_api_keys()
|
|
||||||
elif args.apikey_command == "revoke":
|
|
||||||
await revoke_api_key(args.key_id)
|
|
||||||
elif args.apikey_command == "verify":
|
|
||||||
await verify_api_key(args.api_key)
|
|
||||||
else:
|
|
||||||
apikey_parser.print_help()
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
try:
|
try:
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue