67 lines
1.9 KiB
Python
67 lines
1.9 KiB
Python
import logging
|
|
import uvicorn
|
|
|
|
from database import engine, Base
|
|
from dotenv import load_dotenv
|
|
from fastapi import FastAPI, Request, status
|
|
from fastapi.responses import JSONResponse
|
|
from loggerino import timestamp_log_config
|
|
from os import getenv
|
|
from schemas import SMSMessage
|
|
from service import (
|
|
receive_sms_messages_handler,
|
|
retrieve_sms_messages_by_phone_number_handler,
|
|
delete_sms_message_by_uuid_handler
|
|
)
|
|
from uuid import UUID
|
|
from uvicorn.config import LOGGING_CONFIG
|
|
|
|
|
|
# Create instance of FastAPI
|
|
app = FastAPI()
|
|
|
|
# Load dotenv file (.env)
|
|
load_dotenv()
|
|
|
|
# Load custom logger format
|
|
logger = logging.getLogger("uvicorn.error")
|
|
|
|
# Create tables (if they don't exist)
|
|
Base.metadata.create_all(bind=engine)
|
|
|
|
# Load whitelisted IPs
|
|
WHITELISTED_IPS = getenv("WHITELISTED_IPS").split(',')
|
|
|
|
|
|
@app.middleware("http")
|
|
async def validate_ip(request: Request, call_next):
|
|
ip = str(request.headers.get("x-forwarded-for", str(request.client.host)))
|
|
|
|
if ip not in WHITELISTED_IPS:
|
|
data = {"message": f"IP {ip} is not allowed to access this resource."}
|
|
return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST, content=data)
|
|
|
|
return await call_next(request)
|
|
|
|
|
|
@app.post("/sms-message", status_code=status.HTTP_200_OK)
|
|
async def post_sms_message(message: SMSMessage):
|
|
receive_sms_messages_handler(message)
|
|
|
|
|
|
@app.get('/sms-message/{number}', status_code=status.HTTP_200_OK)
|
|
def get_sms_messages_by_phone_number(number: str, cost: bool = False, metadata: bool = False):
|
|
contact = retrieve_sms_messages_by_phone_number_handler(number, cost, metadata)
|
|
return {'status': 'success', 'results': len(contact), 'response': contact}
|
|
|
|
|
|
@app.delete('/sms-message/{uuid}', status_code=status.HTTP_202_ACCEPTED)
|
|
def delete_sms_message_by_uuid(uuid: UUID):
|
|
delete_sms_message_by_uuid_handler(uuid)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
uvicorn.run(
|
|
app, host="0.0.0.0", port=8000, log_config=timestamp_log_config(LOGGING_CONFIG)
|
|
)
|