trustgate / main.py
patharanor's picture
initial project
750073f
raw
history blame
1.41 kB
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Depends, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from dotenv import load_dotenv
import os
# Load environment variables from .env file
load_dotenv()
app = FastAPI()
# CORS Middleware: restrict access to only trusted origins
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
#allow_origins=["https://your-frontend-domain.com"],
#allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Fetch the secure token from environment variables
SECURE_TOKEN = os.getenv("SECURE_TOKEN")
PORT = os.getenv("PORT")
# Simple token-based authentication dependency
async def authenticate_token(token: str):
if token != f"Bearer {SECURE_TOKEN}":
raise HTTPException(status_code=401, detail="Invalid token")
# WebSocket endpoint
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket, token: str = Depends(authenticate_token)):
await websocket.accept()
try:
while True:
data = await websocket.receive_text()
print(f"Message from client: {data}")
await websocket.send_text(f"Server received: {data}")
except WebSocketDisconnect:
print("Client disconnected")
if __name__ == "__main__":
# Run the server without TLS (insecure)
uvicorn.run("main:app", host="0.0.0.0", port=PORT)