feat(auth): delegate CORM sessions and permissions to ERP
This commit is contained in:
@@ -19,8 +19,7 @@ from urllib.parse import quote
|
||||
from dotenv import load_dotenv
|
||||
from fastapi import FastAPI, HTTPException, Request, Body, UploadFile, File, Form, Query, BackgroundTasks
|
||||
from fastapi.responses import HTMLResponse, JSONResponse, StreamingResponse, FileResponse, RedirectResponse
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.middleware.sessions import SessionMiddleware
|
||||
from erp_auth import AuthGuardMiddleware
|
||||
import pandas as pd
|
||||
|
||||
# Load local settings before application modules read environment values.
|
||||
@@ -43,80 +42,6 @@ from google_runtime import (
|
||||
APP_ROOT_PATH = os.getenv("APP_ROOT_PATH", "").rstrip("/")
|
||||
MAIN_LOGIN_URL = os.getenv("MAIN_LOGIN_URL", "https://dbx.no1king.freeddns.org/login")
|
||||
MAIN_LOGOUT_URL = os.getenv("MAIN_LOGOUT_URL", "https://dbx.no1king.freeddns.org/logout")
|
||||
SESSION_USER_KEY = os.getenv("SESSION_USER_KEY", "user_email")
|
||||
SESSION_NAME_KEY = os.getenv("SESSION_NAME_KEY", "user_name")
|
||||
|
||||
# 인증 우회 경로 — 정적 자원, 헬스, OAuth 콜백, 로그인/로그아웃 위임
|
||||
# Starlette scope.path 는 root_path 가 제거된 형태로 들어오므로 prefix 없이 매칭.
|
||||
_AUTH_EXEMPT_PREFIXES = (
|
||||
"/static/",
|
||||
"/health",
|
||||
"/api/cafe24/callback",
|
||||
"/admin/oauth/callback",
|
||||
"/login",
|
||||
"/logout",
|
||||
"/favicon.ico",
|
||||
)
|
||||
|
||||
|
||||
def _require_session_secret() -> str:
|
||||
secret = os.getenv("SESSION_SECRET_KEY", "").strip()
|
||||
if not secret:
|
||||
raise RuntimeError(
|
||||
"SESSION_SECRET_KEY 환경변수가 설정되지 않았습니다. "
|
||||
"openssl rand -hex 32 로 새 값을 만들어 .env 에 넣고 컨테이너를 재기동하세요. "
|
||||
"dbx-main 과 SSO 하려면 양쪽 .env 에 같은 값이어야 합니다."
|
||||
)
|
||||
return secret
|
||||
|
||||
|
||||
class AuthGuardMiddleware(BaseHTTPMiddleware):
|
||||
"""세션에 user_email 이 없으면 차단.
|
||||
|
||||
- HTML 요청 (Accept: text/html 또는 / 같은 페이지) → dbx-main /login?next=... 302
|
||||
- 그 외 (API 등) → 401 JSON
|
||||
- _AUTH_EXEMPT_PREFIXES 에 해당하는 경로는 통과
|
||||
"""
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
# 환경별로 scope.path 가 root_path 를 포함할 수도, 안 할 수도 있어
|
||||
# 항상 root_path 제외된 형태로 정규화한다.
|
||||
raw = request.scope.get("path", "") or "/"
|
||||
if APP_ROOT_PATH and raw.startswith(APP_ROOT_PATH + "/"):
|
||||
path = raw[len(APP_ROOT_PATH):]
|
||||
elif APP_ROOT_PATH and raw == APP_ROOT_PATH:
|
||||
path = "/"
|
||||
else:
|
||||
path = raw
|
||||
|
||||
for prefix in _AUTH_EXEMPT_PREFIXES:
|
||||
if path == prefix or path.startswith(prefix):
|
||||
return await call_next(request)
|
||||
|
||||
# 서비스 간 호출 — X-Service-Token 헤더가 일치하면 세션 없이도 통과.
|
||||
# NPM 은 외부에서 들어온 이 헤더를 빈 값으로 strip 해야 한다 (보안).
|
||||
service_token = os.getenv("INTERNAL_SERVICE_TOKEN", "")
|
||||
if service_token:
|
||||
incoming_token = request.headers.get("x-service-token", "")
|
||||
if incoming_token and incoming_token == service_token:
|
||||
return await call_next(request)
|
||||
|
||||
email = request.session.get(SESSION_USER_KEY)
|
||||
if email:
|
||||
return await call_next(request)
|
||||
|
||||
# 미인증
|
||||
accept = request.headers.get("accept", "")
|
||||
wants_html = "text/html" in accept or not path.startswith("/api/")
|
||||
if wants_html:
|
||||
next_path = f"{APP_ROOT_PATH}{path}" if APP_ROOT_PATH else path
|
||||
if request.scope.get("query_string"):
|
||||
next_path = f"{next_path}?{request.scope['query_string'].decode('latin-1')}"
|
||||
sep = "&" if "?" in MAIN_LOGIN_URL else "?"
|
||||
target = f"{MAIN_LOGIN_URL}{sep}next={quote(next_path, safe='/')}"
|
||||
return RedirectResponse(url=target, status_code=302)
|
||||
return JSONResponse({"detail": "Not authenticated"}, status_code=401)
|
||||
|
||||
# ==========================================
|
||||
# 데이터베이스 접속 설정 (환경변수 기반)
|
||||
# ==========================================
|
||||
@@ -163,21 +88,9 @@ except ImportError:
|
||||
|
||||
app = FastAPI(title="CS Web Program")
|
||||
|
||||
# 미들웨어 등록 순서 주의:
|
||||
# Starlette 은 add_middleware 를 "반대 순서로" 적용한다 (마지막에 추가한 것이 가장 바깥).
|
||||
# AuthGuardMiddleware 가 request.session 을 읽으려면 SessionMiddleware 가
|
||||
# 먼저 실행돼서 scope 에 session 을 주입해야 한다.
|
||||
# 따라서 AuthGuard 를 먼저 추가 (내부) → Session 을 나중에 추가 (외부, 먼저 실행).
|
||||
# 세션 발급/검증/갱신은 ERP만 수행한다. CORM은 쿠키를 ERP에 전달할 뿐
|
||||
# 세션 서명 키를 갖거나 Set-Cookie로 ERP 세션을 갱신하지 않는다.
|
||||
app.add_middleware(AuthGuardMiddleware)
|
||||
app.add_middleware(
|
||||
SessionMiddleware,
|
||||
secret_key=_require_session_secret(),
|
||||
session_cookie=os.getenv("SESSION_COOKIE_NAME", "session"),
|
||||
same_site=os.getenv("SESSION_SAME_SITE", "lax"),
|
||||
https_only=os.getenv("SESSION_HTTPS_ONLY", "0") == "1",
|
||||
max_age=int(os.getenv("SESSION_MAX_AGE", "28800")),
|
||||
path="/",
|
||||
)
|
||||
|
||||
|
||||
@app.get("/health/db")
|
||||
@@ -378,8 +291,8 @@ async def index(request: Request):
|
||||
context={
|
||||
"version_history": version_history,
|
||||
"root_path": APP_ROOT_PATH,
|
||||
"user_email": request.session.get(SESSION_USER_KEY, ""),
|
||||
"user_name": request.session.get(SESSION_NAME_KEY, ""),
|
||||
"user_email": getattr(request.state, "erp_user", {}).get("email", ""),
|
||||
"user_name": getattr(request.state, "erp_user", {}).get("name", ""),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user