Skip to content

Commit

Permalink
Merge pull request #67 from ClimateCompatibleGrowth/66-add-access-con…
Browse files Browse the repository at this point in the history
…trol-allow-origin-to-header

added CORS middleware configuration
  • Loading branch information
willu47 authored Jan 20, 2025
2 parents ce07150 + 4c39ee9 commit 4ff8866
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
9 changes: 9 additions & 0 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors import CORSMiddleware

from typing import Annotated
from uuid import UUID
Expand Down Expand Up @@ -33,6 +34,14 @@

app = FastAPI()

app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=False,
allow_methods=["GET", "POST", "PUT", "DELETE"],
allow_headers=["*"]
)

app.include_router(author.router)
app.include_router(output.router)
app.include_router(country.router)
Expand Down
27 changes: 27 additions & 0 deletions app/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,3 +143,30 @@ def test_workstream_error_on_not_exist(self):
"""
response = client.get("/api/workstreams/XXX")
assert response.status_code == 404

class TestCORS:
def test_cors_preflight(self):
response = client.options("/api/authors", headers={
"Origin": "http://localhost:3000",
"Access-Control-Request-Method": "GET",
"Access-Control-Request-Headers": "Content-Type"
})
assert response.status_code == 200
assert response.headers["access-control-allow-origin"] == "*"
assert "GET" in response.headers["access-control-allow-methods"]

def test_cors_headers_on_response(self):
response = client.get("/api/authors", headers={
"Origin": "http://localhost:3000"
})
assert response.status_code == 200
assert response.headers["access-control-allow-origin"] == "*"

def test_cors_credentials(self):
response = client.options("/api/authors", headers={
"Origin": "http://localhost:3000",
"Access-Control-Request-Method": "GET",
"Access-Control-Request-Headers": "Content-Type, Authorization"
})
assert response.status_code == 200
assert "authorization" in response.headers["access-control-allow-headers"].lower()

0 comments on commit 4ff8866

Please sign in to comment.