Skip to content

Commit

Permalink
📦 chore: Change CORS
Browse files Browse the repository at this point in the history
  • Loading branch information
xitowzys committed Apr 26, 2023
1 parent 8ccb181 commit 8f748d6
Showing 1 changed file with 46 additions and 11 deletions.
57 changes: 46 additions & 11 deletions core/rest_api/api.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from fastapi import FastAPI
from fastapi import FastAPI, Request
from loguru import logger
from starlette.responses import JSONResponse
from uvicorn_loguru_integration import run_uvicorn_loguru
import uvicorn

Expand All @@ -8,6 +9,32 @@
from fastapi.middleware.cors import CORSMiddleware


async def custom_cors_middleware(request: Request, call_next):
response = None
allowed_port = 9000
origin = request.headers.get("origin")

if origin and origin.endswith(f":{allowed_port}"):
response = await call_next(request)

response.headers["Access-Control-Allow-Origin"] = origin
response.headers["Access-Control-Allow-Credentials"] = "true"
response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
response.headers["Access-Control-Allow-Headers"] = "Authorization, Content-Type, Accept"

if request.method == "OPTIONS" and response:
response = JSONResponse(content={})
response.headers["Access-Control-Allow-Origin"] = origin
response.headers["Access-Control-Allow-Credentials"] = "true"
response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
response.headers["Access-Control-Allow-Headers"] = "Authorization, Content-Type, Accept"

if not response:
response = await call_next(request)

return response


class API:
def __init__(self):
self.__app: FastAPI = FastAPI(debug=True)
Expand All @@ -16,7 +43,7 @@ def __init__(self):

config: fastapi_gateway_auto_generate.Config = fastapi_gateway_auto_generate.Config(
fast_api_app=self.__app,
db_path=DICT_ENVS["DATABASE_PATH"] # "./database/database.db"
db_path=DICT_ENVS["DATABASE_PATH"] # "./database/database.db"
)

fastapi_gateway_auto_generate.Generator(config=config)
Expand All @@ -25,15 +52,23 @@ def __init_routes(self):
logger.success("Routers initialized")

def __cors_settings(self):
origins = ["*"]

self.__app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# def custom_origin_check(origin: str) -> bool:
# # Check if the request comes from port 9000
# return origin.endswith(':9000')

# origins = ["*"]
#
# self.__app.add_middleware(
# CORSMiddleware,
# allow_origin_callback=origins,
# allow_credentials=True,
# allow_methods=["*"],
# allow_headers=["*"],
# expose_headers=["*"],
#
# )

self.__app.middleware("http")(custom_cors_middleware)

logger.success("Cors settings are installed")

Expand Down

0 comments on commit 8f748d6

Please sign in to comment.