2025-10-03 19:39:17 +02:00

71 lines
2.0 KiB
Python

from fastapi import FastAPI, Query, Depends, HTTPException, Header
from fastapi.responses import JSONResponse
from fastapi.security.api_key import APIKeyHeader
from starlette.exceptions import HTTPException as StarletteHTTPException
from typing import Dict
from pydantic import BaseModel
from validator import verify_api_key
from db import get_db
from logger_handler import setup_logger
from rabbitmq_handler import send_message_to_rmq
import uvicorn
from uvicorn_logging_config import LOGGING_CONFIG
logger = setup_logger(__name__)
api_key_header_internal = APIKeyHeader(name="X-API-Key-Internal")
class Notification(BaseModel):
receipent_user_id : int
message : Dict
api = FastAPI(
title="Internal Notifier API",
description="API to forward messages to RabbitMQ",
version="1.0.0"
)
def verify_api_key_dependency_internal(db=Depends(get_db), api_key: str = Depends(api_key_header_internal)) -> str:
cursor = db.cursor()
cursor.execute("SELECT program_name, api_key FROM internal_api_keys WHERE status = 'active'")
for program_name, hashed_key in cursor.fetchall():
if verify_api_key(api_key=api_key, hashed=hashed_key):
return program_name
raise HTTPException(status_code=403, detail="Unauthorized")
@api.exception_handler(StarletteHTTPException)
async def custom_http_exception_handler(request,exc):
if exc.status_code == 404:
return JSONResponse(
status_code=403,
content={"detail": "Unauthorized"}
)
return JSONResponse(
status_code=exc.status_code,
content={"detail": exc.detail}
)
@api.post("/internal/receive-notifications")
def receive_notifications(
notification_data: Notification,
db = Depends(get_db),
program_name: str = Depends(verify_api_key_dependency_internal)
):
logger.info(f"Received notifcation data from {program_name} for RMQ")
send_message_to_rmq(notification_data.user_id,notification_data.message)
logger.info("Successfully delivered message to RMQ")
return {"status": "queued"}
if __name__ == "__main__":
uvicorn.run(
"main:api",
host="0.0.0.0",
port=8101,
log_config=LOGGING_CONFIG,
log_level="info"
)