Files
king 007a16eb9c fix(공통): 로그인 후 보던 화면으로 복귀 + 깨진 users.json 덮어쓰기 방지
- app/store.py login_redirect(): 로그인 전 화면 주소를 /login?next= 로 넘긴다(GET 만 —
  폼 POST 주소로 돌아가면 405). 경비·쿠팡·휴가·말레이시아·배송·카페24·실적 11곳이
  next 없이 /login 으로 보내던 것과 프로젝트·입출고·안내문 발송의 복사본 4벌을 이 함수로.
- UserStore._read: JSONDecodeError 를 빈 목록으로 삼키지 않는다 — 다음 로그인이 전체
  사용자·권한을 그 한 명으로 덮어쓰던 것을 막는다.
- tests/test_login_redirect.py

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 10:45:58 +09:00

127 lines
4.8 KiB
Python

"""실적 모듈 공용 가드/서비스 생성 — router.py 가 쓴다(순환 import 방지로 분리).
권한(프론트에서 메뉴를 숨기는 것과 별개로 **서버에서** 항상 검사):
- 실적 대시보드/매출 업데이트/상세 조회 : 모듈 권한 `performance` (admin 은 자동)
- 실적 설정(수수료·API 인증정보·연결 테스트·테스트 데이터) : 관리자(is_admin)만
"""
from __future__ import annotations
from typing import Any
from fastapi import HTTPException, Request
from fastapi.responses import HTMLResponse, RedirectResponse
MODULE_KEY = "performance"
MODULE_NAME = "실적"
CONFIG_HELP = (
"실적 모듈이 아직 설정되지 않았습니다. "
"scripts/sql/performance_db_init.sql 로 performance_db 를 만들고 "
"PERFORMANCE_DB_URL 환경변수를 설정한 뒤 컨테이너를 재기동하세요."
)
def get_store(request: Request) -> Any:
return getattr(request.app.state, "performance_store", None)
def key_ring():
"""마스터 키 — 호출할 때마다 환경변수에서 읽는다(DB 에는 없다)."""
from .security.crypto import KeyRing # noqa: WPS433
return KeyRing.from_env()
def key_status() -> dict[str, Any]:
"""설정 화면용 — 키가 설정됐는지/버전만. 키 값은 절대 넣지 않는다."""
from .security.crypto import CryptoConfigError # noqa: WPS433
try:
ring = key_ring()
except CryptoConfigError as exc:
return {"ok": False, "message": str(exc), "current_version": None, "versions": []}
return {"ok": True, "message": "", "current_version": ring.current_version, "versions": ring.versions}
def services(request: Request, store: Any):
"""(CredentialService, SyncService)."""
from .credentials import CredentialService # noqa: WPS433
from .sync import SyncService # noqa: WPS433
creds = CredentialService(store, key_ring)
return creds, SyncService(store, creds, app_state=request.app.state)
def require_user(request: Request) -> dict[str, Any]:
from app.main import get_current_user_record # noqa: WPS433
from app.store import has_module # noqa: WPS433
user = get_current_user_record(request)
if user is None:
raise HTTPException(status_code=401, detail="로그인이 필요합니다.")
if not has_module(user, MODULE_KEY):
raise HTTPException(status_code=403, detail=f"{MODULE_NAME} 모듈 권한이 없습니다.")
return user
def require_admin(request: Request) -> dict[str, Any]:
from app.store import is_admin # noqa: WPS433
user = require_user(request)
if not is_admin(user):
raise HTTPException(status_code=403, detail="실적 설정은 관리자만 변경할 수 있습니다.")
return user
def require_store(request: Request, *, admin: bool = False) -> tuple[Any, dict[str, Any]]:
user = require_admin(request) if admin else require_user(request)
st = get_store(request)
if st is None:
raise HTTPException(status_code=503, detail=CONFIG_HELP)
return st, user
def guard(request: Request, *, admin: bool = False):
"""페이지 진입부. tuple(store, user) 이 아니면 그대로 응답으로 돌려준다."""
from app.main import get_current_user_record, render_template # noqa: WPS433
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
user = get_current_user_record(request)
if user is None:
return login_redirect(request)
if not has_module(user, MODULE_KEY) or (admin and not is_admin(user)):
reason = "실적 설정은 관리자만 볼 수 있습니다." if admin else f"{MODULE_NAME} 접근 권한이 없습니다."
return render_template(request, "denied.html",
{"reason": reason, "user": user, "is_admin": is_admin(user)}, status_code=403)
st = get_store(request)
if st is None:
return render_config_needed(request, user)
return st, user
def render_config_needed(request: Request, user: dict[str, Any]) -> HTMLResponse:
from app.main import build_erp_nav, render_template # noqa: WPS433
from app.store import is_admin # noqa: WPS433
return render_template(
request, "denied.html",
{"reason": CONFIG_HELP, "user": user, "is_admin": is_admin(user),
"nav_items": build_erp_nav(user, active=MODULE_KEY)},
status_code=503,
)
def base_ctx(user: dict[str, Any], *, active_tab: str, page_title: str = "실적") -> dict[str, Any]:
from app.main import build_erp_nav # noqa: WPS433
from app.store import is_admin # noqa: WPS433
return {
"user": user,
"is_admin": is_admin(user),
"nav_items": build_erp_nav(user, active=MODULE_KEY),
"active_tab": active_tab,
"page_title": page_title,
"page_subtitle": "쇼핑몰 통합 매출",
}