FediProxy/main.py
2024-12-11 09:28:29 +01:00

43 lines
1.4 KiB
Python

from fastapi import FastAPI, HTTPException
import requests
import os
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"*",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
ACCESS_TOKEN = os.getenv("ACCESS_TOKEN")
EXTERNAL_API_BASE_URL = os.getenv("EXTERNAL_API_BASE_URL")
ALLOWED_ACCOUNTS = str(os.getenv("ALLOWED_ACCOUNTS")).split(',')
print(f"Account IDs that are allowed to be accessed: {ALLOWED_ACCOUNTS}")
@app.get("/api/v1/accounts/{account_id}/statuses")
async def fetch_data(account_id):
if not account_id.isalnum():
raise HTTPException(status_code=401, detail="Account ID is not alphanumeric")
if account_id not in ALLOWED_ACCOUNTS:
raise HTTPException(status_code=401, detail="You can only use this proxy to access configured accounts")
if not ACCESS_TOKEN:
raise HTTPException(status_code=500, detail="Access token not configured")
headers = {"Authorization": f"Bearer {ACCESS_TOKEN}"}
try:
response = requests.get(f"{EXTERNAL_API_BASE_URL}/api/v1/accounts/{account_id}/statuses", headers=headers)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
raise HTTPException(status_code=502, detail=f"Error fetching data from API: {e}")