From 5940f54d2bb92d222b895ab2cc62dac8464b00d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=AF=BC=ED=97=8C?= Date: Thu, 18 Jun 2026 11:16:33 +0900 Subject: [PATCH 01/14] =?UTF-8?q?feat(backend):=20supplier=5Fusers=20?= =?UTF-8?q?=EA=B8=B0=EB=B0=98=20=EC=9D=B8=EC=A6=9D=20=EC=9E=AC=EA=B5=AC?= =?UTF-8?q?=EC=B6=95=20=EB=B0=8F=20=EB=8B=A8=EC=9D=BC=EC=84=B8=EC=85=98=20?= =?UTF-8?q?=ED=86=A0=ED=81=B0=20=EC=A0=80=EC=9E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - tbl_account 예시 인증 제거, supplier_users 기반으로 일원화(generic 네이밍 재사용) - DBType USER/PARTNER 분리, AccountStatus/UserRole/TokenType enum 추가 - 보호 요청 시 su_id DB 존재/활성 검증(stateless JWT 빈틈 보완), 공급사명(partner.suppliers) 응답 포함 - 로그인 시 단일 세션 access/refresh 토큰을 supplier_user_tokens 에 저장(재로그인 시 교체) - greenlet 의존성 추가, 인증 e2e 테스트(test_auth.py) 재작성 Co-Authored-By: Claude Opus 4.8 (1M context) --- backend/common/database/db_session_manager.py | 10 +- backend/common/database/model/models.py | 77 ++++- backend/common/enums.py | 29 +- backend/common/models/gmodel.py | 9 +- backend/conftest.py | 7 +- backend/crud/user_crud.py | 126 +++++++- backend/requirements.txt | 1 + backend/router/v1/auth/account.py | 30 +- backend/router/v1/auth/protocol.py | 28 +- backend/router/v1/validator/dependencies.py | 3 +- backend/services/auth_service.py | 271 ++++++++++++----- backend/tests/test_auth.py | 283 +++++++++++++++--- 12 files changed, 707 insertions(+), 167 deletions(-) diff --git a/backend/common/database/db_session_manager.py b/backend/common/database/db_session_manager.py index 31d9d2f..b0c4a36 100644 --- a/backend/common/database/db_session_manager.py +++ b/backend/common/database/db_session_manager.py @@ -34,17 +34,21 @@ class DBSessionManager(Singleton): # 종료 시 dispose 하기 위해 생성한 엔진을 모아둔다. self.__engines = [] # 논리 DB -> config. DB 가 늘어나면 여기에 추가만 하면 된다. + # USER/PARTNER 는 물리적으로 같은 negosium_db 라 main_db_config 를 재사용한다(도메인별 논리 구분용). self.__db_type_map = { - DBType.MAIN.value: main_db_config, + DBType.USER.value: main_db_config, + DBType.PARTNER.value: main_db_config, } # Write 엔진 맵 self.__write_session = { - DBType.MAIN.value: self.create_engine(DBType.MAIN.value, DBWRType.DB_WRITE.value), + DBType.USER.value: self.create_engine(DBType.USER.value, DBWRType.DB_WRITE.value), + DBType.PARTNER.value: self.create_engine(DBType.PARTNER.value, DBWRType.DB_WRITE.value), } # Read 엔진 맵 self.__read_session = { - DBType.MAIN.value: self.create_engine(DBType.MAIN.value, DBWRType.DB_READ.value), + DBType.USER.value: self.create_engine(DBType.USER.value, DBWRType.DB_READ.value), + DBType.PARTNER.value: self.create_engine(DBType.PARTNER.value, DBWRType.DB_READ.value), } def create_engine(self, db_type: int, db_wr_type: int): diff --git a/backend/common/database/model/models.py b/backend/common/database/model/models.py index 0da66c6..edb1924 100644 --- a/backend/common/database/model/models.py +++ b/backend/common/database/model/models.py @@ -1,5 +1,6 @@ from sqlalchemy.orm import declarative_base -from sqlalchemy import Column, Integer, String, Boolean, DateTime +from sqlalchemy import Column, Integer, String, Boolean, DateTime, SmallInteger +from sqlalchemy.dialects.postgresql import UUID, JSONB from sqlalchemy.sql import text from common.enums import DBType @@ -8,19 +9,69 @@ from common.enums import DBType MAIN_BASE = declarative_base() -class tbl_account(MAIN_BASE): - # 모델이 자신이 속한 논리 DB 를 알려준다 (람다 실행 시 DBType 으로 세션 선택). +class supplier_users(MAIN_BASE): + # 이 프로젝트의 기본 유저. 실제 테이블은 negosium_db 의 supplier 스키마(supplier_users). @staticmethod def DBType(): - return DBType.MAIN.value + return DBType.USER.value - __tablename__ = "tbl_account" + __tablename__ = "supplier_users" + __table_args__ = {"schema": "supplier"} - uid = Column(Integer, primary_key=True, autoincrement=True) - id = Column(String(45), nullable=False, unique=True) # 로그인 ID. 중복 가입 방지 위해 unique. - pw = Column(String(255), nullable=False, default="") # bcrypt 해시 저장 - nickname = Column(String(45), nullable=False, default="") - is_blocked = Column(Boolean, nullable=False, default=False) - # PostgreSQL UTC now: now() 는 timestamptz 이므로 utc 로 변환해 timestamp 로 저장. - last_login_at = Column(DateTime, nullable=False, server_default=text("(now() AT TIME ZONE 'utc')")) - create_at = Column(DateTime, server_default=text("(now() AT TIME ZONE 'utc')")) + # gen_random_uuid() 는 pgcrypto 확장 기준. 코드값(status/role/type)은 SMALLINT 정수 코드(앱 enum 매핑). + su_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")) # 유저 식별자(PK) + supplier_id = Column(UUID(as_uuid=True), nullable=False) # 소속 공급사(partner.suppliers.supplier_id) + id = Column(String(20), nullable=False) # 로그인 ID + password = Column(String(255), nullable=False) # 해시된 비밀번호이어야 함 + name = Column(String(50), nullable=True) # 이름 + email = Column(String(255), nullable=True) # 이메일 + contact_number = Column(String(20), nullable=True) # 연락처 + last_accessed_at = Column(DateTime(timezone=True), nullable=False) # 마지막 접속 시각 + status = Column(SmallInteger, nullable=False, server_default=text("1")) # 상태: 1=active, 2=inactive + role = Column(SmallInteger, nullable=False, server_default=text("1")) # 권한: 1=user, 2=manager + created_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')")) # 생성 시각(UTC) + updated_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')")) # 수정 시각(UTC, 앱에서 갱신) + deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부 + + +class suppliers(MAIN_BASE): + # partner.suppliers (공급사 회사). 공급사명(name) 조회용. partner 도메인이라 DBType 은 PARTNER. + @staticmethod + def DBType(): + return DBType.PARTNER.value + + __tablename__ = "suppliers" + __table_args__ = {"schema": "partner"} + + supplier_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")) # 공급사 식별자(PK) + company_id = Column(UUID(as_uuid=True), nullable=False) # 소속 회사(company.companies.company_id) + user_id = Column(UUID(as_uuid=True), nullable=False) # 등록 유저(company.users.user_id) + name = Column(String(100), nullable=False) # 공급사명 + code = Column(String(20), nullable=True) # 공급사 코드 + manager_name = Column(String(50), nullable=True) # 담당자명 + manager_email = Column(String(255), nullable=True) # 담당자 이메일 + manager_contact_number = Column(String(20), nullable=True) # 담당자 연락처 + priority = Column(String(10), nullable=True) # 우선순위 (고객사별 문자열 값 가능) + created_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')")) # 생성 시각(UTC) + updated_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')")) # 수정 시각(UTC, 앱에서 갱신) + deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부 + + +class supplier_user_tokens(MAIN_BASE): + # 유저 인증 토큰. supplier_users 1 : N tokens. + @staticmethod + def DBType(): + return DBType.USER.value + + __tablename__ = "supplier_user_tokens" + __table_args__ = {"schema": "supplier"} + + sut_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")) # 토큰 식별자(PK) + su_id = Column(UUID(as_uuid=True), nullable=False) # 소유 유저(supplier.supplier_users.su_id) + type = Column(SmallInteger, nullable=False) # 토큰 종류 (코드, 앱 enum 매핑) + token = Column(JSONB, nullable=False) # 토큰 본문(JSON) + issued_at = Column(DateTime(timezone=True), nullable=False) # 발급 시각 + expired_at = Column(DateTime(timezone=True), nullable=False) # 만료 시각 + created_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')")) # 생성 시각(UTC) + updated_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')")) # 수정 시각(UTC, 앱에서 갱신) + deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부 diff --git a/backend/common/enums.py b/backend/common/enums.py index 8793ea9..99c76ba 100644 --- a/backend/common/enums.py +++ b/backend/common/enums.py @@ -49,9 +49,11 @@ EXCEPTION_HTTP_INVALID_TOKEN_ACCESS = HTTPException(status_code=ErrorType.HTTP_I class DBType(Enum): """논리 DB 구분. 모델마다 DBType() 으로 자신이 속한 DB 를 반환한다. DB 가 늘어나면 여기에 추가하고 db_session_manager 의 맵에 등록만 하면 된다. + 물리적으로 같은 negosium_db 라도 도메인별 논리 구분으로 나눠 둘 수 있다(커넥션 config 는 재사용). """ - MAIN = 1 + USER = 1 # 기본 유저 (supplier_users 테이블) + PARTNER = 2 # partner 도메인 (partner.suppliers 등) class DBWRType(Enum): @@ -59,3 +61,28 @@ class DBWRType(Enum): DB_READ = 1 DB_WRITE = 2 + + +# ============================================================ +# 도메인 코드값. 스키마는 SMALLINT 정수 코드(1부터)로 두고, 의미 매핑은 여기 enum 으로 한다. +# (postgres-init/01-schema.sql: "코드값(status/role/type 등)은 SMALLINT 정수 코드로 둔다") +# ============================================================ +class AccountStatus(Enum): + """계정 상태 코드. company.users / supplier.supplier_users 의 status 컬럼.""" + + ACTIVE = 1 # 활성 + INACTIVE = 2 # 비활성 + + +class UserRole(Enum): + """유저 권한 코드. company.users / supplier.supplier_users 의 role 컬럼.""" + + USER = 1 # 일반 유저 + MANAGER = 2 # 매니저 + + +class TokenType(Enum): + """토큰 종류 코드. supplier.supplier_user_tokens 의 type 컬럼.""" + + ACCESS = 1 + REFRESH = 2 diff --git a/backend/common/models/gmodel.py b/backend/common/models/gmodel.py index b09f002..36d3ab9 100644 --- a/backend/common/models/gmodel.py +++ b/backend/common/models/gmodel.py @@ -46,11 +46,14 @@ class Res_WebPacketProtocol(WebPacketProtocol): class UserInfo(StructModel): - """JWT subject 로 인코딩되는 유저 식별 정보.""" + """JWT subject 로 인코딩되는 유저 식별 정보. su_id/supplier_id 는 uuid 문자열로 인코딩한다.""" - uid: int + su_id: str id: str - nickname: str + name: str + supplier_id: str + supplier_name: str + role: int def __init__(self, *args, **kwargs) -> None: super().__init__() diff --git a/backend/conftest.py b/backend/conftest.py index d5a3fe8..b1f138f 100644 --- a/backend/conftest.py +++ b/backend/conftest.py @@ -6,7 +6,6 @@ os.environ.setdefault("APP_ENV", "local") import pytest_asyncio from httpx import ASGITransport, AsyncClient -from sqlalchemy import text from sqlalchemy.ext.asyncio import create_async_engine from common.database.model.models import MAIN_BASE @@ -20,15 +19,13 @@ def _write_url(cfg) -> str: @pytest_asyncio.fixture async def db_engine(): - """테스트용 스키마를 보장하고, 매 테스트 시작 시 테이블을 비워 격리한다. + """테스트용 스키마를 보장한다. 격리는 각 테스트가 전용 행만 시드/정리하는 방식으로 한다. - 앱(DB_SESSION_MNG)은 자체 엔진으로 같은 DB(config.test.toml)에 접속하므로, - 여기서 만든 스키마를 그대로 공유한다. + 앱(DB_SESSION_MNG)은 자체 엔진으로 같은 DB 에 접속하므로 여기서 만든 스키마를 그대로 공유한다. """ engine = create_async_engine(_write_url(main_db_config)) async with engine.begin() as conn: await conn.run_sync(MAIN_BASE.metadata.create_all) # 이미 있으면 skip - await conn.execute(text("TRUNCATE TABLE tbl_account")) yield engine await engine.dispose() diff --git a/backend/crud/user_crud.py b/backend/crud/user_crud.py index b2a7ac6..ee70bfd 100644 --- a/backend/crud/user_crud.py +++ b/backend/crud/user_crud.py @@ -1,12 +1,12 @@ from abc import ABC, abstractmethod from typing import Tuple -from sqlalchemy import select, update +from sqlalchemy import delete, select, update from sqlalchemy.ext.asyncio import AsyncSession from common.database.db_session_manager import DB_SESSION_MNG -from common.database.model.models import tbl_account -from common.enums import ErrorType +from common.database.model.models import supplier_user_tokens, supplier_users, suppliers +from common.enums import ErrorType, TokenType from common.logger import LOG from common.utils.gtime import GTime @@ -14,29 +14,54 @@ from common.utils.gtime import GTime # CRUD 는 인터페이스(I*) 와 구현(*) 으로 분리한다. # - service 는 인터페이스 타입에 의존하고 Depends 로 구현을 주입받는다 (테스트/교체 용이). # - 모든 메서드는 (session, ...) 을 받는다. session 은 람다 호출 시 매니저가 넘겨준다. +# - 유저는 supplier_users 테이블, 공급사명은 partner.suppliers 에서 조회한다(no-FK). class IUserCRUD(ABC): @abstractmethod - async def get_account_by_id(self, cdb: AsyncSession, user_id: str) -> Tuple[ErrorType, tbl_account]: + async def get_account_by_id(self, cdb: AsyncSession, login_id: str) -> Tuple[ErrorType, supplier_users]: pass @abstractmethod - async def is_account(self, cdb: AsyncSession, user_id: str) -> ErrorType: + async def get_account_by_su_id(self, cdb: AsyncSession, su_id) -> Tuple[ErrorType, supplier_users]: pass @abstractmethod - async def add_account(self, cdb: AsyncSession, account: tbl_account) -> ErrorType: + async def get_supplier_name(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, str]: pass @abstractmethod - async def update_last_login(self, cdb: AsyncSession, user_uid: int) -> ErrorType: + async def is_account(self, cdb: AsyncSession, login_id: str) -> ErrorType: + pass + + @abstractmethod + async def add_account(self, cdb: AsyncSession, account: supplier_users) -> ErrorType: + pass + + @abstractmethod + async def add_token(self, cdb: AsyncSession, token: supplier_user_tokens) -> ErrorType: + pass + + @abstractmethod + async def delete_tokens_by_su_id(self, cdb: AsyncSession, su_id) -> ErrorType: + pass + + @abstractmethod + async def update_access_token(self, cdb: AsyncSession, su_id, token, issued_at, expired_at) -> ErrorType: + pass + + @abstractmethod + async def update_last_accessed(self, cdb: AsyncSession, su_id) -> ErrorType: pass class UserCRUD(IUserCRUD): - async def get_account_by_id(self, cdb: AsyncSession, user_id: str) -> Tuple[ErrorType, tbl_account]: + async def get_account_by_id(self, cdb: AsyncSession, login_id: str) -> Tuple[ErrorType, supplier_users]: try: - query = select(tbl_account).where(tbl_account.id == user_id).limit(1) - err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_account_by_id(ID:{user_id}) failed.") + query = ( + select(supplier_users) + .where(supplier_users.id == login_id, supplier_users.deleted == False) # noqa: E712 + .limit(1) + ) + err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_account_by_id(ID:{login_id}) failed.") if err_type != ErrorType.SUCCESS: return err_type, None if len(row_list) != 1: @@ -46,9 +71,47 @@ class UserCRUD(IUserCRUD): LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED, None - async def is_account(self, cdb: AsyncSession, user_id: str) -> ErrorType: + async def get_account_by_su_id(self, cdb: AsyncSession, su_id) -> Tuple[ErrorType, supplier_users]: try: - query = select(tbl_account).where(tbl_account.id == user_id).limit(1) + query = ( + select(supplier_users) + .where(supplier_users.su_id == su_id, supplier_users.deleted == False) # noqa: E712 + .limit(1) + ) + err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_account_by_su_id(su_id:{su_id}) failed.") + if err_type != ErrorType.SUCCESS: + return err_type, None + if len(row_list) != 1: + return ErrorType.DB_INVALID_KEY, None + return ErrorType.SUCCESS, row_list[0] + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, None + + async def get_supplier_name(self, cdb: AsyncSession, supplier_id) -> Tuple[ErrorType, str]: + try: + query = ( + select(suppliers.name) + .where(suppliers.supplier_id == supplier_id, suppliers.deleted == False) # noqa: E712 + .limit(1) + ) + err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_supplier_name(supplier_id:{supplier_id}) failed.") + if err_type != ErrorType.SUCCESS: + return err_type, None + if len(row_list) != 1: + return ErrorType.DB_INVALID_KEY, None + return ErrorType.SUCCESS, row_list[0] + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, None + + async def is_account(self, cdb: AsyncSession, login_id: str) -> ErrorType: + try: + query = ( + select(supplier_users) + .where(supplier_users.id == login_id, supplier_users.deleted == False) # noqa: E712 + .limit(1) + ) err_type, row_list = await DB_SESSION_MNG.execute(cdb, query) if err_type != ErrorType.SUCCESS: return err_type @@ -59,16 +122,49 @@ class UserCRUD(IUserCRUD): LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED - async def add_account(self, cdb: AsyncSession, account: tbl_account) -> ErrorType: + async def add_account(self, cdb: AsyncSession, account: supplier_users) -> ErrorType: try: return await DB_SESSION_MNG.insert(cdb, account) except Exception as ex: LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED - async def update_last_login(self, cdb: AsyncSession, user_uid: int) -> ErrorType: + async def add_token(self, cdb: AsyncSession, token: supplier_user_tokens) -> ErrorType: try: - query = update(tbl_account).where(tbl_account.uid == user_uid).values(last_login_at=GTime.UTC()) + return await DB_SESSION_MNG.insert(cdb, token) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED + + async def delete_tokens_by_su_id(self, cdb: AsyncSession, su_id) -> ErrorType: + # 단일 세션: 로그인/로그아웃 시 해당 유저의 토큰 행을 모두 제거한다(하드 삭제, 누적 방지). + try: + query = delete(supplier_user_tokens).where(supplier_user_tokens.su_id == su_id) + return await DB_SESSION_MNG.add(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED + + async def update_access_token(self, cdb: AsyncSession, su_id, token, issued_at, expired_at) -> ErrorType: + # 재발급 시 저장된 access 행만 새 토큰으로 갱신한다. + try: + query = ( + update(supplier_user_tokens) + .where( + supplier_user_tokens.su_id == su_id, + supplier_user_tokens.type == TokenType.ACCESS.value, + supplier_user_tokens.deleted == False, # noqa: E712 + ) + .values(token=token, issued_at=issued_at, expired_at=expired_at) + ) + return await DB_SESSION_MNG.add(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED + + async def update_last_accessed(self, cdb: AsyncSession, su_id) -> ErrorType: + try: + query = update(supplier_users).where(supplier_users.su_id == su_id).values(last_accessed_at=GTime.UTC()) return await DB_SESSION_MNG.add(cdb, query) except Exception as ex: LOG.e_no_callstack(ex) diff --git a/backend/requirements.txt b/backend/requirements.txt index 2f928b6..332cd3b 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -1,6 +1,7 @@ fastapi uvicorn[standard] sqlalchemy>=2.0 +greenlet # SQLAlchemy async 의 sync/async 브리지에 필수 (일부 환경에서 자동 설치 누락됨) asyncpg python-jose[cryptography] bcrypt diff --git a/backend/router/v1/auth/account.py b/backend/router/v1/auth/account.py index b5d4648..df3de34 100644 --- a/backend/router/v1/auth/account.py +++ b/backend/router/v1/auth/account.py @@ -1,12 +1,9 @@ from fastapi import APIRouter, Depends, Request -from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer from common.models.gmodel import UserInfo from router.v1.validator.dependencies import IsValidAccessToken, IsValidRefreshToken, RemoveNoneResponse from services.auth_service import AuthService -from .protocol import Req_CreateAccount, Req_Login, Res_CreateAccount, Res_Login, Res_RefreshToken - -security = HTTPBearer() +from .protocol import Req_CreateAccount, Req_Login, Res_CreateAccount, Res_Login, Res_Me, Res_RefreshToken # 라우터(MVC 의 컨트롤러). 요청 검증 -> service 호출 -> RemoveNoneResponse 반환만 담당. router = APIRouter(prefix="/v1/auth", tags=["Auth"], responses={404: {"description": "Not found"}}) @@ -17,26 +14,31 @@ async def login(request: Request, req: Req_Login, service: AuthService = Depends return RemoveNoneResponse(await service.attempt_login(req.id, req.pw, request.client.host)) -@router.post(path="/create", response_model=Res_CreateAccount, summary="계정 생성", description="새 계정을 생성한다.") +# TODO: 계정 생성은 관리자/매니저 권한으로 제한할 가능성이 있음(현재는 비보호). +@router.post(path="/create", response_model=Res_CreateAccount, summary="계정 생성", description="supplier_id 소속의 유저를 생성한다(공급사 존재를 앱에서 검증).") async def create_account(request: Request, req: Req_CreateAccount, service: AuthService = Depends()): - return RemoveNoneResponse(await service.create_account(req.id, req.pw, req.nickname, request.client.host)) + return RemoveNoneResponse( + await service.create_account( + req.supplier_id, req.id, req.pw, req.name, req.email, req.contact_number, req.role, request.client.host + ) + ) @router.post( path="/refresh_token", - dependencies=[Depends(IsValidRefreshToken)], response_model=Res_RefreshToken, summary="액세스 토큰 갱신", - description="refresh 토큰으로 access 토큰을 재발급한다.", + description="refresh 토큰으로 access 토큰을 재발급한다. su_id DB 존재/활성은 service 에서 확인한다.", ) -async def refresh_token(service: AuthService = Depends(), credentials: HTTPAuthorizationCredentials = Depends(security)): - return RemoveNoneResponse(await service.refresh_token(credentials.credentials)) +async def refresh_token(user_info: UserInfo = Depends(IsValidRefreshToken), service: AuthService = Depends()): + return RemoveNoneResponse(await service.refresh_token(user_info)) @router.get( path="/me", - summary="내 정보 (보호된 엔드포인트 예시)", - description="유효한 access 토큰이 있어야 호출 가능. 토큰 검증 결과 UserInfo 를 주입받는다.", + response_model=Res_Me, + summary="내 정보 (보호된 엔드포인트)", + description="access 토큰 검증(validator) 후 su_id DB 존재/활성을 service 에서 확인해 반환한다.", ) -async def me(user_info: UserInfo = Depends(IsValidAccessToken)): - return {"uid": user_info.uid, "id": user_info.id, "nickname": user_info.nickname} +async def me(user_info: UserInfo = Depends(IsValidAccessToken), service: AuthService = Depends()): + return RemoveNoneResponse(await service.get_me(user_info)) diff --git a/backend/router/v1/auth/protocol.py b/backend/router/v1/auth/protocol.py index 2ef226e..c3cda59 100644 --- a/backend/router/v1/auth/protocol.py +++ b/backend/router/v1/auth/protocol.py @@ -1,5 +1,3 @@ -from pydantic import Field - from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol @@ -14,21 +12,37 @@ class Req_Login(AuthProtocol): class Res_Login(Res_WebPacketProtocol): - uid: int = Field(0, description="user uid", json_schema_extra={"format": "int64"}) - nickname: str = "" + su_id: str = "" + name: str = "" # 유저 개인 이름 + supplier_id: str = "" # 소속 공급사(partner.suppliers) + supplier_name: str = "" # 공급사명 + role: int = 0 access_token: str = "" refresh_token: str = "" class Req_CreateAccount(AuthProtocol): - id: str = "" + supplier_id: str = "" # 소속 공급사(partner.suppliers.supplier_id) + id: str = "" # 로그인 ID pw: str = "" - nickname: str = "" + name: str = "" + email: str = "" + contact_number: str = "" + role: int = 1 # 1=user, 2=manager (UserRole) class Res_CreateAccount(Res_WebPacketProtocol): - uid: int = Field(0, description="생성된 user uid", json_schema_extra={"format": "int64"}) + su_id: str = "" class Res_RefreshToken(Res_WebPacketProtocol): access_token: str = "" + + +class Res_Me(Res_WebPacketProtocol): + su_id: str = "" + id: str = "" + name: str = "" + supplier_id: str = "" + supplier_name: str = "" + role: int = 0 diff --git a/backend/router/v1/validator/dependencies.py b/backend/router/v1/validator/dependencies.py index 73ad74e..08d676f 100644 --- a/backend/router/v1/validator/dependencies.py +++ b/backend/router/v1/validator/dependencies.py @@ -88,8 +88,7 @@ def DecodeRefreshToken(jwt_token: str) -> UserInfo: return __decode_token(jwt_token, JWT_REFRESH_SECRET, EXCEPTION_REFRESH_TOKEN_EXPIRED) -# ---- Depends 용 토큰 검증기 ------------------------------------------------ -# 보호된 엔드포인트에서 dependencies=[Depends(IsValidAccessToken)] 로 사용. +# ---- Depends 용 토큰 검증기 (디코드만; DB 존재/활성 검증은 service 가 담당) ----- async def IsValidAccessToken(credentials: HTTPAuthorizationCredentials = Depends(security)) -> UserInfo: return DecodeAccessToken(credentials.credentials) diff --git a/backend/services/auth_service.py b/backend/services/auth_service.py index 1d41675..e91c48c 100644 --- a/backend/services/auth_service.py +++ b/backend/services/auth_service.py @@ -1,24 +1,23 @@ +import uuid + from fastapi import Depends from common.database.db_session_manager import DB_SESSION_MNG -from common.database.model.models import tbl_account -from common.enums import DBWRType, ErrorType +from common.database.model.models import supplier_user_tokens, supplier_users, suppliers +from common.enums import AccountStatus, DBWRType, ErrorType, TokenType from common.logger import LOG from common.models.gmodel import UserInfo +from common.utils.gtime import GTime +from config.server_configs import jwt_token_config from crud.user_crud import IUserCRUD, UserCRUD -from router.v1.auth.protocol import Res_CreateAccount, Res_Login, Res_RefreshToken -from router.v1.validator.dependencies import ( - CreateAccessToken, - CreateRefreshToken, - DecodeRefreshToken, - GetHashedPW, - VerifyPW, -) +from router.v1.auth.protocol import Res_CreateAccount, Res_Login, Res_Me, Res_RefreshToken +from router.v1.validator.dependencies import CreateAccessToken, CreateRefreshToken, GetHashedPW, VerifyPW class AuthService: """비즈니스 로직 계층 (MVC 의 컨트롤러-서비스 분리에서 서비스). + - 유저는 supplier_users 테이블(JWT subject = UserInfo). uuid 는 문자열로 인코딩. - CRUD 는 Depends 로 인터페이스 타입으로 주입받는다. - DB 접근은 DB_SESSION_MNG 의 람다 실행으로만 한다. 조회 = execute_lambda(..., DB_READ, lambda s: crud.xxx(s, ...)) @@ -29,57 +28,33 @@ class AuthService: def __init__(self, user_crud: IUserCRUD = Depends(UserCRUD)): self.user_crud = user_crud - async def attempt_login(self, id: str, pw: str, connect_ip: str) -> Res_Login: - LOG.i(f"LOGIN : {id=}") - res = Res_Login() - - # 1) 계정 조회 (Read DB) - err_type, account = await DB_SESSION_MNG.execute_lambda( - tbl_account.DBType(), - DBWRType.DB_READ.value, - lambda s: self.user_crud.get_account_by_id(s, id), - ) - if err_type != ErrorType.SUCCESS: - # 계정 없음/조회 실패 모두 로그인 실패로 일반화 - res.result.SetResult(ErrorType.ACCOUNT_INVALID_INFO) - return res - account: tbl_account - - # 2) 비밀번호 검증 - if not await VerifyPW(pw, account.pw): - res.result.SetResult(ErrorType.ACCOUNT_INVALID_INFO) - return res - - # 3) 차단 여부 - if account.is_blocked: - res.result.SetResult(ErrorType.ACCOUNT_BLOCKED_USER) - return res - - # 4) 토큰 발급 - user_info = UserInfo(uid=account.uid, id=account.id, nickname=account.nickname) - res.access_token = CreateAccessToken(user_info) - res.refresh_token = CreateRefreshToken(user_info) - - # 5) 마지막 로그인 시간 갱신 (Write DB, 트랜잭션) - err_type = await DB_SESSION_MNG.execute_lambda_run( - [tbl_account.DBType()], - [lambda s: self.user_crud.update_last_login(s, account.uid)], - ) - if err_type != ErrorType.SUCCESS: - res.result.SetResult(err_type) - return res - - res.uid = account.uid - res.nickname = account.nickname - return res - - async def create_account(self, id: str, pw: str, nickname: str, connect_ip: str) -> Res_CreateAccount: - LOG.i(f"CREATE : {id=}, {nickname=}") + async def create_account( + self, supplier_id: str, id: str, pw: str, name: str, email: str, contact_number: str, role: int, connect_ip: str + ) -> Res_CreateAccount: + LOG.i(f"CREATE : {id=}, {supplier_id=}") res = Res_CreateAccount() - # 1) 중복 ID 확인 (Read DB) + # 0) supplier_id 형식 검증 + try: + sid = uuid.UUID(supplier_id) + except (ValueError, TypeError): + res.result.SetResult(ErrorType.INVALID_REQUEST_DATA) + return res + + # 1) 공급사 존재 확인 (no-FK 라 앱에서 무결성 검증, PARTNER Read) + err_type, _ = await DB_SESSION_MNG.execute_lambda( + suppliers.DBType(), + DBWRType.DB_READ.value, + lambda s: self.user_crud.get_supplier_name(s, sid), + ) + if err_type != ErrorType.SUCCESS: + # 존재하지 않는 supplier_id + res.result.SetResult(ErrorType.INVALID_REQUEST_DATA) + return res + + # 2) 중복 로그인 ID 확인 (USER Read) err_type = await DB_SESSION_MNG.execute_lambda( - tbl_account.DBType(), + supplier_users.DBType(), DBWRType.DB_READ.value, lambda s: self.user_crud.is_account(s, id), ) @@ -90,26 +65,188 @@ class AuthService: res.result.SetResult(err_type) return res - # 2) 계정 생성 (비밀번호는 bcrypt 해시로 저장) - account = tbl_account(id=id, pw=await GetHashedPW(pw), nickname=nickname or id) + # 3) 생성 (pw bcrypt 해시. last_accessed_at 은 NOT NULL/무기본값이라 생성 시각으로 둔다) + account = supplier_users( + supplier_id=sid, + id=id, + password=await GetHashedPW(pw), + name=name or None, + email=email or None, + contact_number=contact_number or None, + last_accessed_at=GTime.UTC(), + status=AccountStatus.ACTIVE.value, + role=role, + ) err_type = await DB_SESSION_MNG.execute_lambda_run( - [tbl_account.DBType()], + [supplier_users.DBType()], [lambda s: self.user_crud.add_account(s, account)], ) if err_type != ErrorType.SUCCESS: - # 사전 검사와 INSERT 사이의 경쟁 조건에서 unique 위반이 나면 동일 코드로 매핑. + # 사전 검사와 INSERT 사이 경쟁 조건의 unique 위반은 동일 코드로 매핑. if err_type == ErrorType.DB_ALREADY_SAME_KEY: res.result.SetResult(ErrorType.ACCOUNT_ALREADY_EXIST) else: res.result.SetResult(err_type) return res - res.uid = account.uid + res.su_id = str(account.su_id) return res - async def refresh_token(self, refresh_token: str) -> Res_RefreshToken: - res = Res_RefreshToken() - # refresh 토큰 검증은 라우터 Depends(IsValidRefreshToken) 에서 1차 수행됨. - user_info = DecodeRefreshToken(refresh_token) + async def attempt_login(self, id: str, pw: str, connect_ip: str) -> Res_Login: + LOG.i(f"LOGIN : {id=}") + res = Res_Login() + + # 1) 계정 조회 (USER Read 세션) + err_type, account = await DB_SESSION_MNG.execute_lambda( + supplier_users.DBType(), + DBWRType.DB_READ.value, + lambda s: self.user_crud.get_account_by_id(s, id), + ) + if err_type != ErrorType.SUCCESS: + # 계정 없음/조회 실패 모두 로그인 실패로 일반화 + res.result.SetResult(ErrorType.ACCOUNT_INVALID_INFO) + return res + account: supplier_users + + # 2) 비밀번호 검증 + if not await VerifyPW(pw, account.password): + res.result.SetResult(ErrorType.ACCOUNT_INVALID_INFO) + return res + + # 3) 상태 확인 (active 만 허용) + if account.status != AccountStatus.ACTIVE.value: + res.result.SetResult(ErrorType.ACCOUNT_BLOCKED_USER) + return res + + # 3-1) 공급사명 조회 (PARTNER Read 세션). 부가 정보라 실패해도 로그인은 막지 않고 빈 값. + _, sname = await DB_SESSION_MNG.execute_lambda( + suppliers.DBType(), + DBWRType.DB_READ.value, + lambda s: self.user_crud.get_supplier_name(s, account.supplier_id), + ) + supplier_name = sname or "" + + # 4) 토큰 발급 + user_info = UserInfo( + su_id=str(account.su_id), + id=account.id, + name=account.name or "", + supplier_id=str(account.supplier_id), + supplier_name=supplier_name, + role=account.role, + ) res.access_token = CreateAccessToken(user_info) + res.refresh_token = CreateRefreshToken(user_info) + + # 5) 마지막 접속 시간 갱신 + 토큰 교체 (Write DB, 한 트랜잭션) + # 단일 세션: 이전 토큰 행을 모두 지우고 access/refresh 2행을 새로 넣어 이전 세션을 무효화한다. + # 저장된 토큰은 추후 로그아웃/검증(토큰 대조)에서 사용한다. + now = GTime.UTC() + access_row = supplier_user_tokens( + su_id=account.su_id, + type=TokenType.ACCESS.value, + token={"jwt": res.access_token}, + issued_at=now, + expired_at=GTime.AddMinutes(jwt_token_config.access_expire_min), + ) + refresh_row = supplier_user_tokens( + su_id=account.su_id, + type=TokenType.REFRESH.value, + token={"jwt": res.refresh_token}, + issued_at=now, + expired_at=GTime.AddDays(jwt_token_config.refresh_expire_day), + ) + err_type = await DB_SESSION_MNG.execute_lambda_run( + [supplier_users.DBType()], + [ + lambda s: self.user_crud.update_last_accessed(s, account.su_id), + lambda s: self.user_crud.delete_tokens_by_su_id(s, account.su_id), # 단일 세션: 이전 토큰 제거 + lambda s: self.user_crud.add_token(s, access_row), + lambda s: self.user_crud.add_token(s, refresh_row), + ], + ) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + res.su_id = str(account.su_id) + res.name = account.name or "" + res.supplier_id = str(account.supplier_id) + res.supplier_name = supplier_name + res.role = account.role + return res + + async def __load_active_account(self, su_id_str: str) -> tuple[ErrorType, UserInfo]: + """su_id 로 유저를 조회해 존재 + status=active 확인 후, 공급사명까지 채운 DB 최신값 UserInfo 를 + 반환한다. (토큰 발급 후 삭제/비활성된 계정 차단용) + 실패 시 (에러코드, None) 을 반환하며, HTTP 변환은 라우터가 result 로 내려보낸다. + """ + # 1) 계정 조회 (USER Read 세션) + err_type, account = await DB_SESSION_MNG.execute_lambda( + supplier_users.DBType(), + DBWRType.DB_READ.value, + lambda s: self.user_crud.get_account_by_su_id(s, uuid.UUID(su_id_str)), + ) + if err_type != ErrorType.SUCCESS or account is None: + return ErrorType.ACCOUNT_INVALID_INFO, None + if account.status != AccountStatus.ACTIVE.value: # active 만 허용 + return ErrorType.ACCOUNT_BLOCKED_USER, None + + # 2) 공급사명 조회 (PARTNER Read 세션). 부가 정보라 실패해도 빈 값. + _, sname = await DB_SESSION_MNG.execute_lambda( + suppliers.DBType(), + DBWRType.DB_READ.value, + lambda s: self.user_crud.get_supplier_name(s, account.supplier_id), + ) + return ErrorType.SUCCESS, UserInfo( + su_id=str(account.su_id), + id=account.id, + name=account.name or "", + supplier_id=str(account.supplier_id), + supplier_name=sname or "", + role=account.role, + ) + + async def get_me(self, user_info: UserInfo) -> Res_Me: + # 토큰 디코드는 라우터 Depends(IsValidAccessToken) 에서 수행됨. 여기선 su_id DB 검증. + res = Res_Me() + err_type, info = await self.__load_active_account(user_info.su_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + res.su_id = info.su_id + res.id = info.id + res.name = info.name + res.supplier_id = info.supplier_id + res.supplier_name = info.supplier_name + res.role = info.role + return res + + async def refresh_token(self, user_info: UserInfo) -> Res_RefreshToken: + # 토큰 디코드는 라우터 Depends(IsValidRefreshToken) 에서 수행됨. 여기선 su_id DB 검증 후 재발급. + res = Res_RefreshToken() + err_type, info = await self.__load_active_account(user_info.su_id) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + new_access = CreateAccessToken(info) # DB 최신값으로 재구성한 토큰 + # 단일 세션: 저장된 access 행을 새 토큰으로 갱신한다(refresh 행은 유지). + err_type = await DB_SESSION_MNG.execute_lambda_run( + [supplier_users.DBType()], + [ + lambda s: self.user_crud.update_access_token( + s, + uuid.UUID(info.su_id), + {"jwt": new_access}, + GTime.UTC(), + GTime.AddMinutes(jwt_token_config.access_expire_min), + ) + ], + ) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + res.access_token = new_access return res diff --git a/backend/tests/test_auth.py b/backend/tests/test_auth.py index 47963c4..c59f866 100644 --- a/backend/tests/test_auth.py +++ b/backend/tests/test_auth.py @@ -1,63 +1,272 @@ -"""auth 도메인 e2e 테스트. +"""인증 e2e 테스트 (supplier_users 기반 유저). -실행 전제: docker-compose 로 PostgreSQL 이 떠 있어야 한다 (negosium_db 사용). - docker compose up -d # 또는 로컬 postgres +실행 전제: PostgreSQL 이 떠 있어야 한다 (negosium_db, supplier/partner 스키마 적용). cd backend && python -m pytest + +테스트는 dev negosium_db 를 그대로 쓰므로, 다른 데이터를 건드리지 않도록 +TRUNCATE 대신 전용 테스트 행(pytest_user)만 시드/정리한다. """ +import uuid -async def test_create_and_login_flow(client): - # 1) 계정 생성 - r = await client.post("/v1/auth/create", json={"id": "user1", "pw": "pw1234", "nickname": "닉네임"}) +import bcrypt +import pytest_asyncio +from sqlalchemy import text + +TEST_LOGIN_ID = "pytest_user" +TEST_PW = "pytest1234" +TEST_USER_NAME = "테스트담당자" # supplier_users.name (유저 개인 이름) +TEST_SUPPLIER_NAME = "파이테스트공급사" # partner.suppliers.name (공급사명) + + +@pytest_asyncio.fixture +async def account_seed(db_engine): + """partner.suppliers(공급사) + supplier.supplier_users(유저) 테스트 행을 시드하고, 끝나면 정리한다.""" + supplier_id = uuid.uuid4() + pw_hash = bcrypt.hashpw(TEST_PW.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") + + async def _cleanup(conn): + await conn.execute( + text( + "DELETE FROM supplier.supplier_user_tokens WHERE su_id IN " + "(SELECT su_id FROM supplier.supplier_users WHERE id = :id)" + ), + {"id": TEST_LOGIN_ID}, + ) + await conn.execute(text("DELETE FROM supplier.supplier_users WHERE id = :id"), {"id": TEST_LOGIN_ID}) + await conn.execute(text("DELETE FROM partner.suppliers WHERE name = :n"), {"n": TEST_SUPPLIER_NAME}) + + async with db_engine.begin() as conn: + await _cleanup(conn) # 이전 실행 잔재 제거 + await conn.execute( + text( + "INSERT INTO partner.suppliers (supplier_id, company_id, user_id, name) " + "VALUES (:sid, gen_random_uuid(), gen_random_uuid(), :name)" + ), + {"sid": supplier_id, "name": TEST_SUPPLIER_NAME}, + ) + await conn.execute( + text( + "INSERT INTO supplier.supplier_users " + "(supplier_id, id, password, name, last_accessed_at, status, role) " + "VALUES (:sid, :id, :pw, :uname, now(), 1, 1)" + ), + {"sid": supplier_id, "id": TEST_LOGIN_ID, "pw": pw_hash, "uname": TEST_USER_NAME}, + ) + + yield {"supplier_id": supplier_id} + + # 테스트 중 생성된 유저/토큰까지 정리하기 위해 supplier_id 기준으로 지운다. + async with db_engine.begin() as conn: + await conn.execute( + text( + "DELETE FROM supplier.supplier_user_tokens WHERE su_id IN " + "(SELECT su_id FROM supplier.supplier_users WHERE supplier_id = :sid)" + ), + {"sid": supplier_id}, + ) + await conn.execute(text("DELETE FROM supplier.supplier_users WHERE supplier_id = :sid"), {"sid": supplier_id}) + await conn.execute(text("DELETE FROM partner.suppliers WHERE supplier_id = :sid"), {"sid": supplier_id}) + + +async def _set_account(db_engine, **values): + """테스트용 유저 행의 컬럼을 갱신한다 (status/deleted 등).""" + sets = ", ".join(f"{k} = :{k}" for k in values) + params = {**values, "id": TEST_LOGIN_ID} + async with db_engine.begin() as conn: + await conn.execute(text(f"UPDATE supplier.supplier_users SET {sets} WHERE id = :id"), params) + + +async def _login(client): + return await client.post("/v1/auth/login", json={"id": TEST_LOGIN_ID, "pw": TEST_PW}) + + +# ---- 생성 ------------------------------------------------------------------- +async def test_create_success(client, account_seed): + sid = str(account_seed["supplier_id"]) + r = await client.post( + "/v1/auth/create", + json={"supplier_id": sid, "id": "pytest_new", "pw": "newpw1234", "name": "새담당자", "role": 2}, + ) assert r.status_code == 200 body = r.json() assert body["result"]["success"] is True - assert body["uid"] > 0 + assert body["su_id"] + # 생성된 계정으로 즉시 로그인 가능 + r2 = await client.post("/v1/auth/login", json={"id": "pytest_new", "pw": "newpw1234"}) + lb = r2.json() + assert lb["result"]["success"] is True + assert lb["role"] == 2 # 매니저로 생성됨 - # 2) 로그인 -> 토큰 발급 - r = await client.post("/v1/auth/login", json={"id": "user1", "pw": "pw1234"}) + +async def test_create_duplicate(client, account_seed): + sid = str(account_seed["supplier_id"]) + payload = {"supplier_id": sid, "id": "pytest_dup", "pw": "x12345"} + r1 = await client.post("/v1/auth/create", json=payload) + assert r1.json()["result"]["success"] is True + r2 = await client.post("/v1/auth/create", json=payload) + assert r2.json()["result"]["code"] == 1201 # ACCOUNT_ALREADY_EXIST + + +async def test_create_invalid_supplier(client, account_seed): + # 존재하지 않는 supplier_id (no-FK 라 앱에서 검증) + r = await client.post( + "/v1/auth/create", + json={"supplier_id": str(uuid.uuid4()), "id": "pytest_orphan", "pw": "x12345"}, + ) + body = r.json() + assert body["result"]["success"] is False + assert body["result"]["code"] == 101 # INVALID_REQUEST_DATA + + +async def test_create_malformed_supplier_id(client, account_seed): + r = await client.post( + "/v1/auth/create", + json={"supplier_id": "not-a-uuid", "id": "pytest_bad", "pw": "x12345"}, + ) + assert r.json()["result"]["code"] == 101 # INVALID_REQUEST_DATA + + +# ---- 로그인 ----------------------------------------------------------------- +async def test_login_success(client, account_seed): + r = await _login(client) assert r.status_code == 200 body = r.json() assert body["result"]["success"] is True assert body["access_token"] assert body["refresh_token"] - assert body["nickname"] == "닉네임" - access_token = body["access_token"] - - # 3) 보호된 엔드포인트 호출 - r = await client.get("/v1/auth/me", headers={"Authorization": f"Bearer {access_token}"}) - assert r.status_code == 200 - assert r.json()["id"] == "user1" + assert body["name"] == TEST_USER_NAME # 유저 개인 이름 + assert body["supplier_name"] == TEST_SUPPLIER_NAME # 공급사명(partner.suppliers) + assert body["role"] == 1 + assert body["su_id"] + assert body["supplier_id"] == str(account_seed["supplier_id"]) -async def test_login_with_wrong_password(client): - await client.post("/v1/auth/create", json={"id": "user2", "pw": "correct", "nickname": "n"}) - - r = await client.post("/v1/auth/login", json={"id": "user2", "pw": "wrong"}) +async def test_login_wrong_password(client, account_seed): + r = await client.post("/v1/auth/login", json={"id": TEST_LOGIN_ID, "pw": "wrong"}) assert r.status_code == 200 body = r.json() assert body["result"]["success"] is False - # 자격증명 오류는 ACCOUNT_INVALID_INFO(1200) - assert body["result"]["code"] == 1200 - assert body.get("access_token", "") == "" # 실패 시 토큰은 빈 문자열 + assert body["result"]["code"] == 1200 # ACCOUNT_INVALID_INFO + assert body.get("access_token", "") == "" -async def test_login_nonexistent_account(client): - r = await client.post("/v1/auth/login", json={"id": "ghost", "pw": "whatever"}) - assert r.json()["result"]["success"] is False - - -async def test_duplicate_account_create(client): - r1 = await client.post("/v1/auth/create", json={"id": "dup", "pw": "pw1234", "nickname": "n"}) - assert r1.json()["result"]["success"] is True - - r2 = await client.post("/v1/auth/create", json={"id": "dup", "pw": "pw5678", "nickname": "n2"}) - body = r2.json() +async def test_login_nonexistent(client): + r = await client.post("/v1/auth/login", json={"id": "ghost_user", "pw": "whatever"}) + assert r.status_code == 200 + body = r.json() assert body["result"]["success"] is False - # ACCOUNT_ALREADY_EXIST(1201) - assert body["result"]["code"] == 1201 + assert body["result"]["code"] == 1200 -async def test_me_without_token_is_rejected(client): +async def _stored_tokens(db_engine, su_id): + """su_id 의 저장된 토큰을 {type: jwt} dict 로 반환.""" + import json + + async with db_engine.begin() as conn: + rows = ( + await conn.execute( + text("SELECT type, token FROM supplier.supplier_user_tokens WHERE su_id = :sid AND deleted = false"), + {"sid": uuid.UUID(su_id)}, + ) + ).fetchall() + out = {} + for t, tok in rows: + out[t] = (json.loads(tok) if isinstance(tok, str) else tok)["jwt"] + return out + + +async def test_login_stores_access_and_refresh(client, account_seed, db_engine): + # 로그인 시 access(type=1) + refresh(type=2) 2행이 저장되고, 응답 토큰과 일치한다. + body = (await _login(client)).json() + assert body["result"]["success"] is True + stored = await _stored_tokens(db_engine, body["su_id"]) + assert set(stored.keys()) == {1, 2} # ACCESS, REFRESH + assert stored[1] == body["access_token"] + assert stored[2] == body["refresh_token"] + + +async def test_relogin_replaces_tokens_single_session(client, account_seed, db_engine): + # 단일 세션: 재로그인해도 토큰 행이 누적되지 않고 항상 정확히 2행(access/refresh)만 유지된다. + await _login(client) + second = (await _login(client)).json() + su_id = second["su_id"] + async with db_engine.begin() as conn: + count = ( + await conn.execute( + text("SELECT count(*) FROM supplier.supplier_user_tokens WHERE su_id = :sid AND deleted = false"), + {"sid": uuid.UUID(su_id)}, + ) + ).scalar() + assert count == 2 # 누적되지 않음 (2번 로그인해도 2행) + stored = await _stored_tokens(db_engine, su_id) + assert stored[2] == second["refresh_token"] # 최신 로그인 토큰으로 교체됨 + + +async def test_login_inactive(client, account_seed, db_engine): + await _set_account(db_engine, status=2) # 비활성 + r = await _login(client) + body = r.json() + assert body["result"]["success"] is False + assert body["result"]["code"] == 1202 # ACCOUNT_BLOCKED_USER + + +# ---- /me (보호된 엔드포인트) ------------------------------------------------- +async def test_me_active(client, account_seed): + access = (await _login(client)).json()["access_token"] + r = await client.get("/v1/auth/me", headers={"Authorization": f"Bearer {access}"}) + assert r.status_code == 200 + body = r.json() + assert body["result"]["success"] is True + assert body["id"] == TEST_LOGIN_ID + assert body["supplier_name"] == TEST_SUPPLIER_NAME + + +async def test_me_inactive_after_token(client, account_seed, db_engine): + # 토큰 발급 후 계정이 비활성(status=2)되면 만료 전이라도 차단된다 (200 + result code). + access = (await _login(client)).json()["access_token"] + await _set_account(db_engine, status=2) + r = await client.get("/v1/auth/me", headers={"Authorization": f"Bearer {access}"}) + assert r.status_code == 200 + assert r.json()["result"]["code"] == 1202 # ACCOUNT_BLOCKED_USER + + +async def test_me_deleted_after_token(client, account_seed, db_engine): + # 소프트 삭제(deleted=TRUE)된 계정도 차단된다. + access = (await _login(client)).json()["access_token"] + await _set_account(db_engine, deleted=True) + r = await client.get("/v1/auth/me", headers={"Authorization": f"Bearer {access}"}) + assert r.status_code == 200 + assert r.json()["result"]["code"] == 1200 # ACCOUNT_INVALID_INFO (조회 안 됨) + + +async def test_me_without_token(client): r = await client.get("/v1/auth/me") assert r.status_code in (401, 403) # HTTPBearer 가 자격증명 없음을 거부 + + +async def test_me_invalid_token(client): + r = await client.get("/v1/auth/me", headers={"Authorization": "Bearer garbage.token.value"}) + assert r.status_code == 433 # HTTP_INVALID_CLIENT_ACCESS (validator 가 raise) + + +# ---- refresh ---------------------------------------------------------------- +async def test_refresh_success(client, account_seed): + refresh = (await _login(client)).json()["refresh_token"] + r = await client.post("/v1/auth/refresh_token", headers={"Authorization": f"Bearer {refresh}"}) + assert r.status_code == 200 + body = r.json() + assert body["result"]["success"] is True + assert body["access_token"] + + +async def test_refresh_inactive_after_token(client, account_seed, db_engine): + # 삭제/비활성 계정에는 토큰을 재발급하지 않는다. + refresh = (await _login(client)).json()["refresh_token"] + await _set_account(db_engine, status=2) + r = await client.post("/v1/auth/refresh_token", headers={"Authorization": f"Bearer {refresh}"}) + assert r.status_code == 200 + body = r.json() + assert body["result"]["success"] is False + assert body["result"]["code"] == 1202 + assert body.get("access_token", "") == "" From 2832162672079105f8f55a2df4c3000c9cd976a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=AF=BC=ED=97=8C?= Date: Thu, 18 Jun 2026 11:16:43 +0900 Subject: [PATCH 02/14] =?UTF-8?q?feat(backend):=20CORS=20=ED=97=88?= =?UTF-8?q?=EC=9A=A9=20=EC=98=A4=EB=A6=AC=EC=A7=84=20=EC=84=A4=EC=A0=95=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - WebServerConfig.cors_origins(list) 추가, config 의 오리진이 있을 때만 CORSMiddleware 적용 - 명시적 오리진이라 allow_credentials=true (Authorization 헤더 허용) - 로컬 기본값: http://localhost:5173, http://127.0.0.1:5173 (Vite) Co-Authored-By: Claude Opus 4.8 (1M context) --- backend/config/config.local.toml.example | 2 ++ backend/config/config_models.py | 2 ++ backend/router/router.py | 13 +++++++++++++ 3 files changed, 17 insertions(+) diff --git a/backend/config/config.local.toml.example b/backend/config/config.local.toml.example index adb45b8..8f95efc 100644 --- a/backend/config/config.local.toml.example +++ b/backend/config/config.local.toml.example @@ -7,6 +7,8 @@ port = 9300 process_count = 1 is_ssl = false is_test = true +# CORS 허용 오리진(프론트). 비우면 [] (CORS 미적용). 예: 로컬 Vite = http://localhost:5173 +cors_origins = ["http://localhost:5173", "http://127.0.0.1:5173"] [LogConfig] print_console = true diff --git a/backend/config/config_models.py b/backend/config/config_models.py index d5af607..c338b82 100644 --- a/backend/config/config_models.py +++ b/backend/config/config_models.py @@ -7,6 +7,8 @@ class WebServerConfig(ConfigModel): process_count: int = 1 is_ssl: bool = False is_test: bool = False + # CORS 허용 오리진(프론트). 비우면 CORS 미적용. 예: ["http://localhost:5173"] + cors_origins: list[str] = [] class LogConfig(ConfigModel): diff --git a/backend/router/router.py b/backend/router/router.py index 15eec9c..6a8c54f 100644 --- a/backend/router/router.py +++ b/backend/router/router.py @@ -2,11 +2,13 @@ import time from contextlib import asynccontextmanager from fastapi import FastAPI, Request +from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.gzip import GZipMiddleware from common.database.db_session_manager import DB_SESSION_MNG from common.logger import LOG from common.utils.gtime import GTime +from config.server_configs import web_server_config import router.v1.auth.account API_SERVER_START_TIME = GTime.UTCStr() @@ -22,6 +24,17 @@ async def lifespan(app: FastAPI): app = FastAPI(title="Negosium Api Server", lifespan=lifespan) +# CORS: config 의 cors_origins 가 있을 때만 적용(브라우저 프론트 호출 허용). +# 명시적 오리진을 쓰므로 allow_credentials=True 가능(쿠키/Authorization 헤더 허용). +if web_server_config.cors_origins: + app.add_middleware( + CORSMiddleware, + allow_origins=web_server_config.cors_origins, + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + ) + # Accept-Encoding: gzip 요청에 대해 1000 bytes 이상 응답을 압축. app.add_middleware(GZipMiddleware, minimum_size=1000) From 23cb8291bc2cc468f66c2f88329d49ce8d6d3c47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=AF=BC=ED=97=8C?= Date: Thu, 18 Jun 2026 11:16:55 +0900 Subject: [PATCH 03/14] =?UTF-8?q?chore(backend):=20=EB=A1=9C=EC=BB=AC=20?= =?UTF-8?q?=EC=8B=A4=ED=96=89/=EB=B6=80=ED=95=98=ED=85=8C=EC=8A=A4?= =?UTF-8?q?=ED=8A=B8=20=EC=8A=A4=ED=81=AC=EB=A6=BD=ED=8A=B8=20=EC=B6=94?= =?UTF-8?q?=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - run_local_server.sh / run_local_locust.sh / run_local_pgwatch.sh (대화형, 메뉴 선택 방식) - loadtest: self-register 방식 locustfile (가상 유저가 on_start 에서 계정 생성 → login/me/refresh) - locust 스크립트가 부하용 공급사 보장·이전 부하계정/토큰 정리·LOAD_SUPPLIER_ID 주입을 자동 처리 Co-Authored-By: Claude Opus 4.8 (1M context) --- backend/loadtest/locustfile.py | 89 ++++++++++++++++++++++------------ backend/run_local_locust.sh | 88 +++++++++++++++++++++++++++++++++ backend/run_local_pgwatch.sh | 62 +++++++++++++++++++++++ backend/run_local_server.sh | 57 ++++++++++++++++++++++ 4 files changed, 266 insertions(+), 30 deletions(-) create mode 100755 backend/run_local_locust.sh create mode 100755 backend/run_local_pgwatch.sh create mode 100755 backend/run_local_server.sh diff --git a/backend/loadtest/locustfile.py b/backend/loadtest/locustfile.py index af9f02f..900a06f 100644 --- a/backend/loadtest/locustfile.py +++ b/backend/loadtest/locustfile.py @@ -1,74 +1,101 @@ -"""Negosium 인증 서버 부하 테스트. +"""인증 서버 부하 테스트 (self-register 방식, 사전 시드 불필요). -실행: - pip install locust - locust -f loadtest/locustfile.py --host http://localhost:9300 - # 웹 UI: http://localhost:8089 에서 사용자 수/spawn rate 입력 +각 가상 유저가 on_start 에서 자기 계정을 생성(/create)하고 로그인한 뒤, +me/login/refresh/healthz 를 가중치대로 반복한다. - # 헤드리스(CI) 예시 - 100 VU, 10/s 증가, 2분: - locust -f loadtest/locustfile.py --host http://localhost:9300 \ - --headless -u 100 -r 10 -t 2m +supplier 의 /create 는 supplier_id(소속 공급사)가 필수이므로, run_local_locust.sh 가 +부하용 공급사(부하테스트공급사) 1건을 보장하고 그 supplier_id 를 LOAD_SUPPLIER_ID 로 넘긴다. + +직접 실행 시: + LOAD_SUPPLIER_ID=<공급사 uuid> locust -f loadtest/locustfile.py --host http://localhost:9300 + +정리(테스트 후, self-register 로 쌓인 계정 삭제): + psql ... -c "DELETE FROM supplier.supplier_users WHERE id LIKE 'load_user_%';" 주의: -- /login 은 bcrypt 검증(CPU 바운드)이 들어가 가장 무겁다. RPS 가 낮으면 - 거의 확실히 bcrypt cost 가 병목이다 (DB 아님). -- 부하를 올리며 서버 측에서 PostgreSQL 커넥션 수를 함께 모니터링하라: - SELECT count(*) FROM pg_stat_activity; - (pool_size + max_overflow) x 2(R/W) x 워커수 가 max_connections 를 넘으면 - max_connections 초과 시 실패한다. +- /create, /login 은 bcrypt(CPU 바운드) + DB read/write 라 가장 무겁다. +- /me, /refresh 는 su_id DB 존재/활성 검증(read 2회)을 한다 — 순수 JWT 경로가 아니다. +- 논리 DB 가 USER/PARTNER 2개라 같은 negosium_db 에 엔진 풀이 4벌(R/W×2) 잡힌다. + SELECT count(*) FROM pg_stat_activity WHERE datname = 'negosium_db'; """ +import os import random from locust import HttpUser, between, events, task +LOAD_SUPPLIER_ID = os.environ.get("LOAD_SUPPLIER_ID", "") +LOAD_PW = "loadpw1234" + -# 각 시뮬레이션 유저는 고유 계정을 만들어 로그인 흐름을 반복한다. class AuthUser(HttpUser): wait_time = between(0.5, 2.0) def on_start(self): - # 유저별 고유 계정 생성 후 1회 로그인하여 토큰 확보. - self.user_id = f"load_{random.randint(0, 1_000_000_000)}" - self.password = "pw1234" - self.token = None - - self.client.post( + # 유저마다 고유 계정을 생성(self-register)하고 로그인해 토큰을 확보한다. + self.login_id = f"load_user_{random.randint(0, 1_000_000_000)}" + self.access_token = None + self.refresh_token = None + with self.client.post( "/v1/auth/create", - json={"id": self.user_id, "pw": self.password, "nickname": "load"}, + json={"supplier_id": LOAD_SUPPLIER_ID, "id": self.login_id, "pw": LOAD_PW}, name="POST /v1/auth/create", - ) + catch_response=True, + ) as resp: + if resp.status_code == 200 and resp.json().get("result", {}).get("success"): + resp.success() + else: + resp.failure(f"create failed: {resp.status_code} {resp.text[:120]}") self._login() def _login(self): with self.client.post( "/v1/auth/login", - json={"id": self.user_id, "pw": self.password}, + json={"id": self.login_id, "pw": LOAD_PW}, name="POST /v1/auth/login", catch_response=True, ) as resp: if resp.status_code == 200 and resp.json().get("result", {}).get("success"): - self.token = resp.json().get("access_token") + body = resp.json() + self.access_token = body.get("access_token") + self.refresh_token = body.get("refresh_token") resp.success() else: resp.failure(f"login failed: {resp.status_code} {resp.text[:120]}") @task(5) def me(self): - # JWT 검증만 하는 경량 경로 (DB 無). bcrypt 경로와 처리량 비교용. - if not self.token: + # 토큰 검증 + su_id/공급사명 DB 조회(2 read). 보호 엔드포인트 처리량 측정. + if not self.access_token: return self.client.get( "/v1/auth/me", - headers={"Authorization": f"Bearer {self.token}"}, + headers={"Authorization": f"Bearer {self.access_token}"}, name="GET /v1/auth/me", ) @task(2) def login(self): - # bcrypt + DB write 가 포함된 무거운 경로. + # bcrypt + DB read 2 + DB write 가 포함된 무거운 경로. self._login() + @task(1) + def refresh(self): + # refresh 토큰 검증 + su_id DB 존재/활성 확인 후 access 재발급. + if not self.refresh_token: + return + with self.client.post( + "/v1/auth/refresh_token", + headers={"Authorization": f"Bearer {self.refresh_token}"}, + name="POST /v1/auth/refresh_token", + catch_response=True, + ) as resp: + if resp.status_code == 200 and resp.json().get("result", {}).get("success"): + self.access_token = resp.json().get("access_token") + resp.success() + else: + resp.failure(f"refresh failed: {resp.status_code} {resp.text[:120]}") + @task(1) def healthz(self): # 베이스라인 (앱 오버헤드 측정). @@ -77,4 +104,6 @@ class AuthUser(HttpUser): @events.test_start.add_listener def _on_start(environment, **kwargs): - print("부하 테스트 시작 - PostgreSQL 커넥션 수 모니터링 권장 (pg_stat_activity)") + if not LOAD_SUPPLIER_ID: + print("[warn] LOAD_SUPPLIER_ID 가 비어있습니다 — /create 가 전부 실패합니다. run_local_locust.sh 로 실행하세요.") + print("부하 테스트 시작 - self-register 방식. PostgreSQL 커넥션 수 모니터링 권장 (pg_stat_activity)") diff --git a/backend/run_local_locust.sh b/backend/run_local_locust.sh new file mode 100755 index 0000000..bbeea31 --- /dev/null +++ b/backend/run_local_locust.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +# +# 로컬 부하테스트(locust) 실행 (대화형). 실행하면 파일/시드/방식을 골라 입력한다. +# loadtest/ 아래 locust 파일이 늘어나도 목록에서 선택만 하면 된다. +# +set -euo pipefail +cd "$(dirname "$0")" # backend/ + +VENV=".venv" +LOCUST="$VENV/bin/locust" +HOST="${LOCUST_HOST:-http://localhost:9300}" +# 시드용 DB 접속 (local 기본값, 환경변수로 override 가능) +PGHOST="${PGHOST:-127.0.0.1}" +PGPORT="${PGPORT:-5432}" +PGUSER="${PGUSER:-postgres}" +PGDATABASE="${PGDATABASE:-negosium_db}" + +# locust 설치 보장 +if [[ ! -x "$LOCUST" ]]; then + echo "[setup] locust 설치..." + "$VENV/bin/python" -m pip install -q locust +fi + +# 1) locust 파일 선택 +FILES=() +while IFS= read -r f; do + FILES+=("$f") +done < <(ls -1 loadtest/*.py 2>/dev/null | grep -v __pycache__ || true) +if [[ ${#FILES[@]} -eq 0 ]]; then + echo "[error] loadtest/ 에 locust 파일이 없습니다." + exit 1 +fi +echo "── locust 파일 선택 ──" +i=1 +for f in "${FILES[@]}"; do + echo " $i) ${f#loadtest/}" + i=$((i + 1)) +done +read -rp "선택 [1]: " fsel +fsel="${fsel:-1}" +FILE="${FILES[$((fsel - 1))]:-}" +if [[ -z "$FILE" ]]; then + echo "[error] 잘못된 선택: $fsel" + exit 1 +fi + +# 2) 부하용 공급사 1건 보장 → supplier_id 를 LOAD_SUPPLIER_ID 로 넘긴다. +# 유저는 사전 시드하지 않고 locust on_start 에서 self-register 한다(tbl 방식). +# (없으면 만들고, 있으면 그대로 사용 = get-or-create) +LOAD_SUPPLIER_ID="$(psql -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" -d "$PGDATABASE" -t -A -c " +WITH ex AS ( + SELECT supplier_id FROM partner.suppliers WHERE name='부하테스트공급사' AND deleted=false LIMIT 1 +), ins AS ( + INSERT INTO partner.suppliers (supplier_id, company_id, user_id, name) + SELECT gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), '부하테스트공급사' + WHERE NOT EXISTS (SELECT 1 FROM ex) + RETURNING supplier_id +) +SELECT supplier_id FROM ins UNION ALL SELECT supplier_id FROM ex LIMIT 1; +" 2>/dev/null | tr -d '[:space:]')" +if [[ -z "$LOAD_SUPPLIER_ID" ]]; then + echo "[error] 부하용 공급사 supplier_id 를 확보하지 못했습니다 (DB 접속/스키마 확인)." + exit 1 +fi + +# 이전 실행에서 self-register 로 쌓인 계정/토큰 정리(누적 방지). 공급사 행은 재사용하므로 남긴다. +psql -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" -d "$PGDATABASE" -q \ + -c "DELETE FROM supplier.supplier_user_tokens WHERE su_id IN (SELECT su_id FROM supplier.supplier_users WHERE id LIKE 'load_user_%'); + DELETE FROM supplier.supplier_users WHERE id LIKE 'load_user_%';" >/dev/null 2>&1 || true +echo "[info] 부하용 공급사 supplier_id=$LOAD_SUPPLIER_ID (유저는 self-register, 이전 부하계정 정리됨)" + +# 3) 실행 방식 선택 +echo "── 실행 방식 ──" +echo " 1) 웹 UI (브라우저에서 사용자 수 조절, http://localhost:8089)" +echo " 2) 헤드리스 (값 입력)" +read -rp "선택 [1]: " mode +mode="${mode:-1}" + +if [[ "$mode" == "2" ]]; then + read -rp "동시 사용자 수 [50]: " VU; VU="${VU:-50}" + read -rp "초당 증가 수 [10]: " RATE; RATE="${RATE:-10}" + read -rp "지속 시간(예 30s/2m) [1m]: " DUR; DUR="${DUR:-1m}" + echo "[run] $FILE headless -u $VU -r $RATE -t $DUR (host=$HOST)" + exec env LOAD_SUPPLIER_ID="$LOAD_SUPPLIER_ID" "$LOCUST" -f "$FILE" --host "$HOST" --headless -u "$VU" -r "$RATE" -t "$DUR" +else + echo "[run] $FILE 웹 UI → http://localhost:8089 (host=$HOST)" + exec env LOAD_SUPPLIER_ID="$LOAD_SUPPLIER_ID" "$LOCUST" -f "$FILE" --host "$HOST" +fi diff --git a/backend/run_local_pgwatch.sh b/backend/run_local_pgwatch.sh new file mode 100755 index 0000000..7c3ef5b --- /dev/null +++ b/backend/run_local_pgwatch.sh @@ -0,0 +1,62 @@ +#!/usr/bin/env bash +# +# PostgreSQL 커넥션 모니터 (로그 방식). negosium_db 커넥션을 한 줄씩 쌓아가며 본다. +# 부하테스트(run_local_locust.sh) 중 별도 터미널에서 띄워 풀 사용량 추세를 관찰한다. +# (화면을 덮어쓰지 않으므로 스크롤로 이력을 그대로 볼 수 있다) +# +set -uo pipefail +cd "$(dirname "$0")" # backend/ + +# DB 접속 (local 기본값, 환경변수로 override 가능) +PGHOST="${PGHOST:-127.0.0.1}" +PGPORT="${PGPORT:-5432}" +PGUSER="${PGUSER:-postgres}" +PGDATABASE="${PGDATABASE:-negosium_db}" + +q() { psql -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" -d "$PGDATABASE" "$@"; } + +# 접속 확인 +if ! q -tAc "SELECT 1" >/dev/null 2>&1; then + echo "[error] DB 접속 실패: $PGUSER@$PGHOST:$PGPORT/$PGDATABASE" + exit 1 +fi +MAXCONN="$(q -tAc "SHOW max_connections;" 2>/dev/null | tr -d '[:space:]')" +MAXCONN="${MAXCONN:-0}" + +read -rp "갱신 간격(초) [1]: " ITV; ITV="${ITV:-1}" +read -rp "로그 파일로도 저장 (경로, 비우면 화면만): " LOGF + +echo "DB=$PGDATABASE max_connections=$MAXCONN (Ctrl+C 로 종료)" +echo " - total: 전체 커넥션 / active: 실행 중 / idle: 풀 유휴 / idle_tx: 트랜잭션 유휴(누수 의심)" +HEADER="시각 total active idle idle_tx" +echo "$HEADER" +[[ -n "$LOGF" ]] && { echo "# $HEADER" >>"$LOGF"; } + +emit() { # 화면 + (옵션)파일 + echo "$1" + [[ -n "$LOGF" ]] && echo "$1" >>"$LOGF" +} + +# 우리 앱 풀 산식(참고): USER/PARTNER × R/W = 엔진 4벌 × (pool_size+max_overflow) = 최대 120 / 워커 +while true; do + TS="$(date '+%H:%M:%S')" + # 상태별 카운트를 한 쿼리로(모니터 자신은 제외). 출력: "total active idle idle_tx" + ROW="$(q -tAF' ' -c "SELECT count(*), + count(*) FILTER (WHERE state='active'), + count(*) FILTER (WHERE state='idle'), + count(*) FILTER (WHERE state='idle in transaction') + FROM pg_stat_activity + WHERE datname='$PGDATABASE' AND pid <> pg_backend_pid();" 2>/dev/null)" + read -r TOTAL ACTIVE IDLE IDLETX <<<"${ROW:-0 0 0 0}" + TOTAL="${TOTAL:-0}"; ACTIVE="${ACTIVE:-0}"; IDLE="${IDLE:-0}"; IDLETX="${IDLETX:-0}" + + PCT=0 + if [[ "$MAXCONN" =~ ^[0-9]+$ && "$MAXCONN" -gt 0 ]]; then PCT=$(( TOTAL * 100 / MAXCONN )); fi + WARN="" + if (( PCT >= 80 )); then WARN=" <- max 임박!"; fi + + emit "$(printf '%s %3s/%s (%3s%%) %5s %4s %4s%s' \ + "$TS" "$TOTAL" "$MAXCONN" "$PCT" "$ACTIVE" "$IDLE" "$IDLETX" "$WARN")" + + sleep "$ITV" +done diff --git a/backend/run_local_server.sh b/backend/run_local_server.sh new file mode 100755 index 0000000..d0b493e --- /dev/null +++ b/backend/run_local_server.sh @@ -0,0 +1,57 @@ +#!/usr/bin/env bash +# +# 로컬 백엔드 서버 실행 (대화형). 실행하면 모드를 골라 입력한다. +# 최초 실행 시 venv 생성 + 의존성 설치까지 자동으로 한다. +# +set -euo pipefail +cd "$(dirname "$0")" # backend/ + +VENV=".venv" +PY="$VENV/bin/python" +PORT=9300 + +# 1) venv + 의존성 보장 +if [[ ! -d "$VENV" ]]; then + echo "[setup] venv 생성 + 의존성 설치..." + python3 -m venv "$VENV" + "$PY" -m pip install -q --upgrade pip + "$PY" -m pip install -q -r requirements.txt +fi + +# 2) config 보장 +if [[ ! -f config/config.local.toml ]]; then + echo "[error] config/config.local.toml 이 없습니다. 아래로 생성 후 값을 채우세요:" + echo " cp config/config.local.toml.example config/config.local.toml" + exit 1 +fi + +# 3) 모드 선택 +echo "── 실행 모드 선택 ──" +echo " 1) 일반 실행 (web_main.py)" +echo " 2) 자동 재시작 (uvicorn --reload, 개발용)" +echo " 3) 의존성 재설치" +echo " q) 취소" +read -rp "선택 [1]: " choice +choice="${choice:-1}" + +case "$choice" in + 3) echo "[setup] 의존성 재설치..."; "$PY" -m pip install -q -r requirements.txt; echo "완료"; exit 0 ;; + q|Q) echo "취소합니다."; exit 0 ;; +esac + +# 4) 포트 정리 (이미 떠 있으면 종료) +if lsof -ti:"$PORT" >/dev/null 2>&1; then + echo "[info] 포트 $PORT 사용 중 → 기존 프로세스 종료" + lsof -ti:"$PORT" | xargs kill 2>/dev/null || true + sleep 1 +fi +export APP_ENV=local + +# 5) 실행 +case "$choice" in + 1) echo "[run] web_main.py → http://localhost:$PORT/docs" + exec "$PY" web_main.py ;; + 2) echo "[run] uvicorn --reload → http://localhost:$PORT/docs" + exec "$VENV/bin/uvicorn" router.router:app --host 0.0.0.0 --port "$PORT" --reload ;; + *) echo "[error] 알 수 없는 선택: $choice"; exit 1 ;; +esac From 698d4e72d4dd2b40e84108ca13eb088e2239c0f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=AF=BC=ED=97=8C?= Date: Thu, 18 Jun 2026 11:26:08 +0900 Subject: [PATCH 04/14] =?UTF-8?q?feat(backend):=20=EB=A1=9C=EA=B7=B8?= =?UTF-8?q?=EC=95=84=EC=9B=83=20+=20stateful=20=ED=86=A0=ED=81=B0=20?= =?UTF-8?q?=EA=B2=80=EC=A6=9D=20(=EB=8B=A8=EC=9D=BC=20=EC=84=B8=EC=85=98?= =?UTF-8?q?=20=EC=A6=89=EC=8B=9C=20=ED=8F=90=EA=B8=B0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - POST /v1/auth/logout: 저장된 access/refresh 토큰 행 삭제 → 즉시 로그아웃 - /me, refresh 에서 제시된 토큰을 저장된 토큰과 대조(불일치 시 TOKEN_REVOKED=1203) → 로그아웃/타기기 재로그인으로 교체된 토큰을 만료 전이라도 차단 - crud get_token 추가, ErrorType.TOKEN_REVOKED(1203) 추가, Res_Logout 프로토콜 - 로그아웃/단일세션 무효화 e2e 테스트 추가 (test_auth.py) Co-Authored-By: Claude Opus 4.8 (1M context) --- backend/common/enums.py | 1 + backend/crud/user_crud.py | 26 +++++++++++++++ backend/router/v1/auth/account.py | 40 ++++++++++++++++++----- backend/router/v1/auth/protocol.py | 4 +++ backend/services/auth_service.py | 38 +++++++++++++++++++--- backend/tests/test_auth.py | 52 ++++++++++++++++++++++++++++++ 6 files changed, 148 insertions(+), 13 deletions(-) diff --git a/backend/common/enums.py b/backend/common/enums.py index 99c76ba..e3525b7 100644 --- a/backend/common/enums.py +++ b/backend/common/enums.py @@ -35,6 +35,7 @@ class ErrorType(Enum): ACCOUNT_INVALID_INFO = 1200 ACCOUNT_ALREADY_EXIST = auto() ACCOUNT_BLOCKED_USER = auto() + TOKEN_REVOKED = auto() # 제시된 토큰이 저장된 토큰과 불일치(로그아웃/타기기 로그인으로 교체됨) # ErrorType 의 HTTP_* 값과 status_code 를 맞춰 router 단에서 raise 한다. diff --git a/backend/crud/user_crud.py b/backend/crud/user_crud.py index ee70bfd..88af505 100644 --- a/backend/crud/user_crud.py +++ b/backend/crud/user_crud.py @@ -40,6 +40,10 @@ class IUserCRUD(ABC): async def add_token(self, cdb: AsyncSession, token: supplier_user_tokens) -> ErrorType: pass + @abstractmethod + async def get_token(self, cdb: AsyncSession, su_id, token_type: int) -> Tuple[ErrorType, str]: + pass + @abstractmethod async def delete_tokens_by_su_id(self, cdb: AsyncSession, su_id) -> ErrorType: pass @@ -136,6 +140,28 @@ class UserCRUD(IUserCRUD): LOG.e_no_callstack(ex) return ErrorType.DB_RUN_FAILED + async def get_token(self, cdb: AsyncSession, su_id, token_type: int) -> Tuple[ErrorType, str]: + # 저장된 토큰(jwt 문자열)을 반환한다. stateful 검증(제시 토큰 ↔ 저장 토큰 대조)용. + try: + query = ( + select(supplier_user_tokens.token["jwt"].astext) + .where( + supplier_user_tokens.su_id == su_id, + supplier_user_tokens.type == token_type, + supplier_user_tokens.deleted == False, # noqa: E712 + ) + .limit(1) + ) + err_type, row_list = await DB_SESSION_MNG.execute(cdb, query) + if err_type != ErrorType.SUCCESS: + return err_type, None + if len(row_list) != 1: + return ErrorType.DB_INVALID_KEY, None + return ErrorType.SUCCESS, row_list[0] + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, None + async def delete_tokens_by_su_id(self, cdb: AsyncSession, su_id) -> ErrorType: # 단일 세션: 로그인/로그아웃 시 해당 유저의 토큰 행을 모두 제거한다(하드 삭제, 누적 방지). try: diff --git a/backend/router/v1/auth/account.py b/backend/router/v1/auth/account.py index df3de34..623924c 100644 --- a/backend/router/v1/auth/account.py +++ b/backend/router/v1/auth/account.py @@ -1,9 +1,15 @@ from fastapi import APIRouter, Depends, Request +from fastapi.security import HTTPAuthorizationCredentials from common.models.gmodel import UserInfo -from router.v1.validator.dependencies import IsValidAccessToken, IsValidRefreshToken, RemoveNoneResponse +from router.v1.validator.dependencies import ( + IsValidAccessToken, + IsValidRefreshToken, + RemoveNoneResponse, + security, +) from services.auth_service import AuthService -from .protocol import Req_CreateAccount, Req_Login, Res_CreateAccount, Res_Login, Res_Me, Res_RefreshToken +from .protocol import Req_CreateAccount, Req_Login, Res_CreateAccount, Res_Login, Res_Logout, Res_Me, Res_RefreshToken # 라우터(MVC 의 컨트롤러). 요청 검증 -> service 호출 -> RemoveNoneResponse 반환만 담당. router = APIRouter(prefix="/v1/auth", tags=["Auth"], responses={404: {"description": "Not found"}}) @@ -28,17 +34,35 @@ async def create_account(request: Request, req: Req_CreateAccount, service: Auth path="/refresh_token", response_model=Res_RefreshToken, summary="액세스 토큰 갱신", - description="refresh 토큰으로 access 토큰을 재발급한다. su_id DB 존재/활성은 service 에서 확인한다.", + description="refresh 토큰으로 access 토큰을 재발급한다. su_id DB 존재/활성 + 저장 토큰 대조를 service 에서 확인한다.", ) -async def refresh_token(user_info: UserInfo = Depends(IsValidRefreshToken), service: AuthService = Depends()): - return RemoveNoneResponse(await service.refresh_token(user_info)) +async def refresh_token( + user_info: UserInfo = Depends(IsValidRefreshToken), + credentials: HTTPAuthorizationCredentials = Depends(security), + service: AuthService = Depends(), +): + return RemoveNoneResponse(await service.refresh_token(user_info, credentials.credentials)) + + +@router.post( + path="/logout", + response_model=Res_Logout, + summary="로그아웃", + description="저장된 access/refresh 토큰을 폐기한다. 이후 보호 요청·재발급이 차단된다(단일 세션).", +) +async def logout(user_info: UserInfo = Depends(IsValidAccessToken), service: AuthService = Depends()): + return RemoveNoneResponse(await service.logout(user_info)) @router.get( path="/me", response_model=Res_Me, summary="내 정보 (보호된 엔드포인트)", - description="access 토큰 검증(validator) 후 su_id DB 존재/활성을 service 에서 확인해 반환한다.", + description="access 토큰 검증(validator) 후 su_id DB 존재/활성 + 저장 토큰 대조를 service 에서 확인해 반환한다.", ) -async def me(user_info: UserInfo = Depends(IsValidAccessToken), service: AuthService = Depends()): - return RemoveNoneResponse(await service.get_me(user_info)) +async def me( + user_info: UserInfo = Depends(IsValidAccessToken), + credentials: HTTPAuthorizationCredentials = Depends(security), + service: AuthService = Depends(), +): + return RemoveNoneResponse(await service.get_me(user_info, credentials.credentials)) diff --git a/backend/router/v1/auth/protocol.py b/backend/router/v1/auth/protocol.py index c3cda59..bd21a32 100644 --- a/backend/router/v1/auth/protocol.py +++ b/backend/router/v1/auth/protocol.py @@ -46,3 +46,7 @@ class Res_Me(Res_WebPacketProtocol): supplier_id: str = "" supplier_name: str = "" role: int = 0 + + +class Res_Logout(Res_WebPacketProtocol): + pass diff --git a/backend/services/auth_service.py b/backend/services/auth_service.py index e91c48c..eb4f73f 100644 --- a/backend/services/auth_service.py +++ b/backend/services/auth_service.py @@ -10,7 +10,7 @@ from common.models.gmodel import UserInfo from common.utils.gtime import GTime from config.server_configs import jwt_token_config from crud.user_crud import IUserCRUD, UserCRUD -from router.v1.auth.protocol import Res_CreateAccount, Res_Login, Res_Me, Res_RefreshToken +from router.v1.auth.protocol import Res_CreateAccount, Res_Login, Res_Logout, Res_Me, Res_RefreshToken from router.v1.validator.dependencies import CreateAccessToken, CreateRefreshToken, GetHashedPW, VerifyPW @@ -207,13 +207,27 @@ class AuthService: role=account.role, ) - async def get_me(self, user_info: UserInfo) -> Res_Me: - # 토큰 디코드는 라우터 Depends(IsValidAccessToken) 에서 수행됨. 여기선 su_id DB 검증. + async def __verify_stored_token(self, su_id_str: str, token_type: int, presented: str) -> bool: + """제시된 토큰이 저장된 토큰과 일치하는지 확인한다(stateful 단일 세션). + 로그아웃·타기기 로그인으로 교체되면 저장 토큰이 없거나 달라져 False 가 된다. + """ + err_type, stored = await DB_SESSION_MNG.execute_lambda( + supplier_users.DBType(), + DBWRType.DB_READ.value, + lambda s: self.user_crud.get_token(s, uuid.UUID(su_id_str), token_type), + ) + return err_type == ErrorType.SUCCESS and stored == presented + + async def get_me(self, user_info: UserInfo, access_token: str) -> Res_Me: + # 토큰 디코드는 라우터 Depends(IsValidAccessToken) 에서 수행됨. 여기선 su_id DB 검증 + 저장 토큰 대조. res = Res_Me() err_type, info = await self.__load_active_account(user_info.su_id) if err_type != ErrorType.SUCCESS: res.result.SetResult(err_type) return res + if not await self.__verify_stored_token(info.su_id, TokenType.ACCESS.value, access_token): + res.result.SetResult(ErrorType.TOKEN_REVOKED) # 로그아웃/타기기 로그인으로 무효화됨 + return res res.su_id = info.su_id res.id = info.id res.name = info.name @@ -222,13 +236,27 @@ class AuthService: res.role = info.role return res - async def refresh_token(self, user_info: UserInfo) -> Res_RefreshToken: - # 토큰 디코드는 라우터 Depends(IsValidRefreshToken) 에서 수행됨. 여기선 su_id DB 검증 후 재발급. + async def logout(self, user_info: UserInfo) -> Res_Logout: + # 해당 유저의 저장 토큰(access/refresh)을 모두 삭제 → 이후 보호 요청·재발급이 차단된다. + res = Res_Logout() + err_type = await DB_SESSION_MNG.execute_lambda_run( + [supplier_users.DBType()], + [lambda s: self.user_crud.delete_tokens_by_su_id(s, uuid.UUID(user_info.su_id))], + ) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + async def refresh_token(self, user_info: UserInfo, refresh_token: str) -> Res_RefreshToken: + # 토큰 디코드는 라우터 Depends(IsValidRefreshToken) 에서 수행됨. 여기선 su_id DB 검증 + 저장 토큰 대조 후 재발급. res = Res_RefreshToken() err_type, info = await self.__load_active_account(user_info.su_id) if err_type != ErrorType.SUCCESS: res.result.SetResult(err_type) return res + if not await self.__verify_stored_token(info.su_id, TokenType.REFRESH.value, refresh_token): + res.result.SetResult(ErrorType.TOKEN_REVOKED) # 로그아웃/타기기 로그인으로 무효화됨 + return res new_access = CreateAccessToken(info) # DB 최신값으로 재구성한 토큰 # 단일 세션: 저장된 access 행을 새 토큰으로 갱신한다(refresh 행은 유지). diff --git a/backend/tests/test_auth.py b/backend/tests/test_auth.py index c59f866..275ba7c 100644 --- a/backend/tests/test_auth.py +++ b/backend/tests/test_auth.py @@ -270,3 +270,55 @@ async def test_refresh_inactive_after_token(client, account_seed, db_engine): assert body["result"]["success"] is False assert body["result"]["code"] == 1202 assert body.get("access_token", "") == "" + + +# ---- 로그아웃 / stateful 토큰 검증 ------------------------------------------- +async def test_logout_revokes_tokens(client, account_seed, db_engine): + body = (await _login(client)).json() + su_id, access, refresh = body["su_id"], body["access_token"], body["refresh_token"] + + # 로그아웃 성공 + r = await client.post("/v1/auth/logout", headers={"Authorization": f"Bearer {access}"}) + assert r.status_code == 200 + assert r.json()["result"]["success"] is True + + # 저장 토큰이 모두 삭제됨 + async with db_engine.begin() as conn: + count = ( + await conn.execute( + text("SELECT count(*) FROM supplier.supplier_user_tokens WHERE su_id = :sid AND deleted = false"), + {"sid": uuid.UUID(su_id)}, + ) + ).scalar() + assert count == 0 + + # 로그아웃 후 같은 access 로 /me → TOKEN_REVOKED(1203) + r2 = await client.get("/v1/auth/me", headers={"Authorization": f"Bearer {access}"}) + assert r2.status_code == 200 + assert r2.json()["result"]["code"] == 1203 + + # 로그아웃 후 같은 refresh 로 재발급 → TOKEN_REVOKED(1203) + r3 = await client.post("/v1/auth/refresh_token", headers={"Authorization": f"Bearer {refresh}"}) + assert r3.json()["result"]["code"] == 1203 + + +async def test_logout_without_token(client): + r = await client.post("/v1/auth/logout") + assert r.status_code in (401, 403) + + +async def test_relogin_invalidates_previous_access(client, account_seed): + # 단일 세션: 재로그인하면 이전 세션의 access 가 무효화된다(저장 토큰이 교체됨). + import asyncio + + first = (await _login(client)).json() + await asyncio.sleep(1.1) # exp(초 단위)가 달라져 토큰이 실제로 바뀌도록 + second = (await _login(client)).json() + assert first["access_token"] != second["access_token"] + + # 이전 access → 무효(TOKEN_REVOKED) + r_old = await client.get("/v1/auth/me", headers={"Authorization": f"Bearer {first['access_token']}"}) + assert r_old.json()["result"]["code"] == 1203 + # 새 access → 정상 + r_new = await client.get("/v1/auth/me", headers={"Authorization": f"Bearer {second['access_token']}"}) + assert r_new.json()["result"]["success"] is True From 16848e9f637dae23e45fb8f7d3045fe651ec16d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=AF=BC=ED=97=8C?= Date: Thu, 18 Jun 2026 11:30:26 +0900 Subject: [PATCH 05/14] =?UTF-8?q?update(front):=20front=20=ED=8F=B4?= =?UTF-8?q?=EB=8D=94=EB=AA=85=20frontend=EB=A1=9C=20=EB=B3=80=EA=B2=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- {front => frontend}/.env.sample | 0 {front => frontend}/.gitignore | 0 {front => frontend}/README.md | 0 {front => frontend}/eslint.config.js | 0 {front => frontend}/index.html | 0 {front => frontend}/package-lock.json | 0 {front => frontend}/package.json | 0 {front => frontend}/public/favicon.svg | 0 {front => frontend}/public/icons.svg | 0 {front => frontend}/src/App.tsx | 0 .../src/assets/imarketkorea-logo-white.png | Bin .../src/assets/imarketkorea-logo.png | Bin {front => frontend}/src/components/Button.tsx | 0 {front => frontend}/src/components/Input.tsx | 0 {front => frontend}/src/components/Logo.tsx | 0 {front => frontend}/src/components/index.ts | 0 {front => frontend}/src/core/provider.tsx | 0 .../src/features/auth/components/LoginForm.tsx | 0 .../src/features/auth/components/SidebarFooter.tsx | 0 .../src/features/auth/hooks/useLogin.ts | 0 .../src/features/auth/hooks/useLoginMutation.ts | 0 {front => frontend}/src/features/auth/index.ts | 0 .../src/features/chat/components/ChatMessage.tsx | 0 .../src/features/chat/components/ChatSection.tsx | 0 .../src/features/chat/components/ItemImage.tsx | 0 .../src/features/chat/components/ItemSection.tsx | 0 .../src/features/chat/components/RemainingTime.tsx | 0 .../src/features/chat/components/UserButton.tsx | 0 .../src/features/chat/components/menu/Contact.tsx | 0 .../src/features/chat/components/menu/Guide.tsx | 0 .../features/chat/components/menu/MDInformation.tsx | 0 .../features/chat/components/menu/MenuSection.tsx | 0 .../src/features/chat/components/menu/NegoStep.tsx | 0 .../chat/components/templates/BidSummary.tsx | 0 .../chat/components/templates/Indicator.tsx | 0 .../chat/components/templates/OtherReason.tsx | 0 .../features/chat/components/templates/RejectCM.tsx | 0 .../chat/components/templates/RejectRSP.tsx | 0 .../features/chat/components/templates/Summary.tsx | 0 .../chat/components/templates/rejectControls.tsx | 0 .../src/features/chat/components/userInputs.tsx | 0 .../src/features/chat/containers/ChatContainer.tsx | 0 .../src/features/chat/hooks/useChatInit.ts | 0 {front => frontend}/src/features/chat/index.ts | 0 .../src/features/chat/lib/koreanNumber.ts | 0 .../src/features/chat/lib/rejectForm.ts | 0 .../src/features/chat/lib/remainingTime.ts | 0 .../src/features/chat/lib/userButtonConfig.ts | 0 .../src/features/chat/mocks/mockChatInit.ts | 0 .../src/features/chat/mocks/mockMessages.ts | 0 .../src/features/chat/stores/useChatInitStore.ts | 0 .../src/features/chat/stores/useChatStore.ts | 0 {front => frontend}/src/features/chat/types.ts | 0 .../src/features/list/components/ActionSection.tsx | 0 .../src/features/list/components/FilterGroup.tsx | 0 .../src/features/list/components/Pagination.tsx | 0 .../src/features/list/components/TableSection.tsx | 0 .../features/list/components/paginationIcons.tsx | 0 .../src/features/list/components/tableColumns.tsx | 0 .../features/list/containers/ContentContainer.tsx | 0 .../features/list/containers/FilterContainer.tsx | 0 .../src/features/list/filterOptions.ts | 0 .../src/features/list/hooks/useList.ts | 0 {front => frontend}/src/features/list/index.ts | 0 .../src/features/list/lib/datetime.ts | 0 .../src/features/list/lib/pagination.ts | 0 .../src/features/list/mocks/mockItems.ts | 0 .../src/features/list/stores/useListStore.ts | 0 {front => frontend}/src/features/list/types.ts | 0 {front => frontend}/src/index.css | 0 {front => frontend}/src/layouts/MainHeaderBar.tsx | 0 {front => frontend}/src/layouts/MainLayout.tsx | 0 {front => frontend}/src/layouts/index.ts | 0 {front => frontend}/src/lib/cn.ts | 0 {front => frontend}/src/lib/index.ts | 0 {front => frontend}/src/lib/interactive.ts | 0 {front => frontend}/src/main.tsx | 0 {front => frontend}/src/pages/ChatPage.tsx | 0 {front => frontend}/src/pages/ListPage.tsx | 0 {front => frontend}/src/pages/LoginPage.tsx | 0 {front => frontend}/src/vite-env.d.ts | 0 {front => frontend}/tsconfig.app.json | 0 {front => frontend}/tsconfig.json | 0 {front => frontend}/tsconfig.node.json | 0 {front => frontend}/vite.config.ts | 0 85 files changed, 0 insertions(+), 0 deletions(-) rename {front => frontend}/.env.sample (100%) rename {front => frontend}/.gitignore (100%) rename {front => frontend}/README.md (100%) rename {front => frontend}/eslint.config.js (100%) rename {front => frontend}/index.html (100%) rename {front => frontend}/package-lock.json (100%) rename {front => frontend}/package.json (100%) rename {front => frontend}/public/favicon.svg (100%) rename {front => frontend}/public/icons.svg (100%) rename {front => frontend}/src/App.tsx (100%) rename {front => frontend}/src/assets/imarketkorea-logo-white.png (100%) rename {front => frontend}/src/assets/imarketkorea-logo.png (100%) rename {front => frontend}/src/components/Button.tsx (100%) rename {front => frontend}/src/components/Input.tsx (100%) rename {front => frontend}/src/components/Logo.tsx (100%) rename {front => frontend}/src/components/index.ts (100%) rename {front => frontend}/src/core/provider.tsx (100%) rename {front => frontend}/src/features/auth/components/LoginForm.tsx (100%) rename {front => frontend}/src/features/auth/components/SidebarFooter.tsx (100%) rename {front => frontend}/src/features/auth/hooks/useLogin.ts (100%) rename {front => frontend}/src/features/auth/hooks/useLoginMutation.ts (100%) rename {front => frontend}/src/features/auth/index.ts (100%) rename {front => frontend}/src/features/chat/components/ChatMessage.tsx (100%) rename {front => frontend}/src/features/chat/components/ChatSection.tsx (100%) rename {front => frontend}/src/features/chat/components/ItemImage.tsx (100%) rename {front => frontend}/src/features/chat/components/ItemSection.tsx (100%) rename {front => frontend}/src/features/chat/components/RemainingTime.tsx (100%) rename {front => frontend}/src/features/chat/components/UserButton.tsx (100%) rename {front => frontend}/src/features/chat/components/menu/Contact.tsx (100%) rename {front => frontend}/src/features/chat/components/menu/Guide.tsx (100%) rename {front => frontend}/src/features/chat/components/menu/MDInformation.tsx (100%) rename {front => frontend}/src/features/chat/components/menu/MenuSection.tsx (100%) rename {front => frontend}/src/features/chat/components/menu/NegoStep.tsx (100%) rename {front => frontend}/src/features/chat/components/templates/BidSummary.tsx (100%) rename {front => frontend}/src/features/chat/components/templates/Indicator.tsx (100%) rename {front => frontend}/src/features/chat/components/templates/OtherReason.tsx (100%) rename {front => frontend}/src/features/chat/components/templates/RejectCM.tsx (100%) rename {front => frontend}/src/features/chat/components/templates/RejectRSP.tsx (100%) rename {front => frontend}/src/features/chat/components/templates/Summary.tsx (100%) rename {front => frontend}/src/features/chat/components/templates/rejectControls.tsx (100%) rename {front => frontend}/src/features/chat/components/userInputs.tsx (100%) rename {front => frontend}/src/features/chat/containers/ChatContainer.tsx (100%) rename {front => frontend}/src/features/chat/hooks/useChatInit.ts (100%) rename {front => frontend}/src/features/chat/index.ts (100%) rename {front => frontend}/src/features/chat/lib/koreanNumber.ts (100%) rename {front => frontend}/src/features/chat/lib/rejectForm.ts (100%) rename {front => frontend}/src/features/chat/lib/remainingTime.ts (100%) rename {front => frontend}/src/features/chat/lib/userButtonConfig.ts (100%) rename {front => frontend}/src/features/chat/mocks/mockChatInit.ts (100%) rename {front => frontend}/src/features/chat/mocks/mockMessages.ts (100%) rename {front => frontend}/src/features/chat/stores/useChatInitStore.ts (100%) rename {front => frontend}/src/features/chat/stores/useChatStore.ts (100%) rename {front => frontend}/src/features/chat/types.ts (100%) rename {front => frontend}/src/features/list/components/ActionSection.tsx (100%) rename {front => frontend}/src/features/list/components/FilterGroup.tsx (100%) rename {front => frontend}/src/features/list/components/Pagination.tsx (100%) rename {front => frontend}/src/features/list/components/TableSection.tsx (100%) rename {front => frontend}/src/features/list/components/paginationIcons.tsx (100%) rename {front => frontend}/src/features/list/components/tableColumns.tsx (100%) rename {front => frontend}/src/features/list/containers/ContentContainer.tsx (100%) rename {front => frontend}/src/features/list/containers/FilterContainer.tsx (100%) rename {front => frontend}/src/features/list/filterOptions.ts (100%) rename {front => frontend}/src/features/list/hooks/useList.ts (100%) rename {front => frontend}/src/features/list/index.ts (100%) rename {front => frontend}/src/features/list/lib/datetime.ts (100%) rename {front => frontend}/src/features/list/lib/pagination.ts (100%) rename {front => frontend}/src/features/list/mocks/mockItems.ts (100%) rename {front => frontend}/src/features/list/stores/useListStore.ts (100%) rename {front => frontend}/src/features/list/types.ts (100%) rename {front => frontend}/src/index.css (100%) rename {front => frontend}/src/layouts/MainHeaderBar.tsx (100%) rename {front => frontend}/src/layouts/MainLayout.tsx (100%) rename {front => frontend}/src/layouts/index.ts (100%) rename {front => frontend}/src/lib/cn.ts (100%) rename {front => frontend}/src/lib/index.ts (100%) rename {front => frontend}/src/lib/interactive.ts (100%) rename {front => frontend}/src/main.tsx (100%) rename {front => frontend}/src/pages/ChatPage.tsx (100%) rename {front => frontend}/src/pages/ListPage.tsx (100%) rename {front => frontend}/src/pages/LoginPage.tsx (100%) rename {front => frontend}/src/vite-env.d.ts (100%) rename {front => frontend}/tsconfig.app.json (100%) rename {front => frontend}/tsconfig.json (100%) rename {front => frontend}/tsconfig.node.json (100%) rename {front => frontend}/vite.config.ts (100%) diff --git a/front/.env.sample b/frontend/.env.sample similarity index 100% rename from front/.env.sample rename to frontend/.env.sample diff --git a/front/.gitignore b/frontend/.gitignore similarity index 100% rename from front/.gitignore rename to frontend/.gitignore diff --git a/front/README.md b/frontend/README.md similarity index 100% rename from front/README.md rename to frontend/README.md diff --git a/front/eslint.config.js b/frontend/eslint.config.js similarity index 100% rename from front/eslint.config.js rename to frontend/eslint.config.js diff --git a/front/index.html b/frontend/index.html similarity index 100% rename from front/index.html rename to frontend/index.html diff --git a/front/package-lock.json b/frontend/package-lock.json similarity index 100% rename from front/package-lock.json rename to frontend/package-lock.json diff --git a/front/package.json b/frontend/package.json similarity index 100% rename from front/package.json rename to frontend/package.json diff --git a/front/public/favicon.svg b/frontend/public/favicon.svg similarity index 100% rename from front/public/favicon.svg rename to frontend/public/favicon.svg diff --git a/front/public/icons.svg b/frontend/public/icons.svg similarity index 100% rename from front/public/icons.svg rename to frontend/public/icons.svg diff --git a/front/src/App.tsx b/frontend/src/App.tsx similarity index 100% rename from front/src/App.tsx rename to frontend/src/App.tsx diff --git a/front/src/assets/imarketkorea-logo-white.png b/frontend/src/assets/imarketkorea-logo-white.png similarity index 100% rename from front/src/assets/imarketkorea-logo-white.png rename to frontend/src/assets/imarketkorea-logo-white.png diff --git a/front/src/assets/imarketkorea-logo.png b/frontend/src/assets/imarketkorea-logo.png similarity index 100% rename from front/src/assets/imarketkorea-logo.png rename to frontend/src/assets/imarketkorea-logo.png diff --git a/front/src/components/Button.tsx b/frontend/src/components/Button.tsx similarity index 100% rename from front/src/components/Button.tsx rename to frontend/src/components/Button.tsx diff --git a/front/src/components/Input.tsx b/frontend/src/components/Input.tsx similarity index 100% rename from front/src/components/Input.tsx rename to frontend/src/components/Input.tsx diff --git a/front/src/components/Logo.tsx b/frontend/src/components/Logo.tsx similarity index 100% rename from front/src/components/Logo.tsx rename to frontend/src/components/Logo.tsx diff --git a/front/src/components/index.ts b/frontend/src/components/index.ts similarity index 100% rename from front/src/components/index.ts rename to frontend/src/components/index.ts diff --git a/front/src/core/provider.tsx b/frontend/src/core/provider.tsx similarity index 100% rename from front/src/core/provider.tsx rename to frontend/src/core/provider.tsx diff --git a/front/src/features/auth/components/LoginForm.tsx b/frontend/src/features/auth/components/LoginForm.tsx similarity index 100% rename from front/src/features/auth/components/LoginForm.tsx rename to frontend/src/features/auth/components/LoginForm.tsx diff --git a/front/src/features/auth/components/SidebarFooter.tsx b/frontend/src/features/auth/components/SidebarFooter.tsx similarity index 100% rename from front/src/features/auth/components/SidebarFooter.tsx rename to frontend/src/features/auth/components/SidebarFooter.tsx diff --git a/front/src/features/auth/hooks/useLogin.ts b/frontend/src/features/auth/hooks/useLogin.ts similarity index 100% rename from front/src/features/auth/hooks/useLogin.ts rename to frontend/src/features/auth/hooks/useLogin.ts diff --git a/front/src/features/auth/hooks/useLoginMutation.ts b/frontend/src/features/auth/hooks/useLoginMutation.ts similarity index 100% rename from front/src/features/auth/hooks/useLoginMutation.ts rename to frontend/src/features/auth/hooks/useLoginMutation.ts diff --git a/front/src/features/auth/index.ts b/frontend/src/features/auth/index.ts similarity index 100% rename from front/src/features/auth/index.ts rename to frontend/src/features/auth/index.ts diff --git a/front/src/features/chat/components/ChatMessage.tsx b/frontend/src/features/chat/components/ChatMessage.tsx similarity index 100% rename from front/src/features/chat/components/ChatMessage.tsx rename to frontend/src/features/chat/components/ChatMessage.tsx diff --git a/front/src/features/chat/components/ChatSection.tsx b/frontend/src/features/chat/components/ChatSection.tsx similarity index 100% rename from front/src/features/chat/components/ChatSection.tsx rename to frontend/src/features/chat/components/ChatSection.tsx diff --git a/front/src/features/chat/components/ItemImage.tsx b/frontend/src/features/chat/components/ItemImage.tsx similarity index 100% rename from front/src/features/chat/components/ItemImage.tsx rename to frontend/src/features/chat/components/ItemImage.tsx diff --git a/front/src/features/chat/components/ItemSection.tsx b/frontend/src/features/chat/components/ItemSection.tsx similarity index 100% rename from front/src/features/chat/components/ItemSection.tsx rename to frontend/src/features/chat/components/ItemSection.tsx diff --git a/front/src/features/chat/components/RemainingTime.tsx b/frontend/src/features/chat/components/RemainingTime.tsx similarity index 100% rename from front/src/features/chat/components/RemainingTime.tsx rename to frontend/src/features/chat/components/RemainingTime.tsx diff --git a/front/src/features/chat/components/UserButton.tsx b/frontend/src/features/chat/components/UserButton.tsx similarity index 100% rename from front/src/features/chat/components/UserButton.tsx rename to frontend/src/features/chat/components/UserButton.tsx diff --git a/front/src/features/chat/components/menu/Contact.tsx b/frontend/src/features/chat/components/menu/Contact.tsx similarity index 100% rename from front/src/features/chat/components/menu/Contact.tsx rename to frontend/src/features/chat/components/menu/Contact.tsx diff --git a/front/src/features/chat/components/menu/Guide.tsx b/frontend/src/features/chat/components/menu/Guide.tsx similarity index 100% rename from front/src/features/chat/components/menu/Guide.tsx rename to frontend/src/features/chat/components/menu/Guide.tsx diff --git a/front/src/features/chat/components/menu/MDInformation.tsx b/frontend/src/features/chat/components/menu/MDInformation.tsx similarity index 100% rename from front/src/features/chat/components/menu/MDInformation.tsx rename to frontend/src/features/chat/components/menu/MDInformation.tsx diff --git a/front/src/features/chat/components/menu/MenuSection.tsx b/frontend/src/features/chat/components/menu/MenuSection.tsx similarity index 100% rename from front/src/features/chat/components/menu/MenuSection.tsx rename to frontend/src/features/chat/components/menu/MenuSection.tsx diff --git a/front/src/features/chat/components/menu/NegoStep.tsx b/frontend/src/features/chat/components/menu/NegoStep.tsx similarity index 100% rename from front/src/features/chat/components/menu/NegoStep.tsx rename to frontend/src/features/chat/components/menu/NegoStep.tsx diff --git a/front/src/features/chat/components/templates/BidSummary.tsx b/frontend/src/features/chat/components/templates/BidSummary.tsx similarity index 100% rename from front/src/features/chat/components/templates/BidSummary.tsx rename to frontend/src/features/chat/components/templates/BidSummary.tsx diff --git a/front/src/features/chat/components/templates/Indicator.tsx b/frontend/src/features/chat/components/templates/Indicator.tsx similarity index 100% rename from front/src/features/chat/components/templates/Indicator.tsx rename to frontend/src/features/chat/components/templates/Indicator.tsx diff --git a/front/src/features/chat/components/templates/OtherReason.tsx b/frontend/src/features/chat/components/templates/OtherReason.tsx similarity index 100% rename from front/src/features/chat/components/templates/OtherReason.tsx rename to frontend/src/features/chat/components/templates/OtherReason.tsx diff --git a/front/src/features/chat/components/templates/RejectCM.tsx b/frontend/src/features/chat/components/templates/RejectCM.tsx similarity index 100% rename from front/src/features/chat/components/templates/RejectCM.tsx rename to frontend/src/features/chat/components/templates/RejectCM.tsx diff --git a/front/src/features/chat/components/templates/RejectRSP.tsx b/frontend/src/features/chat/components/templates/RejectRSP.tsx similarity index 100% rename from front/src/features/chat/components/templates/RejectRSP.tsx rename to frontend/src/features/chat/components/templates/RejectRSP.tsx diff --git a/front/src/features/chat/components/templates/Summary.tsx b/frontend/src/features/chat/components/templates/Summary.tsx similarity index 100% rename from front/src/features/chat/components/templates/Summary.tsx rename to frontend/src/features/chat/components/templates/Summary.tsx diff --git a/front/src/features/chat/components/templates/rejectControls.tsx b/frontend/src/features/chat/components/templates/rejectControls.tsx similarity index 100% rename from front/src/features/chat/components/templates/rejectControls.tsx rename to frontend/src/features/chat/components/templates/rejectControls.tsx diff --git a/front/src/features/chat/components/userInputs.tsx b/frontend/src/features/chat/components/userInputs.tsx similarity index 100% rename from front/src/features/chat/components/userInputs.tsx rename to frontend/src/features/chat/components/userInputs.tsx diff --git a/front/src/features/chat/containers/ChatContainer.tsx b/frontend/src/features/chat/containers/ChatContainer.tsx similarity index 100% rename from front/src/features/chat/containers/ChatContainer.tsx rename to frontend/src/features/chat/containers/ChatContainer.tsx diff --git a/front/src/features/chat/hooks/useChatInit.ts b/frontend/src/features/chat/hooks/useChatInit.ts similarity index 100% rename from front/src/features/chat/hooks/useChatInit.ts rename to frontend/src/features/chat/hooks/useChatInit.ts diff --git a/front/src/features/chat/index.ts b/frontend/src/features/chat/index.ts similarity index 100% rename from front/src/features/chat/index.ts rename to frontend/src/features/chat/index.ts diff --git a/front/src/features/chat/lib/koreanNumber.ts b/frontend/src/features/chat/lib/koreanNumber.ts similarity index 100% rename from front/src/features/chat/lib/koreanNumber.ts rename to frontend/src/features/chat/lib/koreanNumber.ts diff --git a/front/src/features/chat/lib/rejectForm.ts b/frontend/src/features/chat/lib/rejectForm.ts similarity index 100% rename from front/src/features/chat/lib/rejectForm.ts rename to frontend/src/features/chat/lib/rejectForm.ts diff --git a/front/src/features/chat/lib/remainingTime.ts b/frontend/src/features/chat/lib/remainingTime.ts similarity index 100% rename from front/src/features/chat/lib/remainingTime.ts rename to frontend/src/features/chat/lib/remainingTime.ts diff --git a/front/src/features/chat/lib/userButtonConfig.ts b/frontend/src/features/chat/lib/userButtonConfig.ts similarity index 100% rename from front/src/features/chat/lib/userButtonConfig.ts rename to frontend/src/features/chat/lib/userButtonConfig.ts diff --git a/front/src/features/chat/mocks/mockChatInit.ts b/frontend/src/features/chat/mocks/mockChatInit.ts similarity index 100% rename from front/src/features/chat/mocks/mockChatInit.ts rename to frontend/src/features/chat/mocks/mockChatInit.ts diff --git a/front/src/features/chat/mocks/mockMessages.ts b/frontend/src/features/chat/mocks/mockMessages.ts similarity index 100% rename from front/src/features/chat/mocks/mockMessages.ts rename to frontend/src/features/chat/mocks/mockMessages.ts diff --git a/front/src/features/chat/stores/useChatInitStore.ts b/frontend/src/features/chat/stores/useChatInitStore.ts similarity index 100% rename from front/src/features/chat/stores/useChatInitStore.ts rename to frontend/src/features/chat/stores/useChatInitStore.ts diff --git a/front/src/features/chat/stores/useChatStore.ts b/frontend/src/features/chat/stores/useChatStore.ts similarity index 100% rename from front/src/features/chat/stores/useChatStore.ts rename to frontend/src/features/chat/stores/useChatStore.ts diff --git a/front/src/features/chat/types.ts b/frontend/src/features/chat/types.ts similarity index 100% rename from front/src/features/chat/types.ts rename to frontend/src/features/chat/types.ts diff --git a/front/src/features/list/components/ActionSection.tsx b/frontend/src/features/list/components/ActionSection.tsx similarity index 100% rename from front/src/features/list/components/ActionSection.tsx rename to frontend/src/features/list/components/ActionSection.tsx diff --git a/front/src/features/list/components/FilterGroup.tsx b/frontend/src/features/list/components/FilterGroup.tsx similarity index 100% rename from front/src/features/list/components/FilterGroup.tsx rename to frontend/src/features/list/components/FilterGroup.tsx diff --git a/front/src/features/list/components/Pagination.tsx b/frontend/src/features/list/components/Pagination.tsx similarity index 100% rename from front/src/features/list/components/Pagination.tsx rename to frontend/src/features/list/components/Pagination.tsx diff --git a/front/src/features/list/components/TableSection.tsx b/frontend/src/features/list/components/TableSection.tsx similarity index 100% rename from front/src/features/list/components/TableSection.tsx rename to frontend/src/features/list/components/TableSection.tsx diff --git a/front/src/features/list/components/paginationIcons.tsx b/frontend/src/features/list/components/paginationIcons.tsx similarity index 100% rename from front/src/features/list/components/paginationIcons.tsx rename to frontend/src/features/list/components/paginationIcons.tsx diff --git a/front/src/features/list/components/tableColumns.tsx b/frontend/src/features/list/components/tableColumns.tsx similarity index 100% rename from front/src/features/list/components/tableColumns.tsx rename to frontend/src/features/list/components/tableColumns.tsx diff --git a/front/src/features/list/containers/ContentContainer.tsx b/frontend/src/features/list/containers/ContentContainer.tsx similarity index 100% rename from front/src/features/list/containers/ContentContainer.tsx rename to frontend/src/features/list/containers/ContentContainer.tsx diff --git a/front/src/features/list/containers/FilterContainer.tsx b/frontend/src/features/list/containers/FilterContainer.tsx similarity index 100% rename from front/src/features/list/containers/FilterContainer.tsx rename to frontend/src/features/list/containers/FilterContainer.tsx diff --git a/front/src/features/list/filterOptions.ts b/frontend/src/features/list/filterOptions.ts similarity index 100% rename from front/src/features/list/filterOptions.ts rename to frontend/src/features/list/filterOptions.ts diff --git a/front/src/features/list/hooks/useList.ts b/frontend/src/features/list/hooks/useList.ts similarity index 100% rename from front/src/features/list/hooks/useList.ts rename to frontend/src/features/list/hooks/useList.ts diff --git a/front/src/features/list/index.ts b/frontend/src/features/list/index.ts similarity index 100% rename from front/src/features/list/index.ts rename to frontend/src/features/list/index.ts diff --git a/front/src/features/list/lib/datetime.ts b/frontend/src/features/list/lib/datetime.ts similarity index 100% rename from front/src/features/list/lib/datetime.ts rename to frontend/src/features/list/lib/datetime.ts diff --git a/front/src/features/list/lib/pagination.ts b/frontend/src/features/list/lib/pagination.ts similarity index 100% rename from front/src/features/list/lib/pagination.ts rename to frontend/src/features/list/lib/pagination.ts diff --git a/front/src/features/list/mocks/mockItems.ts b/frontend/src/features/list/mocks/mockItems.ts similarity index 100% rename from front/src/features/list/mocks/mockItems.ts rename to frontend/src/features/list/mocks/mockItems.ts diff --git a/front/src/features/list/stores/useListStore.ts b/frontend/src/features/list/stores/useListStore.ts similarity index 100% rename from front/src/features/list/stores/useListStore.ts rename to frontend/src/features/list/stores/useListStore.ts diff --git a/front/src/features/list/types.ts b/frontend/src/features/list/types.ts similarity index 100% rename from front/src/features/list/types.ts rename to frontend/src/features/list/types.ts diff --git a/front/src/index.css b/frontend/src/index.css similarity index 100% rename from front/src/index.css rename to frontend/src/index.css diff --git a/front/src/layouts/MainHeaderBar.tsx b/frontend/src/layouts/MainHeaderBar.tsx similarity index 100% rename from front/src/layouts/MainHeaderBar.tsx rename to frontend/src/layouts/MainHeaderBar.tsx diff --git a/front/src/layouts/MainLayout.tsx b/frontend/src/layouts/MainLayout.tsx similarity index 100% rename from front/src/layouts/MainLayout.tsx rename to frontend/src/layouts/MainLayout.tsx diff --git a/front/src/layouts/index.ts b/frontend/src/layouts/index.ts similarity index 100% rename from front/src/layouts/index.ts rename to frontend/src/layouts/index.ts diff --git a/front/src/lib/cn.ts b/frontend/src/lib/cn.ts similarity index 100% rename from front/src/lib/cn.ts rename to frontend/src/lib/cn.ts diff --git a/front/src/lib/index.ts b/frontend/src/lib/index.ts similarity index 100% rename from front/src/lib/index.ts rename to frontend/src/lib/index.ts diff --git a/front/src/lib/interactive.ts b/frontend/src/lib/interactive.ts similarity index 100% rename from front/src/lib/interactive.ts rename to frontend/src/lib/interactive.ts diff --git a/front/src/main.tsx b/frontend/src/main.tsx similarity index 100% rename from front/src/main.tsx rename to frontend/src/main.tsx diff --git a/front/src/pages/ChatPage.tsx b/frontend/src/pages/ChatPage.tsx similarity index 100% rename from front/src/pages/ChatPage.tsx rename to frontend/src/pages/ChatPage.tsx diff --git a/front/src/pages/ListPage.tsx b/frontend/src/pages/ListPage.tsx similarity index 100% rename from front/src/pages/ListPage.tsx rename to frontend/src/pages/ListPage.tsx diff --git a/front/src/pages/LoginPage.tsx b/frontend/src/pages/LoginPage.tsx similarity index 100% rename from front/src/pages/LoginPage.tsx rename to frontend/src/pages/LoginPage.tsx diff --git a/front/src/vite-env.d.ts b/frontend/src/vite-env.d.ts similarity index 100% rename from front/src/vite-env.d.ts rename to frontend/src/vite-env.d.ts diff --git a/front/tsconfig.app.json b/frontend/tsconfig.app.json similarity index 100% rename from front/tsconfig.app.json rename to frontend/tsconfig.app.json diff --git a/front/tsconfig.json b/frontend/tsconfig.json similarity index 100% rename from front/tsconfig.json rename to frontend/tsconfig.json diff --git a/front/tsconfig.node.json b/frontend/tsconfig.node.json similarity index 100% rename from front/tsconfig.node.json rename to frontend/tsconfig.node.json diff --git a/front/vite.config.ts b/frontend/vite.config.ts similarity index 100% rename from front/vite.config.ts rename to frontend/vite.config.ts From 2480a47efe536815ee783e5ba6af9755713bf6b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=AF=BC=ED=97=8C?= Date: Thu, 18 Jun 2026 12:32:32 +0900 Subject: [PATCH 06/14] =?UTF-8?q?feat(backend):=20=ED=98=91=EC=83=81=20?= =?UTF-8?q?=EC=84=B8=EC=85=98=20=EB=AA=A9=EB=A1=9D=20+=20=EC=B0=B8?= =?UTF-8?q?=EC=97=AC=20=EA=B8=B0=EB=8A=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - GET /v1/negotiation/sessions: 로그인 공급사의 세션 목록(필터/정렬/페이지네이션) · qt_end_time 은 견적(quotation.end_time) 기준, sessions⨝items⨝quotations 조인 · status/qt_type 은 정수 코드로 응답(라벨 매핑은 프론트) - POST /v1/negotiation/sessions/{session_id}/participate: 협상 참여 · 검증: 소유(공급사 대조)→세션상태→견적마감→마감시간, 에러코드 1300~1304 · 협상생성→협상중, 견적→견적진행중 (협상중/완료는 무변경 진입) · 마감초과 시 협상생성 세션만 미참여로 정리 - DBType.NEGOTIATION/QUOTATION, items/sessions/quotations 모델 - QtType/SessionStatus/QuotationStatus enum, AuthService.authenticate 공통화 - 협상 e2e 테스트(test_negotiation.py) Co-Authored-By: Claude Opus 4.8 (1M context) --- backend/common/database/db_session_manager.py | 8 +- backend/common/database/model/models.py | 100 ++++++++- backend/common/enums.py | 42 +++- backend/crud/session_crud.py | 140 ++++++++++++ backend/router/router.py | 2 + backend/router/v1/negotiation/protocol.py | 25 +++ backend/router/v1/negotiation/session.py | 47 ++++ backend/services/auth_service.py | 20 +- backend/services/negotiation_service.py | 150 +++++++++++++ backend/tests/test_negotiation.py | 211 ++++++++++++++++++ 10 files changed, 735 insertions(+), 10 deletions(-) create mode 100644 backend/crud/session_crud.py create mode 100644 backend/router/v1/negotiation/protocol.py create mode 100644 backend/router/v1/negotiation/session.py create mode 100644 backend/services/negotiation_service.py create mode 100644 backend/tests/test_negotiation.py diff --git a/backend/common/database/db_session_manager.py b/backend/common/database/db_session_manager.py index b0c4a36..f6d81ef 100644 --- a/backend/common/database/db_session_manager.py +++ b/backend/common/database/db_session_manager.py @@ -34,21 +34,27 @@ class DBSessionManager(Singleton): # 종료 시 dispose 하기 위해 생성한 엔진을 모아둔다. self.__engines = [] # 논리 DB -> config. DB 가 늘어나면 여기에 추가만 하면 된다. - # USER/PARTNER 는 물리적으로 같은 negosium_db 라 main_db_config 를 재사용한다(도메인별 논리 구분용). + # USER/PARTNER/NEGOTIATION/QUOTATION 은 물리적으로 같은 negosium_db 라 main_db_config 를 재사용한다(도메인별 논리 구분용). self.__db_type_map = { DBType.USER.value: main_db_config, DBType.PARTNER.value: main_db_config, + DBType.NEGOTIATION.value: main_db_config, + DBType.QUOTATION.value: main_db_config, } # Write 엔진 맵 self.__write_session = { DBType.USER.value: self.create_engine(DBType.USER.value, DBWRType.DB_WRITE.value), DBType.PARTNER.value: self.create_engine(DBType.PARTNER.value, DBWRType.DB_WRITE.value), + DBType.NEGOTIATION.value: self.create_engine(DBType.NEGOTIATION.value, DBWRType.DB_WRITE.value), + DBType.QUOTATION.value: self.create_engine(DBType.QUOTATION.value, DBWRType.DB_WRITE.value), } # Read 엔진 맵 self.__read_session = { DBType.USER.value: self.create_engine(DBType.USER.value, DBWRType.DB_READ.value), DBType.PARTNER.value: self.create_engine(DBType.PARTNER.value, DBWRType.DB_READ.value), + DBType.NEGOTIATION.value: self.create_engine(DBType.NEGOTIATION.value, DBWRType.DB_READ.value), + DBType.QUOTATION.value: self.create_engine(DBType.QUOTATION.value, DBWRType.DB_READ.value), } def create_engine(self, db_type: int, db_wr_type: int): diff --git a/backend/common/database/model/models.py b/backend/common/database/model/models.py index edb1924..578cce7 100644 --- a/backend/common/database/model/models.py +++ b/backend/common/database/model/models.py @@ -1,5 +1,5 @@ from sqlalchemy.orm import declarative_base -from sqlalchemy import Column, Integer, String, Boolean, DateTime, SmallInteger +from sqlalchemy import Column, Integer, String, Boolean, DateTime, SmallInteger, BigInteger from sqlalchemy.dialects.postgresql import UUID, JSONB from sqlalchemy.sql import text @@ -57,6 +57,104 @@ class suppliers(MAIN_BASE): deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부 +class items(MAIN_BASE): + # partner.items (상품). + @staticmethod + def DBType(): + return DBType.PARTNER.value + + __tablename__ = "items" + __table_args__ = {"schema": "partner"} + + item_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")) # 상품 식별자(PK) + company_id = Column(UUID(as_uuid=True), nullable=False) # 소속 회사(company.companies.company_id) + user_id = Column(UUID(as_uuid=True), nullable=False) # 등록 유저(company.users.user_id) + name = Column(String(100), nullable=False) # 상품명 + code = Column(String(30), nullable=True) # 상품 코드 + price = Column(BigInteger, nullable=True) # 가격(원) + category = Column(String(255), nullable=True) # 카테고리 + image_url = Column(String(255), nullable=True) # 이미지 URL + model_name = Column(String(100), nullable=True) # 모델명 + spec = Column(String(255), nullable=True) # 규격 + moq = Column(String(50), nullable=True) # 최소 주문 수량 + lead_time = Column(SmallInteger, nullable=True) # 배송 리드타임 + manufacturer = Column(String(50), nullable=True) # 제조사 + made_in = Column(String(100), nullable=True) # 원산지 + quantity_unit = Column(SmallInteger, nullable=True) # 취급 단위 (코드, 앱 enum 매핑) + delivery_type = Column(SmallInteger, nullable=True) # 배송 유형 (코드, 앱 enum 매핑) + vat_yn = Column(Boolean, nullable=True) # 부가세 포함 여부 + delivery_fee_yn = Column(Boolean, nullable=True) # 배송비 포함 여부 + internet_lowest_price_yn = Column(Boolean, nullable=False, server_default=text("false")) # 최저가 솔루션 보조 컬럼 + category_type = Column(Integer, nullable=False, server_default=text("1")) # 카테고리 조회용 자동 증가 숫자 + created_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')")) # 생성 시각(UTC) + updated_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')")) # 수정 시각(UTC, 앱에서 갱신) + deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부 + + +class sessions(MAIN_BASE): + # negotiation.sessions (협상 세션). + @staticmethod + def DBType(): + return DBType.NEGOTIATION.value + + __tablename__ = "sessions" + __table_args__ = {"schema": "negotiation"} + + session_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")) # 협상 세션 식별자(PK) + quotation_id = Column(UUID(as_uuid=True), nullable=False) # 소속 견적(quotation.quotations.qt_id) + item_id = Column(UUID(as_uuid=True), nullable=False) # 대상 상품(partner.items.item_id) + supplier_id = Column(UUID(as_uuid=True), nullable=False) # 대상 공급사(partner.suppliers.supplier_id) + qt_number = Column(String(30), nullable=False) # 견적번호(스냅샷) + qt_round = Column(Integer, nullable=False) # 견적 라운드(스냅샷) + qt_type = Column(SmallInteger, nullable=False) # 견적 유형: 1=재협상, 2=재견적 (QtType) + target_price = Column(BigInteger, nullable=False) # 목표가(원) + status = Column(SmallInteger, nullable=False) # 진행 상태 (SessionStatus 코드) + bid_price = Column(BigInteger, nullable=True) # 입찰가(원) + bid_at = Column(DateTime(timezone=True), nullable=True) # 입찰 시각 + end_time = Column(DateTime(timezone=True), nullable=False) # 세션 종료(마감) 시각 + reject_reason = Column(String(255), nullable=True) # 거절 사유 + reject_price = Column(BigInteger, nullable=True) # 거절 시 제시가(원) + reject_delivery_type = Column(SmallInteger, nullable=True) # 거절 시 배송 유형 (코드) + created_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')")) # 생성 시각(UTC) + updated_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')")) # 수정 시각(UTC, 앱에서 갱신) + deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부 + + +class quotations(MAIN_BASE): + # quotation.quotations (견적). + @staticmethod + def DBType(): + return DBType.QUOTATION.value + + __tablename__ = "quotations" + __table_args__ = {"schema": "quotation"} + + qt_id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")) # 견적 식별자(PK) + user_id = Column(UUID(as_uuid=True), nullable=False) # 생성 유저(company.users.user_id) + qt_setting_id = Column(UUID(as_uuid=True), nullable=False) # 견적 설정(quotation.quotation_settings.qt_setting_id) + version_id = Column(UUID(as_uuid=True), nullable=False) # 버전(card.versions.version_id) + name = Column(String(50), nullable=False) # 견적명 + number = Column(String(30), nullable=False) # 견적번호 + type = Column(SmallInteger, nullable=False) # 견적 유형: 1=재협상, 2=재견적 (QtType) + round = Column(Integer, nullable=False, server_default=text("1")) # 재견적 회차 + status = Column(SmallInteger, nullable=False) # 진행 상태 (QuotationStatus 코드) + start_time = Column(DateTime(timezone=True), nullable=False) # 견적 시작 시각 + end_time = Column(DateTime(timezone=True), nullable=False) # 견적 종료(마감) 시각 + manager_name = Column(String(50), nullable=True) # 담당자명 + manager_email = Column(String(255), nullable=True) # 담당자 이메일 + manager_contact_number = Column(String(20), nullable=True) # 담당자 연락처 + memo = Column(String(100), nullable=True) # 메모 + iteration = Column(Integer, nullable=False, server_default=text("0")) # 반복 횟수 + preferred_sp_yn = Column(Boolean, nullable=True) # 선호 공급사 지정 여부 + preferred_sp_id = Column(UUID(as_uuid=True), nullable=True) # 선호 공급사(partner.suppliers.supplier_id) + preferred_sp_name = Column(String(20), nullable=True) # 선호 공급사명(스냅샷) + equal_bid_yn = Column(Boolean, nullable=True) # 동일가 입찰 발생 여부 + equal_bid_data = Column(JSONB, nullable=True) # 동일가 입찰 상세(JSON) + created_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')")) # 생성 시각(UTC) + updated_at = Column(DateTime(timezone=True), nullable=False, server_default=text("(now() AT TIME ZONE 'utc')")) # 수정 시각(UTC, 앱에서 갱신) + deleted = Column(Boolean, nullable=False, server_default=text("false")) # 소프트 삭제 여부 + + class supplier_user_tokens(MAIN_BASE): # 유저 인증 토큰. supplier_users 1 : N tokens. @staticmethod diff --git a/backend/common/enums.py b/backend/common/enums.py index e3525b7..7559b6d 100644 --- a/backend/common/enums.py +++ b/backend/common/enums.py @@ -37,6 +37,13 @@ class ErrorType(Enum): ACCOUNT_BLOCKED_USER = auto() TOKEN_REVOKED = auto() # 제시된 토큰이 저장된 토큰과 불일치(로그아웃/타기기 로그인으로 교체됨) + # 협상(negotiation) 관련 에러 — 프론트 toast 용 코드 + NEGO_FORBIDDEN = 1300 # 공급사 불일치(권한 없음) + NEGO_NOT_PARTICIPABLE = auto() # 1301 세션 상태가 미참여/협상거부라 참여 불가 + NEGO_QUOTATION_CLOSED = auto() # 1302 견적 마감 상태 + NEGO_DEADLINE_PASSED = auto() # 1303 견적 마감 시간 초과 + NEGO_NOT_FOUND = auto() # 1304 세션/견적 없음 + # ErrorType 의 HTTP_* 값과 status_code 를 맞춰 router 단에서 raise 한다. EXCEPTION_INVALID_CLIENT_REQUEST = HTTPException(status_code=ErrorType.HTTP_INVALID_CLIENT_REQUEST.value, detail=ErrorType.HTTP_INVALID_CLIENT_REQUEST.name) @@ -53,8 +60,10 @@ class DBType(Enum): 물리적으로 같은 negosium_db 라도 도메인별 논리 구분으로 나눠 둘 수 있다(커넥션 config 는 재사용). """ - USER = 1 # 기본 유저 (supplier_users 테이블) - PARTNER = 2 # partner 도메인 (partner.suppliers 등) + USER = 1 # 기본 유저 (supplier_users 테이블) + PARTNER = 2 # partner 도메인 (partner.suppliers, partner.items 등) + NEGOTIATION = 3 # negotiation 도메인 (negotiation.sessions 등) + QUOTATION = 4 # quotation 도메인 (quotation.quotations 등) class DBWRType(Enum): @@ -87,3 +96,32 @@ class TokenType(Enum): ACCESS = 1 REFRESH = 2 + + +class QtType(Enum): + """견적/세션 유형 코드. quotation.quotations.type / negotiation.sessions.qt_type.""" + + RENEGO = 1 # 재협상(1:1) + REQUOTE = 2 # 재견적(1:N) + + +class SessionStatus(Enum): + """협상 세션 진행 상태 코드. negotiation.sessions.status. + ⚠️ 세션을 생성/갱신하는 쪽(바이어/agent)과 코드값이 일치해야 한다. + """ + + CREATED = 1 # 협상생성 + IN_PROGRESS = 2 # 협상중 + DONE = 3 # 협상완료 + NOT_PARTICIPATED = 4 # 미참여 + REJECTED = 5 # 협상거부 + + +class QuotationStatus(Enum): + """견적 진행 상태 코드. quotation.quotations.status. + ⚠️ 견적을 생성/갱신하는 쪽(바이어/agent)과 코드값이 일치해야 한다. + """ + + CREATED = 1 # 견적생성 + IN_PROGRESS = 2 # 견적진행중 + CLOSED = 3 # 견적마감 diff --git a/backend/crud/session_crud.py b/backend/crud/session_crud.py new file mode 100644 index 0000000..8801ae3 --- /dev/null +++ b/backend/crud/session_crud.py @@ -0,0 +1,140 @@ +from abc import ABC, abstractmethod +from typing import Tuple + +from sqlalchemy import asc, desc, func, select, update +from sqlalchemy.ext.asyncio import AsyncSession + +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import items, quotations, sessions +from common.enums import ErrorType +from common.logger import LOG + + +# 협상 세션 CRUD. 목록은 세션(negotiation) ⨝ 상품(partner) ⨝ 견적(quotation) 조인으로 만든다. +# 마감일(qt_end_time)은 견적(quotation.end_time)이 진실값이다(session.end_time 은 협상 종료 시점 기록용). +class ISessionCRUD(ABC): + @abstractmethod + async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit) -> Tuple[ErrorType, list]: + pass + + @abstractmethod + async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type) -> Tuple[ErrorType, int]: + pass + + @abstractmethod + async def get_session_by_id(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, sessions]: + pass + + @abstractmethod + async def get_quotation_by_id(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, quotations]: + pass + + @abstractmethod + async def update_session_status(self, cdb: AsyncSession, session_id, status: int) -> ErrorType: + pass + + @abstractmethod + async def update_quotation_status(self, cdb: AsyncSession, quotation_id, status: int) -> ErrorType: + pass + + +class SessionCRUD(ISessionCRUD): + @staticmethod + def __filters(supplier_id, status, qt_type): + conds = [sessions.supplier_id == supplier_id, sessions.deleted == False] # noqa: E712 + if status is not None: + conds.append(sessions.status == status) + if qt_type is not None: + conds.append(sessions.qt_type == qt_type) + return conds + + async def list_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type, order, offset, limit) -> Tuple[ErrorType, list]: + try: + conds = self.__filters(supplier_id, status, qt_type) + order_col = desc(quotations.end_time) if order == "desc" else asc(quotations.end_time) + query = ( + select( + sessions.session_id, + sessions.status, + sessions.qt_type, + sessions.qt_number, + quotations.end_time, # qt_end_time = 견적 마감 시각 + items.code, + items.name, + items.model_name, + items.manufacturer, + ) + .join(items, items.item_id == sessions.item_id) + .join(quotations, quotations.qt_id == sessions.quotation_id) + .where(*conds, items.deleted == False, quotations.deleted == False) # noqa: E712 + .order_by(order_col) + .offset(offset) + .limit(limit) + ) + err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "list_by_supplier failed.") + if err_type != ErrorType.SUCCESS: + return err_type, [] + return ErrorType.SUCCESS, rows + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, [] + + async def count_by_supplier(self, cdb: AsyncSession, supplier_id, status, qt_type) -> Tuple[ErrorType, int]: + try: + conds = self.__filters(supplier_id, status, qt_type) + query = ( + select(func.count()) + .select_from(sessions) + .join(items, items.item_id == sessions.item_id) + .join(quotations, quotations.qt_id == sessions.quotation_id) + .where(*conds, items.deleted == False, quotations.deleted == False) # noqa: E712 + ) + err_type, rows = await DB_SESSION_MNG.execute(cdb, query, "count_by_supplier failed.") + if err_type != ErrorType.SUCCESS: + return err_type, 0 + return ErrorType.SUCCESS, (rows[0] if rows else 0) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, 0 + + async def get_session_by_id(self, cdb: AsyncSession, session_id) -> Tuple[ErrorType, sessions]: + try: + query = select(sessions).where(sessions.session_id == session_id, sessions.deleted == False).limit(1) # noqa: E712 + err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_session_by_id({session_id}) failed.") + if err_type != ErrorType.SUCCESS: + return err_type, None + if len(row_list) != 1: + return ErrorType.DB_INVALID_KEY, None + return ErrorType.SUCCESS, row_list[0] + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, None + + async def get_quotation_by_id(self, cdb: AsyncSession, quotation_id) -> Tuple[ErrorType, quotations]: + try: + query = select(quotations).where(quotations.qt_id == quotation_id, quotations.deleted == False).limit(1) # noqa: E712 + err_type, row_list = await DB_SESSION_MNG.execute(cdb, query, f"get_quotation_by_id({quotation_id}) failed.") + if err_type != ErrorType.SUCCESS: + return err_type, None + if len(row_list) != 1: + return ErrorType.DB_INVALID_KEY, None + return ErrorType.SUCCESS, row_list[0] + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED, None + + async def update_session_status(self, cdb: AsyncSession, session_id, status: int) -> ErrorType: + try: + query = update(sessions).where(sessions.session_id == session_id).values(status=status) + return await DB_SESSION_MNG.add(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED + + async def update_quotation_status(self, cdb: AsyncSession, quotation_id, status: int) -> ErrorType: + try: + query = update(quotations).where(quotations.qt_id == quotation_id).values(status=status) + return await DB_SESSION_MNG.add(cdb, query) + except Exception as ex: + LOG.e_no_callstack(ex) + return ErrorType.DB_RUN_FAILED diff --git a/backend/router/router.py b/backend/router/router.py index 6a8c54f..7a8f7da 100644 --- a/backend/router/router.py +++ b/backend/router/router.py @@ -10,6 +10,7 @@ from common.logger import LOG from common.utils.gtime import GTime from config.server_configs import web_server_config import router.v1.auth.account +import router.v1.negotiation.session API_SERVER_START_TIME = GTime.UTCStr() @@ -55,3 +56,4 @@ async def healthz(): # 각 도메인 라우터를 등록한다. 새 기능 추가 시 router.v1.. 를 import 후 include. app.include_router(router.v1.auth.account.router) +app.include_router(router.v1.negotiation.session.router) diff --git a/backend/router/v1/negotiation/protocol.py b/backend/router/v1/negotiation/protocol.py new file mode 100644 index 0000000..39b01bc --- /dev/null +++ b/backend/router/v1/negotiation/protocol.py @@ -0,0 +1,25 @@ +from common.models.gmodel import Res_WebPacketProtocol, WebPacketProtocol + + +# 협상 세션 목록 행. status/qt_type 은 정수 코드로 내려가고 라벨 매핑은 프론트가 한다. +class ListItem(WebPacketProtocol): + session_id: str = "" + session_status: int = 0 # SessionStatus 코드 + qt_type: int = 0 # QtType 코드 (1=재협상, 2=재견적) + qt_number: str = "" + qt_end_time: str = "" # ISO 8601 (마감 시각) + item_code: str = "" + item_name: str = "" + model_name: str = "" + maker_name: str = "" + + +class Res_SessionList(Res_WebPacketProtocol): + items: list[ListItem] = [] + total: int = 0 + page: int = 0 + page_size: int = 0 + + +class Res_Participate(Res_WebPacketProtocol): + session_id: str = "" # 참여 성공한 세션 (채팅 진입용) diff --git a/backend/router/v1/negotiation/session.py b/backend/router/v1/negotiation/session.py new file mode 100644 index 0000000..228b4a0 --- /dev/null +++ b/backend/router/v1/negotiation/session.py @@ -0,0 +1,47 @@ +from typing import Optional + +from fastapi import APIRouter, Depends, Query +from fastapi.security import HTTPAuthorizationCredentials + +from common.models.gmodel import UserInfo +from router.v1.validator.dependencies import IsValidAccessToken, RemoveNoneResponse, security +from services.negotiation_service import NegotiationService +from .protocol import Res_Participate, Res_SessionList + +router = APIRouter(prefix="/v1/negotiation", tags=["Negotiation"], responses={404: {"description": "Not found"}}) + + +@router.get( + path="/sessions", + response_model=Res_SessionList, + summary="협상 세션 목록", + description="로그인한 공급사의 협상 세션 목록. 필터(status/qt_type, 정수 코드)·마감일 정렬·페이지네이션 지원.", +) +async def list_sessions( + user_info: UserInfo = Depends(IsValidAccessToken), + credentials: HTTPAuthorizationCredentials = Depends(security), + service: NegotiationService = Depends(), + status: Optional[int] = Query(None, description="세션 상태 코드 (SessionStatus)"), + qt_type: Optional[int] = Query(None, description="견적 유형 코드 (QtType: 1=재협상, 2=재견적)"), + order: str = Query("asc", description="마감일 정렬: asc(임박순)/desc"), + page: int = Query(1, ge=1), + page_size: int = Query(20, ge=1, le=100), +): + return RemoveNoneResponse( + await service.list_sessions(user_info, credentials.credentials, status, qt_type, order, page, page_size) + ) + + +@router.post( + path="/sessions/{session_id}/participate", + response_model=Res_Participate, + summary="협상 참여", + description="세션에 참여한다. 소유(공급사)·세션상태·견적마감·마감시간 검증 후 협상생성→협상중, 견적→견적진행중으로 전이.", +) +async def participate( + session_id: str, + user_info: UserInfo = Depends(IsValidAccessToken), + credentials: HTTPAuthorizationCredentials = Depends(security), + service: NegotiationService = Depends(), +): + return RemoveNoneResponse(await service.participate(user_info, credentials.credentials, session_id)) diff --git a/backend/services/auth_service.py b/backend/services/auth_service.py index eb4f73f..f95f114 100644 --- a/backend/services/auth_service.py +++ b/backend/services/auth_service.py @@ -218,15 +218,23 @@ class AuthService: ) return err_type == ErrorType.SUCCESS and stored == presented - async def get_me(self, user_info: UserInfo, access_token: str) -> Res_Me: - # 토큰 디코드는 라우터 Depends(IsValidAccessToken) 에서 수행됨. 여기선 su_id DB 검증 + 저장 토큰 대조. - res = Res_Me() + async def authenticate(self, user_info: UserInfo, access_token: str) -> tuple[ErrorType, UserInfo]: + """access 토큰 보호 요청 공통 인증: 계정 활성 확인 + 저장된 access 토큰 대조. + 성공 시 (SUCCESS, DB 최신 UserInfo), 실패 시 (에러코드, None). 다른 도메인 service 에서도 재사용한다. + """ err_type, info = await self.__load_active_account(user_info.su_id) if err_type != ErrorType.SUCCESS: - res.result.SetResult(err_type) - return res + return err_type, None if not await self.__verify_stored_token(info.su_id, TokenType.ACCESS.value, access_token): - res.result.SetResult(ErrorType.TOKEN_REVOKED) # 로그아웃/타기기 로그인으로 무효화됨 + return ErrorType.TOKEN_REVOKED, None # 로그아웃/타기기 로그인으로 무효화됨 + return ErrorType.SUCCESS, info + + async def get_me(self, user_info: UserInfo, access_token: str) -> Res_Me: + # 토큰 디코드는 라우터 Depends(IsValidAccessToken) 에서 수행됨. 여기선 공통 인증으로 검증. + res = Res_Me() + err_type, info = await self.authenticate(user_info, access_token) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) return res res.su_id = info.su_id res.id = info.id diff --git a/backend/services/negotiation_service.py b/backend/services/negotiation_service.py new file mode 100644 index 0000000..268887b --- /dev/null +++ b/backend/services/negotiation_service.py @@ -0,0 +1,150 @@ +import uuid +from datetime import datetime, timezone + +from fastapi import Depends + +from common.database.db_session_manager import DB_SESSION_MNG +from common.database.model.models import sessions +from common.enums import DBWRType, ErrorType, QuotationStatus, SessionStatus +from common.models.gmodel import UserInfo +from crud.session_crud import ISessionCRUD, SessionCRUD +from router.v1.negotiation.protocol import ListItem, Res_Participate, Res_SessionList +from services.auth_service import AuthService + + +class NegotiationService: + """협상 도메인 비즈니스 로직. + - 인증(계정 활성 + 저장 토큰 대조)은 AuthService.authenticate 로 위임(재사용). + - 목록은 로그인 유저의 supplier_id 로만 조회한다. + """ + + def __init__(self, auth: AuthService = Depends(AuthService), session_crud: ISessionCRUD = Depends(SessionCRUD)): + self.auth = auth + self.session_crud = session_crud + + async def list_sessions(self, user_info: UserInfo, access_token: str, status, qt_type, order: str, page: int, page_size: int) -> Res_SessionList: + res = Res_SessionList() + + # 1) 인증 (활성 + 저장된 access 토큰 대조) + err_type, info = await self.auth.authenticate(user_info, access_token) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + supplier_id = uuid.UUID(info.supplier_id) + offset = (page - 1) * page_size + + # 2) 목록 조회 (NEGOTIATION Read 세션, sessions ⨝ items) + err_type, rows = await DB_SESSION_MNG.execute_lambda( + sessions.DBType(), + DBWRType.DB_READ.value, + lambda s: self.session_crud.list_by_supplier(s, supplier_id, status, qt_type, order, offset, page_size), + ) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + # 3) 총개수 (페이지네이션용) + err_type, total = await DB_SESSION_MNG.execute_lambda( + sessions.DBType(), + DBWRType.DB_READ.value, + lambda s: self.session_crud.count_by_supplier(s, supplier_id, status, qt_type), + ) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + res.items = [ + ListItem( + session_id=str(r[0]), + session_status=r[1], + qt_type=r[2], + qt_number=r[3], + qt_end_time=r[4].isoformat(timespec="seconds") if r[4] else "", + item_code=r[5] or "", + item_name=r[6] or "", + model_name=r[7] or "", + maker_name=r[8] or "", + ) + for r in rows + ] + res.total = total + res.page = page + res.page_size = page_size + return res + + async def participate(self, user_info: UserInfo, access_token: str, session_id_str: str) -> Res_Participate: + res = Res_Participate() + + # 1) 인증 + err_type, info = await self.auth.authenticate(user_info, access_token) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + try: + session_id = uuid.UUID(session_id_str) + except (ValueError, TypeError): + res.result.SetResult(ErrorType.NEGO_NOT_FOUND) + return res + + # 2) 세션 조회 + err_type, sess = await DB_SESSION_MNG.execute_lambda( + sessions.DBType(), + DBWRType.DB_READ.value, + lambda s: self.session_crud.get_session_by_id(s, session_id), + ) + if err_type != ErrorType.SUCCESS or sess is None: + res.result.SetResult(ErrorType.NEGO_NOT_FOUND) + return res + + # 3) 소유 검증 (세션 공급사 == 접속 유저 공급사) + if str(sess.supplier_id) != info.supplier_id: + res.result.SetResult(ErrorType.NEGO_FORBIDDEN) + return res + + # 4) 세션 상태 검증 (미참여/협상거부는 참여 불가) + if sess.status in (SessionStatus.NOT_PARTICIPATED.value, SessionStatus.REJECTED.value): + res.result.SetResult(ErrorType.NEGO_NOT_PARTICIPABLE) + return res + + # 5) 견적 조회 + 마감 상태 + err_type, quote = await DB_SESSION_MNG.execute_lambda( + sessions.DBType(), + DBWRType.DB_READ.value, + lambda s: self.session_crud.get_quotation_by_id(s, sess.quotation_id), + ) + if err_type != ErrorType.SUCCESS or quote is None: + res.result.SetResult(ErrorType.NEGO_NOT_FOUND) + return res + if quote.status == QuotationStatus.CLOSED.value: + res.result.SetResult(ErrorType.NEGO_QUOTATION_CLOSED) + return res + + # 6) 마감 시간 초과 (견적 end_time < 현재). 협상생성(1)일 때만 session→미참여로 정리. + end = quote.end_time + if end is not None and end.tzinfo is None: + end = end.replace(tzinfo=timezone.utc) + if end is not None and end < datetime.now(timezone.utc): + if sess.status == SessionStatus.CREATED.value: + await DB_SESSION_MNG.execute_lambda_run( + [sessions.DBType()], + [lambda s: self.session_crud.update_session_status(s, session_id, SessionStatus.NOT_PARTICIPATED.value)], + ) + res.result.SetResult(ErrorType.NEGO_DEADLINE_PASSED) + return res + + # 7) 참여 성공 — 협상생성(1)일 때만 상태 전이(협상중/완료는 무변경 진입) + if sess.status == SessionStatus.CREATED.value: + err_type = await DB_SESSION_MNG.execute_lambda_run( + [sessions.DBType()], + [ + lambda s: self.session_crud.update_session_status(s, session_id, SessionStatus.IN_PROGRESS.value), + lambda s: self.session_crud.update_quotation_status(s, sess.quotation_id, QuotationStatus.IN_PROGRESS.value), + ], + ) + if err_type != ErrorType.SUCCESS: + res.result.SetResult(err_type) + return res + + res.session_id = str(sess.session_id) + return res diff --git a/backend/tests/test_negotiation.py b/backend/tests/test_negotiation.py new file mode 100644 index 0000000..5ea6ba2 --- /dev/null +++ b/backend/tests/test_negotiation.py @@ -0,0 +1,211 @@ +"""협상 도메인 e2e 테스트 (세션 목록 + 참여). + +dev negosium_db 를 그대로 쓰므로 전용 테스트 행만 시드/정리한다. +목록의 qt_end_time 은 quotation.end_time 기준이라 세션마다 견적을 함께 시드한다. +""" + +import uuid + +import bcrypt +import pytest_asyncio +from sqlalchemy import text + +TEST_LOGIN_ID = "pytest_nego_user" +TEST_PW = "pytest1234" +TEST_SUPPLIER_NAME = "파이테스트협상공급사" +MARK = "PYTESTNEGO-" # 시드 식별용 prefix (item code / qt number) + + +@pytest_asyncio.fixture +async def nego_seed(db_engine): + """공급사 + 유저 + 세션/견적 3건(본인) + 1건(타 공급사) 시드. 세션/견적 id 를 반환.""" + supplier_id = uuid.uuid4() + other_supplier_id = uuid.uuid4() + pw_hash = bcrypt.hashpw(TEST_PW.encode("utf-8"), bcrypt.gensalt()).decode("utf-8") + + # (code, session.status, qt_type, 마감까지 시간(h), quotation.status, 소속 공급사) + specs = [ + ("A", 1, 2, 2, 1, supplier_id), # 협상생성 / 재견적 / +2h / 견적생성 + ("B", 2, 1, 1, 2, supplier_id), # 협상중 / 재협상 / +1h / 견적진행중 + ("C", 3, 2, 3, 2, supplier_id), # 협상완료 / 재견적 / +3h / 견적진행중 + ("X", 1, 1, 1, 1, other_supplier_id), # 타 공급사 → 목록/참여에서 제외/차단 + ] + sids, qids = {}, {} + + async def _cleanup(conn): + await conn.execute(text(f"DELETE FROM negotiation.sessions WHERE qt_number LIKE '{MARK}%'")) + await conn.execute(text(f"DELETE FROM quotation.quotations WHERE number LIKE '{MARK}%'")) + await conn.execute(text(f"DELETE FROM partner.items WHERE code LIKE '{MARK}%'")) + await conn.execute(text("DELETE FROM supplier.supplier_users WHERE id = :id"), {"id": TEST_LOGIN_ID}) + await conn.execute(text("DELETE FROM partner.suppliers WHERE name = :n"), {"n": TEST_SUPPLIER_NAME}) + + async with db_engine.begin() as conn: + await _cleanup(conn) + await conn.execute( + text("INSERT INTO partner.suppliers (supplier_id, company_id, user_id, name) VALUES (:sid, gen_random_uuid(), gen_random_uuid(), :name)"), + {"sid": supplier_id, "name": TEST_SUPPLIER_NAME}, + ) + await conn.execute( + text( + "INSERT INTO supplier.supplier_users (supplier_id, id, password, name, last_accessed_at, status, role) " + "VALUES (:sid, :id, :pw, '협상담당자', now(), 1, 1)" + ), + {"sid": supplier_id, "id": TEST_LOGIN_ID, "pw": pw_hash}, + ) + for code, sess_st, qt_type, hrs, quote_st, sup in specs: + item_id, qt_id, session_id = uuid.uuid4(), uuid.uuid4(), uuid.uuid4() + sids[code], qids[code] = session_id, qt_id + await conn.execute( + text( + "INSERT INTO partner.items (item_id, company_id, user_id, name, code, model_name, manufacturer) " + "VALUES (:iid, gen_random_uuid(), gen_random_uuid(), :name, :code, :model, '테스트제조사')" + ), + {"iid": item_id, "name": f"상품 {code}", "code": f"{MARK}{code}", "model": f"MODEL-{code}"}, + ) + await conn.execute( + text( + "INSERT INTO quotation.quotations (qt_id, user_id, qt_setting_id, version_id, name, number, type, status, start_time, end_time) " + "VALUES (:qid, gen_random_uuid(), gen_random_uuid(), gen_random_uuid(), :name, :num, :tp, :st, now(), now() + make_interval(hours => :hrs))" + ), + {"qid": qt_id, "name": f"견적 {code}", "num": f"{MARK}{code}", "tp": qt_type, "st": quote_st, "hrs": hrs}, + ) + await conn.execute( + text( + "INSERT INTO negotiation.sessions " + "(session_id, quotation_id, item_id, supplier_id, qt_number, qt_round, qt_type, target_price, status, end_time) " + "VALUES (:sesid, :qid, :iid, :sup, :qtn, 1, :qtt, 100000, :st, now())" + ), + {"sesid": session_id, "qid": qt_id, "iid": item_id, "sup": sup, "qtn": f"{MARK}{code}", "qtt": qt_type, "st": sess_st}, + ) + + yield {"supplier_id": supplier_id, "sids": sids, "qids": qids} + + async with db_engine.begin() as conn: + await _cleanup(conn) + + +async def _login_token(client): + r = await client.post("/v1/auth/login", json={"id": TEST_LOGIN_ID, "pw": TEST_PW}) + return r.json()["access_token"] + + +async def _list(client, token, **params): + return await client.get("/v1/negotiation/sessions", headers={"Authorization": f"Bearer {token}"}, params=params) + + +async def _participate(client, token, session_id): + return await client.post(f"/v1/negotiation/sessions/{session_id}/participate", headers={"Authorization": f"Bearer {token}"}) + + +async def _session_status(db_engine, session_id): + async with db_engine.begin() as conn: + return (await conn.execute(text("SELECT status FROM negotiation.sessions WHERE session_id = :sid"), {"sid": session_id})).scalar() + + +async def _quotation_status(db_engine, qt_id): + async with db_engine.begin() as conn: + return (await conn.execute(text("SELECT status FROM quotation.quotations WHERE qt_id = :qid"), {"qid": qt_id})).scalar() + + +# ---- 목록 ------------------------------------------------------------------- +async def test_list_returns_only_own_supplier_sessions(client, nego_seed): + token = await _login_token(client) + body = (await _list(client, token)).json() + assert body["result"]["success"] is True + assert body["total"] == 3 # 본인 공급사 3건만 (타 공급사 X 제외) + one = next(i for i in body["items"] if i["item_code"] == f"{MARK}B") + assert one["session_status"] == 2 and one["qt_type"] == 1 + assert one["model_name"] == "MODEL-B" and one["maker_name"] == "테스트제조사" + assert one["session_id"] and one["qt_end_time"] + + +async def test_list_filter_status(client, nego_seed): + token = await _login_token(client) + body = (await _list(client, token, status=2)).json() + assert body["total"] == 1 and body["items"][0]["item_code"] == f"{MARK}B" + + +async def test_list_filter_qt_type(client, nego_seed): + token = await _login_token(client) + body = (await _list(client, token, qt_type=2)).json() + assert {i["item_code"] for i in body["items"]} == {f"{MARK}A", f"{MARK}C"} + + +async def test_list_order_by_quotation_end_time(client, nego_seed): + token = await _login_token(client) + asc = (await _list(client, token, order="asc")).json()["items"] + desc = (await _list(client, token, order="desc")).json()["items"] + assert asc[0]["item_code"] == f"{MARK}B" # +1h 가 가장 임박 + assert desc[0]["item_code"] == f"{MARK}C" # +3h 가 가장 멈 + + +async def test_list_pagination(client, nego_seed): + token = await _login_token(client) + body = (await _list(client, token, page=1, page_size=2)).json() + assert body["total"] == 3 and len(body["items"]) == 2 + + +async def test_list_requires_auth(client): + assert (await client.get("/v1/negotiation/sessions")).status_code in (401, 403) + + +# ---- 참여 ------------------------------------------------------------------- +async def test_participate_success(client, nego_seed, db_engine): + token = await _login_token(client) + sid, qid = nego_seed["sids"]["A"], nego_seed["qids"]["A"] # 협상생성 + r = await _participate(client, token, sid) + assert r.json()["result"]["success"] is True + assert r.json()["session_id"] == str(sid) + assert await _session_status(db_engine, sid) == 2 # 협상중 + assert await _quotation_status(db_engine, qid) == 2 # 견적진행중 + + +async def test_participate_forbidden_other_supplier(client, nego_seed): + token = await _login_token(client) + r = await _participate(client, token, nego_seed["sids"]["X"]) # 타 공급사 세션 + assert r.json()["result"]["code"] == 1300 # NEGO_FORBIDDEN + + +async def test_participate_not_participable(client, nego_seed, db_engine): + token = await _login_token(client) + sid = nego_seed["sids"]["A"] + async with db_engine.begin() as conn: + await conn.execute(text("UPDATE negotiation.sessions SET status = 4 WHERE session_id = :sid"), {"sid": sid}) # 미참여 + r = await _participate(client, token, sid) + assert r.json()["result"]["code"] == 1301 # NEGO_NOT_PARTICIPABLE + + +async def test_participate_quotation_closed(client, nego_seed, db_engine): + token = await _login_token(client) + sid, qid = nego_seed["sids"]["A"], nego_seed["qids"]["A"] + async with db_engine.begin() as conn: + await conn.execute(text("UPDATE quotation.quotations SET status = 3 WHERE qt_id = :qid"), {"qid": qid}) # 견적마감 + r = await _participate(client, token, sid) + assert r.json()["result"]["code"] == 1302 # NEGO_QUOTATION_CLOSED + + +async def test_participate_deadline_passed_sets_not_participated(client, nego_seed, db_engine): + token = await _login_token(client) + sid, qid = nego_seed["sids"]["A"], nego_seed["qids"]["A"] # 협상생성 + async with db_engine.begin() as conn: + await conn.execute(text("UPDATE quotation.quotations SET end_time = now() - make_interval(hours => 1) WHERE qt_id = :qid"), {"qid": qid}) + r = await _participate(client, token, sid) + assert r.json()["result"]["code"] == 1303 # NEGO_DEADLINE_PASSED + assert await _session_status(db_engine, sid) == 4 # 협상생성이었으므로 미참여로 정리됨 + assert await _quotation_status(db_engine, qid) == 1 # 견적은 변경 안 됨 + + +async def test_participate_in_progress_no_state_change(client, nego_seed, db_engine): + token = await _login_token(client) + sid, qid = nego_seed["sids"]["B"], nego_seed["qids"]["B"] # 이미 협상중 + r = await _participate(client, token, sid) + assert r.json()["result"]["success"] is True + assert r.json()["session_id"] == str(sid) + assert await _session_status(db_engine, sid) == 2 # 무변경 (협상중 유지) + assert await _quotation_status(db_engine, qid) == 2 # 무변경 + + +async def test_participate_session_not_found(client, nego_seed): + token = await _login_token(client) + r = await _participate(client, token, str(uuid.uuid4())) + assert r.json()["result"]["code"] == 1304 # NEGO_NOT_FOUND From a867daa98faa67f0b972b45ef0ce38430430cfe0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=AF=BC=ED=97=8C?= Date: Thu, 18 Jun 2026 13:12:07 +0900 Subject: [PATCH 07/14] =?UTF-8?q?feat(frontend):=20TanStack=20Query=20?= =?UTF-8?q?=EA=B8=B0=EB=B0=98=20apis=20=EB=A0=88=EC=9D=B4=EC=96=B4=20?= =?UTF-8?q?=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - auth/negotiation 도메인별 api/keys/queries/mutations/type 5파일 구조 - axios 인스턴스: access token 주입, 434 만료 시 refresh 자동 재발급(단일 비행) 후 원요청 재시도, 433/435/1203(TOKEN_REVOKED) 시 세션 종료 처리 - HTTP 200 + result.success=false 비즈니스 에러를 ApiError 로 변환, 에러코드별 한국어 메시지 맵(getApiErrorMessage) 제공 - 토큰 localStorage 저장소(tokenStorage) Co-Authored-By: Claude Opus 4.8 (1M context) --- frontend/src/apis/auth/auth.api.ts | 37 ++++++ frontend/src/apis/auth/auth.keys.ts | 5 + frontend/src/apis/auth/auth.mutations.ts | 55 ++++++++ frontend/src/apis/auth/auth.queries.ts | 20 +++ frontend/src/apis/auth/auth.type.ts | 91 ++++++++++++++ frontend/src/apis/auth/index.ts | 11 ++ frontend/src/apis/http.ts | 118 ++++++++++++++++++ frontend/src/apis/index.ts | 8 ++ frontend/src/apis/negotiation/index.ts | 6 + .../src/apis/negotiation/negotiation.api.ts | 34 +++++ .../src/apis/negotiation/negotiation.keys.ts | 8 ++ .../apis/negotiation/negotiation.mutations.ts | 32 +++++ .../apis/negotiation/negotiation.queries.ts | 17 +++ .../src/apis/negotiation/negotiation.type.ts | 80 ++++++++++++ frontend/src/apis/tokenStorage.ts | 27 ++++ frontend/src/apis/types.ts | 80 ++++++++++++ 16 files changed, 629 insertions(+) create mode 100644 frontend/src/apis/auth/auth.api.ts create mode 100644 frontend/src/apis/auth/auth.keys.ts create mode 100644 frontend/src/apis/auth/auth.mutations.ts create mode 100644 frontend/src/apis/auth/auth.queries.ts create mode 100644 frontend/src/apis/auth/auth.type.ts create mode 100644 frontend/src/apis/auth/index.ts create mode 100644 frontend/src/apis/http.ts create mode 100644 frontend/src/apis/index.ts create mode 100644 frontend/src/apis/negotiation/index.ts create mode 100644 frontend/src/apis/negotiation/negotiation.api.ts create mode 100644 frontend/src/apis/negotiation/negotiation.keys.ts create mode 100644 frontend/src/apis/negotiation/negotiation.mutations.ts create mode 100644 frontend/src/apis/negotiation/negotiation.queries.ts create mode 100644 frontend/src/apis/negotiation/negotiation.type.ts create mode 100644 frontend/src/apis/tokenStorage.ts create mode 100644 frontend/src/apis/types.ts diff --git a/frontend/src/apis/auth/auth.api.ts b/frontend/src/apis/auth/auth.api.ts new file mode 100644 index 0000000..780b0cc --- /dev/null +++ b/frontend/src/apis/auth/auth.api.ts @@ -0,0 +1,37 @@ +// 인증 엔드포인트 호출 함수 (순수 HTTP 레이어, React 의존 없음). +// refresh_token 재발급은 http.ts 인터셉터가 자동 처리하므로 여기서 노출하지 않는다. +import { http } from '@/apis/http' +import type { + CreateAccountRequest, + CreateAccountResponse, + LoginRequest, + LoginResponse, + LogoutResponse, + MeResponse, +} from './auth.type' + +export const authApi = { + /** POST /v1/auth/login — ID/PW 로 로그인, access/refresh 토큰 발급 */ + login: async (body: LoginRequest): Promise => { + const res = await http.post('/v1/auth/login', body) + return res.data + }, + + /** POST /v1/auth/create — 신규 공급사 유저 계정 생성 */ + createAccount: async (body: CreateAccountRequest): Promise => { + const res = await http.post('/v1/auth/create', body) + return res.data + }, + + /** GET /v1/auth/me — 현재 로그인 유저 정보 (access token 필요) */ + me: async (): Promise => { + const res = await http.get('/v1/auth/me') + return res.data + }, + + /** POST /v1/auth/logout — 서버측 토큰 폐기(단일 세션) */ + logout: async (): Promise => { + const res = await http.post('/v1/auth/logout') + return res.data + }, +} diff --git a/frontend/src/apis/auth/auth.keys.ts b/frontend/src/apis/auth/auth.keys.ts new file mode 100644 index 0000000..3f19d6e --- /dev/null +++ b/frontend/src/apis/auth/auth.keys.ts @@ -0,0 +1,5 @@ +// 인증 도메인의 TanStack Query 키 팩토리. +export const authKeys = { + all: ['auth'] as const, + me: () => [...authKeys.all, 'me'] as const, +} diff --git a/frontend/src/apis/auth/auth.mutations.ts b/frontend/src/apis/auth/auth.mutations.ts new file mode 100644 index 0000000..1711229 --- /dev/null +++ b/frontend/src/apis/auth/auth.mutations.ts @@ -0,0 +1,55 @@ +// 인증 도메인의 변경(useMutation) 훅. +import { useMutation, useQueryClient } from '@tanstack/react-query' +import { tokenStorage } from '@/apis/tokenStorage' +import { authApi } from './auth.api' +import { authKeys } from './auth.keys' +import type { CreateAccountRequest, LoginResponse } from './auth.type' + +/** 로그인 폼이 다루는 파라미터 (UI 친화적인 camelCase) */ +export interface LoginParams { + id: string + password: string +} + +/** + * 로그인: 성공 시 토큰을 저장하고 me 캐시를 무효화한다. + */ +export function useLoginMutation() { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: async ({ id, password }) => { + const data = await authApi.login({ id, pw: password }) + tokenStorage.setTokens(data.access_token, data.refresh_token) + return data + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: authKeys.me() }) + }, + }) +} + +/** + * 로그아웃: 서버 토큰 폐기를 시도하고(실패해도) 로컬 토큰/캐시를 비운다. + */ +export function useLogoutMutation() { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: async () => { + try { + await authApi.logout() + } finally { + tokenStorage.clear() + } + }, + onSettled: () => { + queryClient.clear() + }, + }) +} + +/** 공급사 유저 계정 생성 */ +export function useCreateAccountMutation() { + return useMutation({ + mutationFn: (body: CreateAccountRequest) => authApi.createAccount(body), + }) +} diff --git a/frontend/src/apis/auth/auth.queries.ts b/frontend/src/apis/auth/auth.queries.ts new file mode 100644 index 0000000..4167ecb --- /dev/null +++ b/frontend/src/apis/auth/auth.queries.ts @@ -0,0 +1,20 @@ +// 인증 도메인의 조회(useQuery) 훅. +import { useQuery } from '@tanstack/react-query' +import { tokenStorage } from '@/apis/tokenStorage' +import { authApi } from './auth.api' +import { authKeys } from './auth.keys' +import { toAuthUser } from './auth.type' + +/** + * 현재 로그인 유저 정보 조회. + * 토큰이 있을 때만 활성화되며, AuthUser(카멜케이스)로 가공해 반환한다. + */ +export function useMeQuery() { + return useQuery({ + queryKey: authKeys.me(), + queryFn: authApi.me, + enabled: tokenStorage.hasToken(), + staleTime: 5 * 60 * 1000, // 5분 + select: toAuthUser, + }) +} diff --git a/frontend/src/apis/auth/auth.type.ts b/frontend/src/apis/auth/auth.type.ts new file mode 100644 index 0000000..7b152ea --- /dev/null +++ b/frontend/src/apis/auth/auth.type.ts @@ -0,0 +1,91 @@ +// 인증 API 의 요청/응답 타입. +// 와이어 포맷은 백엔드(snake_case)를 그대로 미러링한다. +import type { ApiResult } from '@/apis/types' + +/** 유저 권한 (supplier_users.role) */ +export const UserRole = { + USER: 1, + MANAGER: 2, +} as const +export type UserRole = (typeof UserRole)[keyof typeof UserRole] + +export const USER_ROLE_LABEL: Record = { + [UserRole.USER]: '일반', + [UserRole.MANAGER]: '매니저', +} + +// --- 로그인 --------------------------------------------------------------- +export interface LoginRequest { + id: string + pw: string +} + +export interface LoginResponse { + result: ApiResult + su_id: string + name: string + supplier_id: string + supplier_name: string + role: number + access_token: string + refresh_token: string +} + +// --- 계정 생성 ------------------------------------------------------------ +export interface CreateAccountRequest { + supplier_id: string + id: string + pw: string + name?: string + email?: string + contact_number?: string + role?: number +} + +export interface CreateAccountResponse { + result: ApiResult + su_id: string +} + +// --- 토큰 재발급 ---------------------------------------------------------- +export interface RefreshTokenResponse { + result: ApiResult + access_token: string +} + +// --- 내 정보 (GET /v1/auth/me) ------------------------------------------- +export interface MeResponse { + result: ApiResult + su_id: string + id: string + name: string + supplier_id: string + supplier_name: string + role: number +} + +// --- 로그아웃 ------------------------------------------------------------- +export interface LogoutResponse { + result: ApiResult +} + +/** 앱에서 다루기 편한 현재 유저 형태 (MeResponse 에서 파생) */ +export interface AuthUser { + suId: string + loginId: string + name: string + supplierId: string + supplierName: string + role: number +} + +export function toAuthUser(res: MeResponse): AuthUser { + return { + suId: res.su_id, + loginId: res.id, + name: res.name, + supplierId: res.supplier_id, + supplierName: res.supplier_name, + role: res.role, + } +} diff --git a/frontend/src/apis/auth/index.ts b/frontend/src/apis/auth/index.ts new file mode 100644 index 0000000..9d8f09d --- /dev/null +++ b/frontend/src/apis/auth/index.ts @@ -0,0 +1,11 @@ +// 인증 API 모듈 공개 표면. +export { authApi } from './auth.api' +export { authKeys } from './auth.keys' +export { useMeQuery } from './auth.queries' +export { + useLoginMutation, + useLogoutMutation, + useCreateAccountMutation, + type LoginParams, +} from './auth.mutations' +export * from './auth.type' diff --git a/frontend/src/apis/http.ts b/frontend/src/apis/http.ts new file mode 100644 index 0000000..9f6d179 --- /dev/null +++ b/frontend/src/apis/http.ts @@ -0,0 +1,118 @@ +// 공용 axios 인스턴스. +// - 요청 시 access token 을 Authorization 헤더에 주입 +// - 응답의 result.success=false 봉투를 ApiError 로 변환 +// - access token 만료(434) 시 refresh_token 으로 1회 자동 재발급 후 원요청 재시도 +// - refresh 실패 / 토큰 폐기(1203) / refresh 만료(435) 시 세션 종료 처리 +import axios, { AxiosError, type InternalAxiosRequestConfig } from 'axios' +import { tokenStorage } from './tokenStorage' +import { ApiError, ErrorCode, type ApiResult } from './types' + +const BASE_URL = import.meta.env.VITE_API_BASE_URL + +export const http = axios.create({ + baseURL: BASE_URL, + headers: { 'Content-Type': 'application/json' }, +}) + +// 인증 만료 시 앱이 처리할 핸들러 (로그인 페이지로 이동 등). App 에서 등록한다. +let onUnauthorized: (() => void) | null = null +export function setUnauthorizedHandler(handler: (() => void) | null): void { + onUnauthorized = handler +} + +function handleUnauthorized(): void { + tokenStorage.clear() + onUnauthorized?.() +} + +// --- 요청 인터셉터: access token 주입 ------------------------------------ +http.interceptors.request.use((config) => { + const token = tokenStorage.getAccessToken() + if (token) config.headers.Authorization = `Bearer ${token}` + return config +}) + +// --- 토큰 재발급 (단일 비행: 동시 요청은 하나의 refresh 만 공유) ---------- +let refreshPromise: Promise | null = null + +async function refreshAccessToken(): Promise { + const refreshToken = tokenStorage.getRefreshToken() + if (!refreshToken) { + throw new ApiError(ErrorCode.HTTP_REFRESH_TOKEN_EXPIRED, 'NO_REFRESH_TOKEN') + } + // 인터셉터 재귀를 피하려고 인스턴스가 아닌 기본 axios 로 호출한다. + const res = await axios.post<{ result: ApiResult; access_token?: string }>( + `${BASE_URL}/v1/auth/refresh_token`, + null, + { headers: { Authorization: `Bearer ${refreshToken}` } }, + ) + const { result, access_token } = res.data + if (!result.success || !access_token) { + throw new ApiError(result.code, result.desc) + } + tokenStorage.setAccessToken(access_token) + return access_token +} + +function toApiError(error: unknown): ApiError { + if (error instanceof ApiError) return error + if (axios.isAxiosError(error)) { + const result = (error.response?.data as { result?: ApiResult } | undefined)?.result + if (result) return new ApiError(result.code, result.desc, error.message) + // 토큰 관련 HTTPException 은 result 봉투 대신 {detail: "HTTP_*"} 형태로 온다 + const detail = (error.response?.data as { detail?: string } | undefined)?.detail + const status = error.response?.status ?? 0 + return new ApiError(status, detail ?? error.code ?? 'NETWORK_ERROR', error.message) + } + return new ApiError(ErrorCode.FAIL, 'UNKNOWN', String(error)) +} + +// --- 응답 인터셉터 ------------------------------------------------------- +http.interceptors.response.use( + (response) => { + // HTTP 200 이지만 result.success=false 인 비즈니스 에러를 ApiError 로 변환 + const result = (response.data as { result?: ApiResult } | undefined)?.result + if (result && !result.success) { + // 저장 토큰 무효화(로그아웃/타기기 로그인)는 200 + TOKEN_REVOKED 로 온다 → 세션 종료 + if (result.code === ErrorCode.TOKEN_REVOKED && tokenStorage.hasToken()) { + handleUnauthorized() + } + throw new ApiError(result.code, result.desc) + } + return response + }, + async (error: AxiosError) => { + const status = error.response?.status + const original = error.config as + | (InternalAxiosRequestConfig & { _retried?: boolean }) + | undefined + const bodyCode = (error.response?.data as { result?: ApiResult } | undefined)?.result?.code + const isRefreshCall = original?.url?.includes('/v1/auth/refresh_token') ?? false + + // access token 만료 → refresh 후 1회 재시도 + if (status === 434 && original && !original._retried && !isRefreshCall) { + original._retried = true + try { + refreshPromise ??= refreshAccessToken().finally(() => { + refreshPromise = null + }) + const newToken = await refreshPromise + original.headers.Authorization = `Bearer ${newToken}` + return http(original) + } catch (refreshError) { + handleUnauthorized() + throw toApiError(refreshError) + } + } + + // 인증 실패(헤더 누락 403/401, 잘못된 토큰 433/436, refresh 만료 435) / + // 토큰 폐기(200+1203 이 아닌 경로) → 세션 종료 + const isAuthFailStatus = + status === 401 || status === 403 || status === 433 || status === 435 || status === 436 + if (isAuthFailStatus || bodyCode === ErrorCode.TOKEN_REVOKED || isRefreshCall) { + handleUnauthorized() + } + + throw toApiError(error) + }, +) diff --git a/frontend/src/apis/index.ts b/frontend/src/apis/index.ts new file mode 100644 index 0000000..e707984 --- /dev/null +++ b/frontend/src/apis/index.ts @@ -0,0 +1,8 @@ +// apis 레이어 공개 표면. +export { http, setUnauthorizedHandler } from './http' +export { tokenStorage } from './tokenStorage' +export { ApiError, ErrorCode, isApiError, getApiErrorMessage } from './types' +export type { ApiResult, ApiEnvelope } from './types' + +export * from './auth' +export * from './negotiation' diff --git a/frontend/src/apis/negotiation/index.ts b/frontend/src/apis/negotiation/index.ts new file mode 100644 index 0000000..f82d7e4 --- /dev/null +++ b/frontend/src/apis/negotiation/index.ts @@ -0,0 +1,6 @@ +// 협상 API 모듈 공개 표면. +export { negotiationApi } from './negotiation.api' +export { negotiationKeys } from './negotiation.keys' +export { useSessionListQuery } from './negotiation.queries' +export { useParticipateMutation, useRejectMutation } from './negotiation.mutations' +export * from './negotiation.type' diff --git a/frontend/src/apis/negotiation/negotiation.api.ts b/frontend/src/apis/negotiation/negotiation.api.ts new file mode 100644 index 0000000..0f78a67 --- /dev/null +++ b/frontend/src/apis/negotiation/negotiation.api.ts @@ -0,0 +1,34 @@ +// 협상 엔드포인트 호출 함수 (순수 HTTP 레이어, React 의존 없음). +import { http } from '@/apis/http' +import type { + ParticipateResponse, + RejectRequest, + RejectResponse, + SessionListParams, + SessionListResponse, +} from './negotiation.type' + +export const negotiationApi = { + /** GET /v1/negotiation/sessions — 로그인 공급사의 협상 세션 목록(필터/정렬/페이지) */ + getSessions: async (params: SessionListParams = {}): Promise => { + const res = await http.get('/v1/negotiation/sessions', { params }) + return res.data + }, + + /** POST /v1/negotiation/sessions/{id}/participate — 협상 세션 참여 */ + participate: async (sessionId: string): Promise => { + const res = await http.post( + `/v1/negotiation/sessions/${sessionId}/participate`, + ) + return res.data + }, + + /** POST /v1/negotiation/sessions/{id}/reject — 협상 세션 거부 */ + reject: async (sessionId: string, body: RejectRequest): Promise => { + const res = await http.post( + `/v1/negotiation/sessions/${sessionId}/reject`, + body, + ) + return res.data + }, +} diff --git a/frontend/src/apis/negotiation/negotiation.keys.ts b/frontend/src/apis/negotiation/negotiation.keys.ts new file mode 100644 index 0000000..6461f70 --- /dev/null +++ b/frontend/src/apis/negotiation/negotiation.keys.ts @@ -0,0 +1,8 @@ +// 협상 도메인의 TanStack Query 키 팩토리. +import type { SessionListParams } from './negotiation.type' + +export const negotiationKeys = { + all: ['negotiation'] as const, + sessions: () => [...negotiationKeys.all, 'sessions'] as const, + sessionList: (params: SessionListParams) => [...negotiationKeys.sessions(), params] as const, +} diff --git a/frontend/src/apis/negotiation/negotiation.mutations.ts b/frontend/src/apis/negotiation/negotiation.mutations.ts new file mode 100644 index 0000000..947565f --- /dev/null +++ b/frontend/src/apis/negotiation/negotiation.mutations.ts @@ -0,0 +1,32 @@ +// 협상 도메인의 변경(useMutation) 훅. +import { useMutation, useQueryClient } from '@tanstack/react-query' +import { negotiationApi } from './negotiation.api' +import { negotiationKeys } from './negotiation.keys' +import type { RejectRequest } from './negotiation.type' + +/** + * 협상 세션 참여: 성공 시 세션 목록 캐시를 무효화해 상태를 갱신한다. + */ +export function useParticipateMutation() { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (sessionId: string) => negotiationApi.participate(sessionId), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: negotiationKeys.sessions() }) + }, + }) +} + +/** + * 협상 세션 거부: 성공 시 세션 목록 캐시를 무효화한다. + */ +export function useRejectMutation() { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: ({ sessionId, request }: { sessionId: string; request: RejectRequest }) => + negotiationApi.reject(sessionId, request), + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: negotiationKeys.sessions() }) + }, + }) +} diff --git a/frontend/src/apis/negotiation/negotiation.queries.ts b/frontend/src/apis/negotiation/negotiation.queries.ts new file mode 100644 index 0000000..38942cd --- /dev/null +++ b/frontend/src/apis/negotiation/negotiation.queries.ts @@ -0,0 +1,17 @@ +// 협상 도메인의 조회(useQuery) 훅. +import { keepPreviousData, useQuery } from '@tanstack/react-query' +import { negotiationApi } from './negotiation.api' +import { negotiationKeys } from './negotiation.keys' +import type { SessionListParams } from './negotiation.type' + +/** + * 협상 세션 목록 조회. + * 페이지 전환 시 이전 데이터를 유지해 깜빡임을 줄인다. + */ +export function useSessionListQuery(params: SessionListParams = {}) { + return useQuery({ + queryKey: negotiationKeys.sessionList(params), + queryFn: () => negotiationApi.getSessions(params), + placeholderData: keepPreviousData, + }) +} diff --git a/frontend/src/apis/negotiation/negotiation.type.ts b/frontend/src/apis/negotiation/negotiation.type.ts new file mode 100644 index 0000000..70ba859 --- /dev/null +++ b/frontend/src/apis/negotiation/negotiation.type.ts @@ -0,0 +1,80 @@ +// 협상 API 의 요청/응답 타입 + 코드값 enum. +// 와이어 포맷은 백엔드(snake_case)를 그대로 미러링한다. +import type { ApiResult } from '@/apis/types' + +/** 협상 세션 상태 (negotiation.sessions.status) */ +export const SessionStatus = { + CREATED: 1, // 협상생성(참여대기) + IN_PROGRESS: 2, // 협상중 + DONE: 3, // 협상완료 + NOT_PARTICIPATED: 4, // 미참여(마감) + REJECTED: 5, // 협상거부 +} as const +export type SessionStatus = (typeof SessionStatus)[keyof typeof SessionStatus] + +export const SESSION_STATUS_LABEL: Record = { + [SessionStatus.CREATED]: '협상생성', + [SessionStatus.IN_PROGRESS]: '협상중', + [SessionStatus.DONE]: '협상완료', + [SessionStatus.NOT_PARTICIPATED]: '미참여', + [SessionStatus.REJECTED]: '협상거부', +} + +/** 견적 타입 (negotiation.sessions.qt_type) */ +export const QtType = { + RENEGO: 1, // 재협상(1:1) + REQUOTE: 2, // 재견적(1:N) +} as const +export type QtType = (typeof QtType)[keyof typeof QtType] + +export const QT_TYPE_LABEL: Record = { + [QtType.RENEGO]: '재협상', + [QtType.REQUOTE]: '재견적', +} + +// --- 세션 목록 (GET /v1/negotiation/sessions) ---------------------------- +export interface SessionListParams { + status?: number // SessionStatus 코드 필터 + qt_type?: number // QtType 코드 필터 + order?: 'asc' | 'desc' // 마감(qt_end_time) 정렬, asc=임박순 + page?: number + page_size?: number +} + +export interface SessionListItem { + session_id: string + session_status: number + qt_type: number + qt_number: string + qt_end_time: string // ISO 8601 마감 시각 + item_code: string + item_name: string + model_name: string + maker_name: string +} + +export interface SessionListResponse { + result: ApiResult + items: SessionListItem[] + total: number + page: number + page_size: number +} + +// --- 참여 (POST /v1/negotiation/sessions/{id}/participate) ---------------- +export interface ParticipateResponse { + result: ApiResult + session_id: string +} + +// --- 거부 (POST /v1/negotiation/sessions/{id}/reject) --------------------- +// reject_reason: 프리셋(단종/품절) 라벨 또는 '기타' 직접 입력 텍스트. +// (백엔드 sessions.reject_reason 컬럼에 대응. 엔드포인트는 백엔드 추가 예정) +export interface RejectRequest { + reject_reason: string +} + +export interface RejectResponse { + result: ApiResult + session_id: string +} diff --git a/frontend/src/apis/tokenStorage.ts b/frontend/src/apis/tokenStorage.ts new file mode 100644 index 0000000..ebc5c3a --- /dev/null +++ b/frontend/src/apis/tokenStorage.ts @@ -0,0 +1,27 @@ +// JWT access/refresh 토큰의 영속 저장소. +// axios 인터셉터(http.ts)와 인증 mutation 이 공유한다. + +const ACCESS_KEY = 'negosium.accessToken' +const REFRESH_KEY = 'negosium.refreshToken' + +export const tokenStorage = { + getAccessToken: (): string | null => localStorage.getItem(ACCESS_KEY), + getRefreshToken: (): string | null => localStorage.getItem(REFRESH_KEY), + + setTokens: (accessToken: string, refreshToken: string): void => { + localStorage.setItem(ACCESS_KEY, accessToken) + localStorage.setItem(REFRESH_KEY, refreshToken) + }, + + /** refresh_token 으로 access_token 만 갱신할 때 사용 */ + setAccessToken: (accessToken: string): void => { + localStorage.setItem(ACCESS_KEY, accessToken) + }, + + clear: (): void => { + localStorage.removeItem(ACCESS_KEY) + localStorage.removeItem(REFRESH_KEY) + }, + + hasToken: (): boolean => localStorage.getItem(ACCESS_KEY) !== null, +} diff --git a/frontend/src/apis/types.ts b/frontend/src/apis/types.ts new file mode 100644 index 0000000..0115bf8 --- /dev/null +++ b/frontend/src/apis/types.ts @@ -0,0 +1,80 @@ +// 모든 API 응답이 공유하는 공통 봉투(envelope)와 에러 타입. +// 백엔드는 HTTP 200 으로 내려주면서 result.success=false 로 비즈니스 에러를 표현한다. + +/** 백엔드가 모든 응답에 공통으로 내려주는 처리 결과 */ +export interface ApiResult { + success: boolean + code: number + desc: string +} + +/** result 봉투를 포함하는 응답의 베이스 */ +export interface ApiEnvelope { + result: ApiResult +} + +/** 백엔드 ErrorType 코드 (backend/common 의 ErrorType 과 1:1 매핑) */ +export const ErrorCode = { + SUCCESS: 0, + FAIL: 1, + DB_RUN_FAILED: 10, + DB_ALREADY_SAME_KEY: 11, + JSON_PARSE_ERROR: 100, + INVALID_REQUEST_DATA: 101, + INTERNAL_EXCEPTION: 102, + HTTP_INVALID_CLIENT_REQUEST: 419, + HTTP_TO_MANY_REQUEST: 429, + HTTP_INVALID_CLIENT_ACCESS: 433, + HTTP_ACCESS_TOKEN_EXPIRED: 434, + HTTP_REFRESH_TOKEN_EXPIRED: 435, + HTTP_INVALID_TOKEN_ACCESS: 436, + ACCOUNT_INVALID_INFO: 1200, + ACCOUNT_ALREADY_EXIST: 1201, + ACCOUNT_BLOCKED_USER: 1202, + TOKEN_REVOKED: 1203, + NEGO_FORBIDDEN: 1300, + NEGO_NOT_PARTICIPABLE: 1301, + NEGO_QUOTATION_CLOSED: 1302, + NEGO_DEADLINE_PASSED: 1303, + NEGO_NOT_FOUND: 1304, +} as const + +export type ErrorCode = (typeof ErrorCode)[keyof typeof ErrorCode] + +/** code → 사용자에게 보여줄 한국어 메시지 */ +const API_ERROR_MESSAGES: Record = { + [ErrorCode.ACCOUNT_INVALID_INFO]: '아이디 또는 비밀번호가 올바르지 않습니다.', + [ErrorCode.ACCOUNT_ALREADY_EXIST]: '이미 존재하는 아이디입니다.', + [ErrorCode.ACCOUNT_BLOCKED_USER]: '비활성화된 계정입니다. 관리자에게 문의하세요.', + [ErrorCode.TOKEN_REVOKED]: '다른 기기에서 로그인되어 세션이 종료되었습니다.', + [ErrorCode.HTTP_ACCESS_TOKEN_EXPIRED]: '로그인이 만료되었습니다. 다시 로그인해주세요.', + [ErrorCode.HTTP_REFRESH_TOKEN_EXPIRED]: '로그인이 만료되었습니다. 다시 로그인해주세요.', + [ErrorCode.NEGO_FORBIDDEN]: '해당 협상에 접근할 권한이 없습니다.', + [ErrorCode.NEGO_NOT_PARTICIPABLE]: '참여할 수 없는 협상입니다.', + [ErrorCode.NEGO_QUOTATION_CLOSED]: '마감된 견적입니다.', + [ErrorCode.NEGO_DEADLINE_PASSED]: '협상 마감 시간이 지났습니다.', + [ErrorCode.NEGO_NOT_FOUND]: '협상을 찾을 수 없습니다.', +} + +/** API 에러: result.code(비즈니스) 또는 HTTP status 를 code 로 담는다 */ +export class ApiError extends Error { + readonly code: number + readonly desc: string + + constructor(code: number, desc: string, message?: string) { + super(message ?? API_ERROR_MESSAGES[code] ?? desc) + this.name = 'ApiError' + this.code = code + this.desc = desc + } +} + +export function isApiError(error: unknown): error is ApiError { + return error instanceof ApiError +} + +/** code 에 해당하는 사용자 안내 메시지 (없으면 기본 문구) */ +export function getApiErrorMessage(error: unknown, fallback = '요청 처리 중 오류가 발생했습니다.'): string { + if (isApiError(error)) return API_ERROR_MESSAGES[error.code] ?? error.message ?? fallback + return fallback +} From 7bdd10207adf0d7c47d4d5beec2212d4b970a3be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=AF=BC=ED=97=8C?= Date: Thu, 18 Jun 2026 13:12:16 +0900 Subject: [PATCH 08/14] =?UTF-8?q?feat(frontend):=20=EA=B3=B5=ED=86=B5=20?= =?UTF-8?q?=ED=86=A0=EC=8A=A4=ED=8A=B8(sonner)=C2=B7=EB=AA=A8=EB=8B=AC=20?= =?UTF-8?q?=EC=BB=B4=ED=8F=AC=EB=84=8C=ED=8A=B8=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - sonner 기반 토스트 래퍼(lib/toast): error/info/success/warning, 프로젝트 디자인 토큰으로 스타일 통일. Toaster 를 provider 에 마운트 - 공통 Modal 컴포넌트: 반투명 배경 + 배경 클릭/ESC 닫기 - core/Provider import 케이싱 정리(provider) Co-Authored-By: Claude Opus 4.8 (1M context) --- frontend/package-lock.json | 11 +++++ frontend/package.json | 1 + frontend/src/components/Modal.tsx | 30 ++++++++++++ frontend/src/components/index.ts | 2 + frontend/src/core/provider.tsx | 8 +++- frontend/src/lib/index.ts | 1 + frontend/src/lib/toast.ts | 77 +++++++++++++++++++++++++++++++ frontend/src/main.tsx | 2 +- 8 files changed, 130 insertions(+), 2 deletions(-) create mode 100644 frontend/src/components/Modal.tsx create mode 100644 frontend/src/lib/toast.ts diff --git a/frontend/package-lock.json b/frontend/package-lock.json index e1dc0fd..a62cc79 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -17,6 +17,7 @@ "slate": "^0.124.1", "slate-history": "^0.113.1", "slate-react": "^0.124.2", + "sonner": "^2.0.7", "zustand": "^5.0.14" }, "devDependencies": { @@ -3260,6 +3261,16 @@ "slate-dom": ">=0.119.1" } }, + "node_modules/sonner": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/sonner/-/sonner-2.0.7.tgz", + "integrity": "sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w==", + "license": "MIT", + "peerDependencies": { + "react": "^18.0.0 || ^19.0.0 || ^19.0.0-rc", + "react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-rc" + } + }, "node_modules/source-map-js": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", diff --git a/frontend/package.json b/frontend/package.json index 37a1496..d25a5a7 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -22,6 +22,7 @@ "slate": "^0.124.1", "slate-history": "^0.113.1", "slate-react": "^0.124.2", + "sonner": "^2.0.7", "zustand": "^5.0.14" }, "devDependencies": { diff --git a/frontend/src/components/Modal.tsx b/frontend/src/components/Modal.tsx new file mode 100644 index 0000000..9ace715 --- /dev/null +++ b/frontend/src/components/Modal.tsx @@ -0,0 +1,30 @@ +import { type ReactNode, useEffect } from 'react' + +export interface ModalProps { + children?: ReactNode + onClose: () => void +} + +// 공통 모달: 반투명 배경 + 배경 클릭/ESC 로 닫기. +export function Modal({ children, onClose }: ModalProps) { + const handleBackdropClick = (e: React.MouseEvent) => { + if (e.target === e.currentTarget) onClose() + } + + useEffect(() => { + const handleEscKey = (e: KeyboardEvent) => { + if (e.key === 'Escape') onClose() + } + document.addEventListener('keydown', handleEscKey) + return () => document.removeEventListener('keydown', handleEscKey) + }, [onClose]) + + return ( +
+ {children} +
+ ) +} diff --git a/frontend/src/components/index.ts b/frontend/src/components/index.ts index 78e677c..ac75f31 100644 --- a/frontend/src/components/index.ts +++ b/frontend/src/components/index.ts @@ -1,5 +1,7 @@ export { Button } from '@/components/Button' export type { ButtonProps, ButtonVariant, ButtonSize } from '@/components/Button' export { Input } from '@/components/Input' +export { Modal } from '@/components/Modal' +export type { ModalProps } from '@/components/Modal' export { Logo } from '@/components/Logo' export type { LogoProps, LogoVariant } from '@/components/Logo' diff --git a/frontend/src/core/provider.tsx b/frontend/src/core/provider.tsx index 2749278..1419e65 100644 --- a/frontend/src/core/provider.tsx +++ b/frontend/src/core/provider.tsx @@ -1,5 +1,6 @@ import { type ReactNode } from 'react' import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { Toaster } from 'sonner' const queryClient = new QueryClient({ defaultOptions: { @@ -12,5 +13,10 @@ const queryClient = new QueryClient({ }) export function Provider({ children }: { children: ReactNode }) { - return {children} + return ( + + {children} + + + ) } diff --git a/frontend/src/lib/index.ts b/frontend/src/lib/index.ts index af3e974..b8bb278 100644 --- a/frontend/src/lib/index.ts +++ b/frontend/src/lib/index.ts @@ -2,3 +2,4 @@ export { cn } from '@/lib/cn' export type { ClassValue } from '@/lib/cn' export { interactive } from '@/lib/interactive' +export { toast } from '@/lib/toast' diff --git a/frontend/src/lib/toast.ts b/frontend/src/lib/toast.ts new file mode 100644 index 0000000..a403f0f --- /dev/null +++ b/frontend/src/lib/toast.ts @@ -0,0 +1,77 @@ +// 전역 토스트 (sonner 래퍼). 프로젝트 디자인 토큰으로 스타일을 맞춘다. +// 는 core/provider.tsx 에 마운트되어 있어야 한다. +import { toast as sonnerToast, type ExternalToast } from 'sonner' + +type ToastOptions = ExternalToast + +const baseStyle = { + fontFamily: 'var(--font-sans)', + fontSize: '18px', + fontWeight: 600, + letterSpacing: '-0.28px', + borderRadius: '8px', + padding: '18px 24px', + backgroundColor: 'var(--neutral-00)', + color: 'var(--neutral-90)', + boxShadow: '0px 4px 12px rgba(0, 0, 0, 0.08)', + minWidth: '440px', + wordBreak: 'keep-all' as const, + overflowWrap: 'break-word' as const, + whiteSpace: 'pre-wrap' as const, +} + +const errorStyle = { + ...baseStyle, + border: '1px solid var(--negative)', + color: 'var(--negative)', + backgroundColor: '#fdf2f3', +} + +const infoStyle = { + ...baseStyle, + border: '1px solid var(--info)', + color: 'var(--info)', + backgroundColor: '#eff5ff', +} + +const successStyle = { + ...baseStyle, + border: '1px solid var(--success)', + color: '#0f766e', + backgroundColor: '#f0fdf9', +} + +const warningStyle = { + ...baseStyle, + border: '1px solid var(--neutral-60)', + color: 'var(--neutral-70)', + backgroundColor: 'var(--neutral-10)', +} + +export const toast = { + error: (message: string, options?: ToastOptions) => + sonnerToast.error(message, { + ...options, + style: { ...errorStyle, ...options?.style }, + duration: options?.duration ?? 4000, + }), + info: (message: string, options?: ToastOptions) => + sonnerToast.info(message, { + ...options, + style: { ...infoStyle, ...options?.style }, + duration: options?.duration ?? 3000, + }), + success: (message: string, options?: ToastOptions) => + sonnerToast.success(message, { + ...options, + style: { ...successStyle, ...options?.style }, + duration: options?.duration ?? 3500, + }), + // 완료 안내: 체크 아이콘(success)에 중립 톤 스타일 + warning: (message: string, options?: ToastOptions) => + sonnerToast.success(message, { + ...options, + style: { ...warningStyle, ...options?.style }, + duration: options?.duration ?? 3500, + }), +} diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index af7833d..b0f2ed4 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -1,6 +1,6 @@ import { StrictMode } from 'react' import { createRoot } from 'react-dom/client' -import { Provider } from '@/core/Provider' +import { Provider } from '@/core/provider' import '@/index.css' import App from '@/App' From c0d224ef212917834f9a3ff2bf4525adec2c1c57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=AF=BC=ED=97=8C?= Date: Thu, 18 Jun 2026 13:12:23 +0900 Subject: [PATCH 09/14] =?UTF-8?q?feat(frontend):=20=EC=9D=B8=EC=A6=9D=20?= =?UTF-8?q?=EC=97=B0=EB=8F=99=20(=EB=A1=9C=EA=B7=B8=EC=9D=B8/=EB=A1=9C?= =?UTF-8?q?=EA=B7=B8=EC=95=84=EC=9B=83/=EB=82=B4=EC=A0=95=EB=B3=B4/?= =?UTF-8?q?=EB=9D=BC=EC=9A=B0=ED=8A=B8=20=EA=B0=80=EB=93=9C)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 로그인 실연동: 성공 시 access/refresh 토큰 저장, me 캐시 무효화 - SidebarFooter: useMeQuery 로 공급사명 표시, useLogoutMutation 로 로그아웃 - RequireAuth 가드로 /list·/chat 보호, 토큰 없으면 로그인으로 - 인증 만료/폐기 시 로그인 페이지로 이동(setUnauthorizedHandler) - LoginPage: 이미 로그인 상태면 목록으로 리다이렉트 Co-Authored-By: Claude Opus 4.8 (1M context) --- frontend/src/App.tsx | 25 +++++++++++++++++-- .../features/auth/components/RequireAuth.tsx | 12 +++++++++ .../auth/components/SidebarFooter.tsx | 18 ++++++++++--- .../features/auth/hooks/useLoginMutation.ts | 15 ++--------- frontend/src/features/auth/index.ts | 1 + frontend/src/pages/LoginPage.tsx | 7 ++++++ 6 files changed, 60 insertions(+), 18 deletions(-) create mode 100644 frontend/src/features/auth/components/RequireAuth.tsx diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 363b765..a864750 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,14 +1,35 @@ import { createBrowserRouter, RouterProvider } from 'react-router' +import { setUnauthorizedHandler } from '@/apis' +import { RequireAuth } from '@/features/auth' import LoginPage from '@/pages/LoginPage' import ListPage from '@/pages/ListPage' import ChatPage from '@/pages/ChatPage' const router = createBrowserRouter([ { path: '/', element: }, - { path: '/list', element: }, - { path: '/chat', element: }, + { + path: '/list', + element: ( + + + + ), + }, + { + path: '/chat', + element: ( + + + + ), + }, ]) +// 토큰 만료/폐기로 인증이 끊기면 로그인 페이지로 이동시킨다. +setUnauthorizedHandler(() => { + void router.navigate('/') +}) + function App() { return } diff --git a/frontend/src/features/auth/components/RequireAuth.tsx b/frontend/src/features/auth/components/RequireAuth.tsx new file mode 100644 index 0000000..fc4608c --- /dev/null +++ b/frontend/src/features/auth/components/RequireAuth.tsx @@ -0,0 +1,12 @@ +import type { ReactNode } from 'react' +import { Navigate } from 'react-router' +import { tokenStorage } from '@/apis' + +// 토큰이 없으면 로그인 페이지로 보낸다 (인증 영역 가드). +// 토큰이 있으나 만료/폐기된 경우는 요청 시 인터셉터가 세션을 종료시킨다. +export function RequireAuth({ children }: { children: ReactNode }) { + if (!tokenStorage.hasToken()) { + return + } + return <>{children} +} diff --git a/frontend/src/features/auth/components/SidebarFooter.tsx b/frontend/src/features/auth/components/SidebarFooter.tsx index aeca1d5..eda61dc 100644 --- a/frontend/src/features/auth/components/SidebarFooter.tsx +++ b/frontend/src/features/auth/components/SidebarFooter.tsx @@ -1,18 +1,30 @@ +import { useNavigate } from 'react-router' +import { useLogoutMutation, useMeQuery } from '@/apis' import { Button } from '@/components' // 사이드바 하단: 공급사명 + 로그아웃 export function SidebarFooter() { + const navigate = useNavigate() + const { data: user } = useMeQuery() + const logout = useLogoutMutation() + + const handleLogout = () => { + logout.mutate(undefined, { + onSuccess: () => navigate('/'), + }) + } + return (
- {/* TODO: 공급사명 (auth store 연동) */} - - + {user?.supplierName ?? '-'}
diff --git a/frontend/src/features/auth/hooks/useLoginMutation.ts b/frontend/src/features/auth/hooks/useLoginMutation.ts index 3295d41..76fbeee 100644 --- a/frontend/src/features/auth/hooks/useLoginMutation.ts +++ b/frontend/src/features/auth/hooks/useLoginMutation.ts @@ -1,13 +1,2 @@ -import { useMutation } from '@tanstack/react-query' - -export interface LoginParams { - id: string - password: string -} - -// 임시 stub (검증만 통과하면 성공). TODO: 로그인 API 연동 -export function useLoginMutation() { - return useMutation({ - mutationFn: async () => {}, - }) -} +// 실제 로그인 API 연동은 apis/auth 로 이전됨. 기존 import 경로 호환을 위해 재노출한다. +export { useLoginMutation, type LoginParams } from '@/apis/auth' diff --git a/frontend/src/features/auth/index.ts b/frontend/src/features/auth/index.ts index 2b91506..e940c43 100644 --- a/frontend/src/features/auth/index.ts +++ b/frontend/src/features/auth/index.ts @@ -1,2 +1,3 @@ export { LoginForm } from '@/features/auth/components/LoginForm' export { SidebarFooter } from '@/features/auth/components/SidebarFooter' +export { RequireAuth } from '@/features/auth/components/RequireAuth' diff --git a/frontend/src/pages/LoginPage.tsx b/frontend/src/pages/LoginPage.tsx index 8543179..dc36dbb 100644 --- a/frontend/src/pages/LoginPage.tsx +++ b/frontend/src/pages/LoginPage.tsx @@ -1,7 +1,14 @@ +import { Navigate } from 'react-router' +import { tokenStorage } from '@/apis' import { Logo } from '@/components' import { LoginForm } from '@/features/auth' export function LoginPage() { + // 이미 로그인된 상태면 목록으로 + if (tokenStorage.hasToken()) { + return + } + return (
From fab8e5aa53ca03204ea6b43f49892e48f35ac9bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=AF=BC=ED=97=8C?= Date: Thu, 18 Jun 2026 13:12:31 +0900 Subject: [PATCH 10/14] =?UTF-8?q?feat(frontend):=20=ED=98=91=EC=83=81=20?= =?UTF-8?q?=EB=AA=A9=EB=A1=9D/=EC=B0=B8=EC=97=AC/=EA=B1=B0=EB=B6=80=20?= =?UTF-8?q?=EC=97=B0=EB=8F=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 세션 목록을 useSessionListQuery 로 서버 조회(필터·정렬·페이지 위임), mock 제거. 정수 코드↔한국어 라벨 변환 어댑터(list/lib/adapter) - 협상 참여: useParticipateMutation, 성공 시 채팅 진입·실패 토스트 - 거부: 사유 입력 팝업(RejectPopup) + useRejectMutation, 상태별 차단 안내 - 선택/상태 검증을 토스트로 일원화(ActionSection 은 버튼만 담당) Co-Authored-By: Claude Opus 4.8 (1M context) --- .../list/components/ActionSection.tsx | 39 +++++- .../features/list/components/RejectPopup.tsx | 124 ++++++++++++++++++ .../list/containers/ContentContainer.tsx | 85 +++++++++++- frontend/src/features/list/hooks/useList.ts | 45 +++---- frontend/src/features/list/lib/adapter.ts | 41 ++++++ frontend/src/features/list/mocks/mockItems.ts | 115 ---------------- 6 files changed, 298 insertions(+), 151 deletions(-) create mode 100644 frontend/src/features/list/components/RejectPopup.tsx create mode 100644 frontend/src/features/list/lib/adapter.ts delete mode 100644 frontend/src/features/list/mocks/mockItems.ts diff --git a/frontend/src/features/list/components/ActionSection.tsx b/frontend/src/features/list/components/ActionSection.tsx index 36ce83c..5a52efc 100644 --- a/frontend/src/features/list/components/ActionSection.tsx +++ b/frontend/src/features/list/components/ActionSection.tsx @@ -5,17 +5,42 @@ const PILL = 'text-lg font-semibold whitespace-nowrap ' + interactive -export function ActionSection() { +export interface ActionSectionProps { + isParticipating: boolean + isRejecting: boolean + onParticipate: () => void + onReject: () => void +} + +export function ActionSection({ + isParticipating, + isRejecting, + onParticipate, + onReject, +}: ActionSectionProps) { return (
- {/* TODO: 협상 참여 동작 연동 */} - - {/* TODO: 거부 동작 연동 */} + diff --git a/frontend/src/features/list/components/RejectPopup.tsx b/frontend/src/features/list/components/RejectPopup.tsx new file mode 100644 index 0000000..d7f2d45 --- /dev/null +++ b/frontend/src/features/list/components/RejectPopup.tsx @@ -0,0 +1,124 @@ +import { useState } from 'react' +import { Modal } from '@/components' +import { cn, interactive } from '@/lib' + +const REASONS = ['단종', '품절', '기타'] as const + +export interface RejectPopupProps { + onClose: () => void + /** 최종 거부 사유 (프리셋 라벨 또는 기타 입력 텍스트) */ + onSubmit: (reason: string) => void +} + +// 거부 사유 입력 팝업 (단종/품절/기타). +export function RejectPopup({ onClose, onSubmit }: RejectPopupProps) { + const [selectedReason, setSelectedReason] = useState(null) + const [customReason, setCustomReason] = useState('') + const [showError, setShowError] = useState(false) + + const isEtcOpen = selectedReason === '기타' + const isSubmitDisabled = !selectedReason || (isEtcOpen && !customReason.trim()) + + const handleReasonClick = (reason: string) => { + setShowError(false) + if (selectedReason === reason) { + setSelectedReason(null) + setCustomReason('') + } else { + setSelectedReason(reason) + if (reason !== '기타') setCustomReason('') + } + } + + const handleSubmit = () => { + if (isEtcOpen && !customReason.trim()) { + setShowError(true) + return + } + if (isSubmitDisabled || !selectedReason) return + + const reason = isEtcOpen ? customReason.trim() : selectedReason + onSubmit(reason) + onClose() + } + + return ( + +
+ {/* 헤더 */} +

+ 거부 사유를 입력해주세요 +

+ + {/* 사유 선택 */} +
+ {REASONS.map((reason) => ( + + ))} +
+ + {/* 기타 입력 + 에러 */} +
+
+