"""CORM 사용자 접근의 최종 판단을 ERP에 위임한다.""" import os import secrets from urllib.parse import quote import httpx from fastapi import Request from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse from starlette.middleware.base import BaseHTTPMiddleware class AuthGuardMiddleware(BaseHTTPMiddleware): def __init__(self, app): super().__init__(app) self.root = os.getenv("APP_ROOT_PATH", "").rstrip("/") self.login_url = os.getenv( "MAIN_LOGIN_URL", "https://dbx.no1king.freeddns.org/login" ) self.auth_url = os.getenv( "ERP_AUTH_URL", "http://dbx-main:8000/api/auth/check" ).strip() self.cookie_name = os.getenv("SESSION_COOKIE_NAME", "session") async def dispatch(self, request: Request, call_next): raw = request.scope.get("path", "") or "/" root = self.root or request.scope.get("root_path", "").rstrip("/") path = raw if root and (raw == root or raw.startswith(root + "/")): path = raw[len(root):] or "/" # 공개 경로는 정확히 일치할 때만 허용한다(정적 자원만 하위 경로 포함). if path.startswith("/static/") or path in { "/health", "/health/db", "/api/cafe24/callback", "/admin/oauth/callback", "/login", "/logout", "/favicon.ico", }: return await call_next(request) # 기존 OMS 등의 시스템 호출 인증. 사용자 로그인/권한과 별개다. service_token = os.getenv("INTERNAL_SERVICE_TOKEN", "") incoming = request.headers.get("x-service-token", "") if service_token and incoming and secrets.compare_digest(incoming, service_token): return await call_next(request) wants_html = "text/html" in request.headers.get("accept", "") or not path.startswith("/api/") def denied(status, message): headers = {"Cache-Control": "no-store"} if wants_html: return HTMLResponse( f'' f"
{message}
", status_code=status, headers=headers, ) return JSONResponse({"detail": message}, status_code=status, headers=headers) def unauthenticated(): if not wants_html: return denied(401, "로그인이 필요합니다.") next_path = f"{root}{path}" query = request.scope.get("query_string", b"") if query: next_path += "?" + query.decode("latin-1") sep = "&" if "?" in self.login_url else "?" return RedirectResponse( f"{self.login_url}{sep}next={quote(next_path, safe='/')}", status_code=302, headers={"Cache-Control": "no-store"}, ) cookie = request.cookies.get(self.cookie_name) if not cookie: return unauthenticated() if not self.auth_url: return denied(503, "ERP 인증 서버 설정을 확인해 주세요.") try: # 사용자별 권한 캐시 없음. 쿠키·토큰·ERP 응답 본문은 로그에 남기지 않는다. # 다른 쿠키/서비스 토큰은 전달하지 않으며 리디렉션도 따라가지 않는다. async with httpx.AsyncClient( timeout=3.0, follow_redirects=False, trust_env=False, cookies={self.cookie_name: cookie}, ) as client: response = await client.get( self.auth_url, params={"module": "corm"}, ) if response.status_code == 401: return unauthenticated() if response.status_code == 403: return denied(403, "CORM 접근 권한이 없습니다. ERP 관리자에게 문의해 주세요.") if response.status_code != 200: return denied(503, "ERP에서 접근 권한을 확인할 수 없습니다. 잠시 후 다시 시도해 주세요.") data = response.json() user = data.get("user") if isinstance(data, dict) else None if ( data.get("module") != "corm" or not isinstance(user, dict) or not isinstance(user.get("email"), str) or not user["email"].strip() ): raise ValueError("Invalid ERP authorization response") except (httpx.HTTPError, ValueError, TypeError, AttributeError): return denied(503, "ERP에서 접근 권한을 확인할 수 없습니다. 잠시 후 다시 시도해 주세요.") request.state.erp_user = user return await call_next(request)