Skip to content

Commit 87f5320

Browse files
committed
✨ feat: cors middleware
1 parent 9f2cb63 commit 87f5320

File tree

3 files changed

+34
-8
lines changed

3 files changed

+34
-8
lines changed

app/core/configs.py

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
from enum import Enum
2+
from typing import Annotated, List
23

3-
from pydantic import computed_field
4+
from pydantic import computed_field, field_validator
45
from pydantic_core import MultiHostUrl
5-
from pydantic_settings import BaseSettings
6+
from pydantic_settings import BaseSettings, NoDecode
67

78

89
class ENVIRONMENT(Enum):
@@ -33,17 +34,28 @@ class Configs(BaseSettings):
3334
DB_TABLE_CREATE: bool = True
3435

3536
# --------- AUTH SETTINGS --------- #
36-
GOOGLE_OAUTH_CLIENT_ID: str
37-
GOOGLE_OAUTH_CLIENT_SECRET: str
38-
GITHUB_OAUTH_CLIENT_ID: str
39-
GITHUB_OAUTH_CLIENT_SECRET: str
37+
ALLOW_ORIGINS: Annotated[List[str], NoDecode] = []
38+
39+
@field_validator("ALLOW_ORIGINS", mode="before")
40+
@classmethod
41+
def allow_origins(cls, value: str) -> List[str]:
42+
if value:
43+
return value.split(",")
44+
return []
45+
4046
# openssl rand -hex 32
4147
JWT_SECRET_KEY: str
4248
JWT_ALGORITHM: str
49+
4350
ADMIN_NAME: str
4451
ADMIN_EMAIL: str
4552
ADMIN_PASSWORD: str
4653

54+
GOOGLE_OAUTH_CLIENT_ID: str
55+
GOOGLE_OAUTH_CLIENT_SECRET: str
56+
GITHUB_OAUTH_CLIENT_ID: str
57+
GITHUB_OAUTH_CLIENT_SECRET: str
58+
4759
@property
4860
def DB_SCHEME(self) -> str:
4961
if self.DB_DRIVER:

app/main.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
from fastapi import FastAPI
2+
from fastapi.middleware.cors import CORSMiddleware
23
from fastapi.openapi.docs import (
34
get_swagger_ui_html,
45
get_swagger_ui_oauth2_redirect_html,
@@ -32,8 +33,20 @@
3233
app.mount("/static", StaticFiles(directory="static"), name="static")
3334
for routers in [v1_routers]:
3435
app.include_router(routers)
35-
for middleware in [SessionMiddleware, LoggingMiddleware]:
36-
app.add_middleware(middleware)
36+
for middleware, kwargs in [
37+
(SessionMiddleware, {}),
38+
(
39+
CORSMiddleware,
40+
dict(
41+
allow_origins=configs.ALLOW_ORIGINS,
42+
allow_methods=("GET", "POST", "PUT", "DELETE", "OPTIONS"),
43+
allow_headers=("Authorization", "Content-Type"),
44+
allow_credentials=True,
45+
),
46+
),
47+
(LoggingMiddleware, {}),
48+
]:
49+
app.add_middleware(middleware, **kwargs)
3750

3851

3952
@app.get("/docs", include_in_schema=False)

k8s/postgresql/configmap.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ data:
1111
TZ="Asia/Seoul"
1212
DB_ECHO=true
1313
DB_TABLE_CREATE=true
14+
ALLOW_ORIGINS=http://localhost:5173,https://svelte-cookbook.vercel.app
1415
prod.env: |
1516
PORT="8000"
1617
PROJECT_NAME="Zerohertz's FastAPI Cookbook (prod)"

0 commit comments

Comments
 (0)