[add]: appId and apiKey validation

This commit is contained in:
VivianDee
2025-03-21 10:42:07 +01:00
parent c71995c9c5
commit 0f6d2b1219
6 changed files with 65 additions and 28 deletions
+1
View File
@@ -1 +1,2 @@
from .verify_api_key import require_api_key
from .app_id_checker import require_app_id
+17 -11
View File
@@ -1,20 +1,26 @@
from functools import wraps
from flask import request
from app.helpers.response_helper import ResponseHelper
from app.utils.logger import logger
import os
VALID_APP_IDS = os.getenv("VALID_APP_ID", "")
# Load valid App-IDs from environment variables (comma-separated list)
VALID_APP_ID = os.getenv("VALID_APP_ID", "app1,app2,app3").split(",")
def require_app_id():
"""Middleware to check if App-ID is present and valid."""
app_id = request.headers.get("App-ID")
def require_app_id(f):
"""Decorator to enforce App-ID validation."""
@wraps(f)
def decorated_function(*args, **kwargs):
app_id = request.headers.get("App-ID")
if not app_id:
logger.error("Unauthorized access: Missing App-ID.")
return ResponseHelper.unauthorized("Missing App-ID")
if not app_id:
logger.error("Unauthorized access: Missing App-ID.")
return ResponseHelper.unauthorized("Missing App-ID")
if app_id not in VALID_APP_IDS:
logger.error(f"Unauthorized access: Invalid App-ID {app_id}.")
return ResponseHelper.unauthorized("Invalid App-ID")
if app_id not in VALID_APP_ID:
logger.error(f"Unauthorized access: Invalid App-ID {app_id}.")
return ResponseHelper.unauthorized("Invalid App-ID")
return None
return f(*args, **kwargs)
return decorated_function
+18 -12
View File
@@ -1,20 +1,26 @@
from functools import wraps
from flask import request
from app.helpers.response_helper import ResponseHelper
from app.utils.logger import logger
import os
# Define a valid API key (store securely in environment variables)
VALID_API_KEY = "your-secure-api-key"
# Load valid API key from environment variables (fallback for testing)
VALID_API_KEY = os.getenv("VALID_API_KEY", "test-api-key-12345")
def require_api_key():
"""Middleware to check if API key is present and valid."""
api_key = request.headers.get("X-API-KEY")
def require_api_key(f):
"""Decorator to enforce API key authentication."""
@wraps(f)
def decorated_function(*args, **kwargs):
api_key = request.headers.get("X-API-KEY")
if not api_key:
logger.error("Unauthorized access: Missing API key.")
return ResponseHelper.unauthorized("Missing API key")
if not api_key:
logger.error("Unauthorized access: Missing API key.")
return ResponseHelper.unauthorized("Missing API key")
if api_key != VALID_API_KEY:
logger.error("Unauthorized access: Invalid API key.")
return ResponseHelper.unauthorized("Invalid API key")
if api_key != VALID_API_KEY:
logger.error("Unauthorized access: Invalid API key.")
return ResponseHelper.unauthorized("Invalid API key")
return None
return f(*args, **kwargs)
return decorated_function