refactor(security): move security config to environment variables and improve error handling
This commit is contained in:
parent
918f5d3f19
commit
41ca202d4b
2 changed files with 23 additions and 18 deletions
|
|
@ -1,25 +1,25 @@
|
|||
import asyncio
|
||||
import sys
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
current_dir = Path(__file__).resolve().parent
|
||||
parent_dir = current_dir.parent
|
||||
sys.path.insert(0, str(parent_dir))
|
||||
from database import get_session
|
||||
from database.models.api_key import SwaggerUser, ApiKey
|
||||
from services.api_key import ApiKeyService
|
||||
from security.auth import hash_password
|
||||
from sqlalchemy import select
|
||||
|
||||
import argparse
|
||||
from datetime import datetime
|
||||
import logging
|
||||
|
||||
current_dir = Path(__file__).resolve().parent
|
||||
parent_dir = current_dir.parent
|
||||
sys.path.insert(0, str(parent_dir))
|
||||
|
||||
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s - %(message)s")
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
from database import get_session
|
||||
from database.models.api_key import SwaggerUser, ApiKey
|
||||
from services.api_key import ApiKeyService
|
||||
from security.auth import hash_password, verify_password
|
||||
from sqlalchemy import select
|
||||
|
||||
|
||||
async def add_swagger_user(username: str, password: str, full_name: str = None):
|
||||
"""Ajouter un utilisateur Swagger"""
|
||||
|
|
@ -132,7 +132,7 @@ async def create_api_key(
|
|||
f" Endpoints autorisés: {', '.join(api_key_obj.allowed_endpoints)}"
|
||||
)
|
||||
else:
|
||||
logger.info(f" Endpoints autorisés: Tous")
|
||||
logger.info(" Endpoints autorisés: Tous")
|
||||
|
||||
logger.info("=" * 60)
|
||||
logger.info(" IMPORTANT: Sauvegardez cette clé, elle ne sera plus affichée !")
|
||||
|
|
|
|||
|
|
@ -4,11 +4,12 @@ from typing import Optional, Dict
|
|||
import jwt
|
||||
import secrets
|
||||
import hashlib
|
||||
import os
|
||||
|
||||
SECRET_KEY = "VOTRE_SECRET_KEY_A_METTRE_EN_.ENV"
|
||||
ALGORITHM = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES = 10080
|
||||
REFRESH_TOKEN_EXPIRE_DAYS = 7
|
||||
SECRET_KEY = os.getenv("JWT_SECRET")
|
||||
ALGORITHM = os.getenv("JWT_ALGORITHM")
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES = os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES")
|
||||
REFRESH_TOKEN_EXPIRE_DAYS = os.getenv("REFRESH_TOKEN_EXPIRE_DAYS")
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
|
|
@ -67,9 +68,13 @@ def decode_token(token: str) -> Optional[Dict]:
|
|||
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
||||
return payload
|
||||
except jwt.ExpiredSignatureError:
|
||||
return None
|
||||
except jwt.JWTError:
|
||||
return None
|
||||
raise jwt.InvalidTokenError("Token expiré")
|
||||
except jwt.DecodeError:
|
||||
raise jwt.InvalidTokenError("Token invalide (format incorrect)")
|
||||
except jwt.InvalidTokenError as e:
|
||||
raise jwt.InvalidTokenError(f"Token invalide: {str(e)}")
|
||||
except Exception as e:
|
||||
raise jwt.InvalidTokenError(f"Erreur lors du décodage du token: {str(e)}")
|
||||
|
||||
|
||||
def validate_password_strength(password: str) -> tuple[bool, str]:
|
||||
|
|
|
|||
Loading…
Reference in a new issue