From ea5376820cb9d62af4f23babef834f32776ee13f Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Wed, 14 Oct 2026 15:36:36 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=ED=86=A0=EC=8A=A4=ED=8C=90=20=ED=86=A0?= =?UTF-8?q?=EC=8A=A4=20=EB=A1=9C=EA=B7=B8=EC=9D=B8(mTLS=20=ED=86=A0?= =?UTF-8?q?=ED=81=B0=20=EA=B5=90=ED=99=98=C2=B7=EC=97=B0=EA=B2=B0=20?= =?UTF-8?q?=EB=81=8A=EA=B8=B0=20=EC=BD=9C=EB=B0=B1)=EA=B3=BC=20=EC=A2=8B?= =?UTF-8?q?=EC=95=84=EC=9A=94=C2=B7=EB=8C=93=EA=B8=80=20=EB=8B=A4=EC=8B=9C?= =?UTF-8?q?=20=EC=97=B4=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 7 ++ .gitignore | 7 +- TODO.md | 4 + backend/common/enums.py | 1 + backend/config/settings.py | 7 ++ backend/crud/user_crud.py | 9 ++ backend/postgres-init/init.sql | 9 +- backend/router/v1/auth/account.py | 37 +++++- backend/router/v1/auth/protocol.py | 15 +++ backend/services/auth_service.py | 38 +++++- backend/services/external/toss_login.py | 52 ++++++++ backend/tests/test_auth_toss.py | 87 +++++++++++++ compose.yaml | 2 + docs/앱인토스_진행계획.md | 12 +- .../api/client/@tanstack/react-query.gen.ts | 38 +++++- frontend/src/api/client/index.ts | 4 +- frontend/src/api/client/sdk.gen.ts | 26 +++- frontend/src/api/client/types.gen.ts | 114 +++++++++++++++++- frontend/src/b/BLayout.tsx | 5 +- frontend/src/b/Post.tsx | 29 ++--- frontend/src/b/Sheets.tsx | 72 +++++++++-- frontend/src/lib/analytics.ts | 2 +- frontend/src/lib/platform.ts | 9 +- 23 files changed, 530 insertions(+), 56 deletions(-) create mode 100644 backend/services/external/toss_login.py create mode 100644 backend/tests/test_auth_toss.py diff --git a/.env.example b/.env.example index 78144b6..425aa54 100644 --- a/.env.example +++ b/.env.example @@ -23,6 +23,13 @@ PORT=9810 JWT_ACCESS_SECRET= JWT_REFRESH_SECRET= +# ── 백엔드: 앱인토스 토스 로그인. 인증서·키는 저장소 최상위 secrets/toss/ 에 두고(커밋 안 함) 컨테이너 안 경로를 적는다 +# compose 는 secrets/toss 를 backend 의 /run/secrets/toss 에 읽기 전용으로 붙인다 +TOSS_MTLS_CERT=/run/secrets/toss/nalssigak_public.crt +TOSS_MTLS_KEY=/run/secrets/toss/nalssigak_private.key +# 연결 끊기 콜백 Basic Auth "아이디:비밀번호" — 콘솔에 넣은 값과 같게. 비우면 콜백을 모두 거절한다 +TOSS_UNLINK_AUTH= + # ── 배포(compose): 비우면 로컬 기본값. 킹서버 예: FRONT_PORT=30040, API_BIND=127.0.0.1:9810, PG_BIND=127.0.0.1:5440, REDIS_BIND=127.0.0.1:6390 FRONT_PORT= API_BIND= diff --git a/.gitignore b/.gitignore index 7f38461..d98028b 100644 --- a/.gitignore +++ b/.gitignore @@ -22,4 +22,9 @@ backend/openapi.json # 디자인 도구(impeccable) 캐시 .impeccable/ -/zzz \ No newline at end of file +/zzz +# 인증서·키: 서버와 각자 PC 에만 둔다 (토스 mTLS 등) +secrets/ +*.pem +*.key +*.crt diff --git a/TODO.md b/TODO.md index f213860..ed4ff31 100644 --- a/TODO.md +++ b/TODO.md @@ -167,3 +167,7 @@ | [ ] | **[결정 필요]** 각 순위가 점수 순이 아니라 보임 — 순위가 점수 × 중요도라 환기각 92점(하)이 5위, 골프각 89점이 3위, 빨래각 83점이 2위. 각 탭 받침대·스토리에서 높은 점수가 뒤에 있어 어색함. 점수를 순위대로 보여줄지, 중요도 가중을 줄일지 | 화면 직접 확인 중 발견 (10/12) | `backend/services/calc/index_calc.py` (`PRIORITY_WEIGHT`), `frontend/src/b/GakPage.tsx` | | [x] | 노을 점수 29점(잿빛)인데 결론 '나가 볼 만해요' — 결론이 구름 분포만 보고 공기 보정(가시거리·습도)을 안 봤음 → 공기 보정 0.7배 미만이면 결론 한 단계 낮추고 이유에 공기 표시, '해 질 무렵(N시) 예보 기준' 표시. 운영 DB에 `sky_score.air` 칸 추가 필요(배포 때 `init.sql`의 ALTER) | 사용자 지적 (10/12, 분당구) | `backend/services/sky_service.py` (`day_verdict`, `build_plan`), `backend/services/calc/sky_score.py` (`air_note`) | | [x] | 노을 탭 다시 짜기 → 시안 A(사용자 선택): 히어로 '오늘은 애매해요 / 18:10쯤 가장 붉어요 / 쉬운 이유', 내일 안내 바로 아래, 숫자는 '자세히', 시간표에 가장 붉을 때 — 처음 보면 '그래서 가?'에서 멈춤: 히어로 18:00이 무슨 시각인지 없음, 결론 카드가 좋은 말·나쁜 말을 섞음, 구름 %·예보 모델 수 같은 전문 용어, '가장 붉을 때'가 시간표에 없음, '내일이 더 나아요'가 맨 아래. 시안 먼저 보고 결정 | 사용자 지적 (10/12) | `frontend/src/b/SkyPage.tsx`, `backend/services/calc/sky_score.py` (`reason`) | +| [ ] | 토스 로그인 운영 설정 — 서버 `secrets/toss/`에 인증서·키 복사, 서버 `.env`에 `TOSS_MTLS_CERT`·`TOSS_MTLS_KEY`·`TOSS_UNLINK_AUTH`(값은 `.env.example` 참고). compose 마운트는 넣어 둠. 로컬에서 토스 API 호출 시 `4050 인증서버에 등록된 미니앱이 아닙니다` → 콘솔 토스 로그인 설정 후 다시 확인 | 토스 로그인 구현(10/14) | `compose.yaml`, `.env.example`, `backend/config/settings.py` | +| [ ] | **[결정 필요]** 토스 연결 끊기 처리 — 지금은 UNLINK·탈퇴 모두 토큰만 무효로 함. 토스 탈퇴(`WITHDRAWAL_TOSS`·`WITHDRAWAL_TERMS`) 때 계정·댓글을 지울지 | 토스 로그인 구현(10/14) | `backend/services/auth_service.py` | +| [ ] | 토스 로그인 문구 검토 — '토스로 로그인', '토스로 로그인했어요', '토스 로그인을 마치지 못했어요. 한 번 더 눌러 주세요.', 기본 닉네임 '토스1234'(userKey 끝 4자리) | 토스 로그인 구현(10/14) | `frontend/src/b/Sheets.tsx`, `backend/services/auth_service.py` | +| [ ] | 댓글 신고·차단 — 앱인토스 필수 아님(신고·차단 필수는 채팅·만남·중고거래만, 서비스 오픈 정책·서비스별 주의사항). 만들지 않기로 함(10/14). 검수에서 요청이 오면 만든다 | 토스 로그인 구현(10/14) | | diff --git a/backend/common/enums.py b/backend/common/enums.py index 19d43ec..fac6bae 100644 --- a/backend/common/enums.py +++ b/backend/common/enums.py @@ -159,3 +159,4 @@ class RefType(CodeEnum): class AuthProvider(CodeEnum): LOCAL = 1 GOOGLE = 2 + TOSS = 3 diff --git a/backend/config/settings.py b/backend/config/settings.py index 1c26d87..ca974c8 100644 --- a/backend/config/settings.py +++ b/backend/config/settings.py @@ -36,6 +36,13 @@ class Settings(BaseSettings): jwt_access_minutes: int = 60 jwt_refresh_days: int = 30 + # 앱인토스 토스 로그인. 인증서·키는 저장소 밖(secrets/toss)에 두고 경로만 받는다 + toss_api_base: str = "https://apps-in-toss-api.toss.im" + toss_mtls_cert: str = "" + toss_mtls_key: str = "" + # 연결 끊기 콜백의 Basic Auth 값 "아이디:비밀번호". 콘솔에 넣은 값과 같아야 한다 + toss_unlink_auth: str = "" + @field_validator("data_go_kr_service_key") @classmethod def _decode_service_key(cls, v: str) -> str: diff --git a/backend/crud/user_crud.py b/backend/crud/user_crud.py index 6cd95fa..28c68c3 100644 --- a/backend/crud/user_crud.py +++ b/backend/crud/user_crud.py @@ -12,6 +12,9 @@ class UserCRUD: async def by_login_id(self, s: AsyncSession, login_id: str) -> Optional[User]: return await s.scalar(select(User).where(User.login_id == login_id, User.deleted.is_(False))) + async def by_provider_uid(self, s: AsyncSession, provider: int, provider_uid: str) -> Optional[User]: + return await s.scalar(select(User).where(User.provider == provider, User.provider_uid == provider_uid, User.deleted.is_(False))) + async def get(self, s: AsyncSession, user_id: uuid.UUID) -> Optional[User]: user = await s.get(User, user_id) return user if user is not None and not user.deleted else None @@ -22,6 +25,12 @@ class UserCRUD: await s.flush() return user + async def create_social(self, s: AsyncSession, provider: int, provider_uid: str, login_id: str, nickname: str) -> User: + user = User(login_id=login_id, password=None, provider_uid=provider_uid, nickname=nickname, provider=provider) + s.add(user) + await s.flush() + return user + async def update(self, s: AsyncSession, user_id: uuid.UUID, values: dict) -> Optional[User]: user = await self.get(s, user_id) if user is None: diff --git a/backend/postgres-init/init.sql b/backend/postgres-init/init.sql index 14452c1..2b2dfba 100644 --- a/backend/postgres-init/init.sql +++ b/backend/postgres-init/init.sql @@ -184,13 +184,13 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_post_feed_scope ON public.post (feed_date, -- 사람·반응 (좋아요·저장·댓글은 로그인 필요, 보내기는 누구나) --- 사용자. 일반(아이디·비밀번호) 또는 구글 로그인. 이름·전화번호는 받지 않는다. +-- 사용자. 일반(아이디·비밀번호), 구글, 토스(앱인토스) 로그인. 이름·전화번호는 받지 않는다. CREATE TABLE IF NOT EXISTS public.users ( user_id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - provider SMALLINT NOT NULL DEFAULT 1, -- AuthProvider: 1=일반 2=구글 - login_id VARCHAR(64) NOT NULL, -- 일반은 아이디, 구글은 google_ + provider SMALLINT NOT NULL DEFAULT 1, -- AuthProvider: 1=일반 2=구글 3=토스 + login_id VARCHAR(64) NOT NULL, -- 일반은 아이디, 구글은 google_, 토스는 toss_ password VARCHAR(255) NULL, -- bcrypt 해시. 구글 계정은 NULL - provider_uid VARCHAR(255) NULL, -- 구글 sub. 일반 계정은 NULL + provider_uid VARCHAR(255) NULL, -- 구글 sub 또는 토스 userKey. 일반 계정은 NULL nickname VARCHAR(30) NOT NULL, -- 댓글에 보이는 이름 character VARCHAR(20) NOT NULL DEFAULT 'rabbit', -- 프로필 캐릭터: rabbit·bear·dog·sun·moon·cloud color VARCHAR(20) NOT NULL DEFAULT 'orange', -- 프로필 배경색: orange·blue·green·purple·pink·brown @@ -203,6 +203,7 @@ CREATE TABLE IF NOT EXISTS public.users ( ); CREATE UNIQUE INDEX IF NOT EXISTS uq_users_login_id ON public.users (login_id) WHERE deleted = FALSE; CREATE UNIQUE INDEX IF NOT EXISTS uq_users_google ON public.users (provider_uid) WHERE provider = 2 AND deleted = FALSE; +CREATE UNIQUE INDEX IF NOT EXISTS uq_users_toss ON public.users (provider_uid) WHERE provider = 3 AND deleted = FALSE; CREATE TABLE IF NOT EXISTS public.post_like ( post_id BIGINT NOT NULL, diff --git a/backend/router/v1/auth/account.py b/backend/router/v1/auth/account.py index c99dd7a..2ee0c07 100644 --- a/backend/router/v1/auth/account.py +++ b/backend/router/v1/auth/account.py @@ -1,10 +1,17 @@ -from fastapi import APIRouter, Depends +import base64 +import binascii +import secrets +from typing import Optional + +from fastapi import APIRouter, Depends, Header, HTTPException from common.auth import current_user from common.database.model.models import User from common.enums import AuthProvider, ErrorType +from common.logger import LOG from common.models.errors import error_info -from router.v1.auth.protocol import Me, Req_Login, Req_Refresh, Req_Signup, Req_UpdateMe, Res_Auth, Res_Logout, Res_Me +from config.settings import settings +from router.v1.auth.protocol import Me, Req_Login, Req_Refresh, Req_Signup, Req_TossLogin, Req_TossUnlink, Req_UpdateMe, Res_Auth, Res_Logout, Res_Me, Res_TossUnlink from services.auth_service import AuthService router = APIRouter(prefix="/v1/auth", tags=["auth"]) @@ -33,6 +40,32 @@ async def login(req: Req_Login, service: AuthService = Depends()) -> Res_Auth: return _auth(err, user, service) +@router.post("/toss", response_model=Res_Auth, response_model_exclude_none=True, summary="토스 로그인 (앱인토스 TossAuth.login 의 authorizationCode·referrer)") +async def toss(req: Req_TossLogin, service: AuthService = Depends()) -> Res_Auth: + err, user = await service.toss_login(req.authorization_code, req.referrer) + return _auth(err, user, service) + + +def _check_toss_basic(authorization: Optional[str]) -> None: + """콘솔에 넣은 "아이디:비밀번호" 와 같은지 본다. 값이 비어 있으면 모두 거절한다.""" + given = "" + if authorization and authorization.startswith("Basic "): + try: + given = base64.b64decode(authorization.removeprefix("Basic "), validate=True).decode() + except (binascii.Error, UnicodeDecodeError): + given = "" + if not settings.toss_unlink_auth or not secrets.compare_digest(given.encode(), settings.toss_unlink_auth.encode()): + raise HTTPException(status_code=401, detail=ErrorType.AUTH_FAILED.name) + + +@router.post("/toss/unlink", response_model=Res_TossUnlink, response_model_exclude_none=True, summary="토스 연결 끊기 콜백 (토스 서버가 Basic Auth 로 부름)") +async def toss_unlink(req: Req_TossUnlink, authorization: Optional[str] = Header(None), service: AuthService = Depends()) -> Res_TossUnlink: + _check_toss_basic(authorization) + LOG.info(f"[auth] toss unlink: {req.referrer}") + err = await service.toss_unlink(str(req.userKey)) + return Res_TossUnlink() if err is ErrorType.SUCCESS else Res_TossUnlink(result=error_info(err)) + + @router.post("/refresh", response_model=Res_Auth, response_model_exclude_none=True, summary="토큰 재발급") async def refresh(req: Req_Refresh, service: AuthService = Depends()) -> Res_Auth: err, user = await service.refresh(req.refresh_token) diff --git a/backend/router/v1/auth/protocol.py b/backend/router/v1/auth/protocol.py index f8bb6bc..f80ffcd 100644 --- a/backend/router/v1/auth/protocol.py +++ b/backend/router/v1/auth/protocol.py @@ -15,6 +15,17 @@ class Req_Login(Req_WebPacketProtocol): password: str +class Req_TossLogin(Req_WebPacketProtocol): + authorization_code: str + referrer: str + + +class Req_TossUnlink(Req_WebPacketProtocol): + """토스가 보내는 모양 그대로 (camelCase)""" + userKey: int + referrer: str + + class Req_Refresh(Req_WebPacketProtocol): refresh_token: str @@ -41,6 +52,10 @@ class Res_Auth(Res_WebPacketProtocol): me: Optional[Me] = None +class Res_TossUnlink(Res_WebPacketProtocol): + pass + + class Res_Logout(Res_WebPacketProtocol): pass diff --git a/backend/services/auth_service.py b/backend/services/auth_service.py index 92b3423..3642f15 100644 --- a/backend/services/auth_service.py +++ b/backend/services/auth_service.py @@ -7,9 +7,11 @@ from fastapi import Depends from common.auth import PASSWORD_MAX_BYTES, decode, hash_password, issue_tokens, verify_password from common.database.db_session_manager import DB_SESSION_MNG from common.database.model.models import User -from common.enums import ErrorType +from common.enums import AuthProvider, ErrorType +from common.logger import LOG from config.settings import settings from crud.user_crud import UserCRUD +from services.external import toss_login LOGIN_ID = re.compile(r"^[a-z0-9_]{4,20}$") PASSWORD_MIN = 8 @@ -17,6 +19,7 @@ NICKNAME = re.compile(r"^\S.{0,10}\S$") CHARACTERS = ("rabbit", "bear", "dog", "sun", "moon", "cloud") COLORS = ("orange", "blue", "green", "purple", "pink", "brown") MOODS = ("clear", "partly", "cloudy", "rain", "thunder", "snow", "fog", "rainbow") +TOSS_REFERRERS = ("DEFAULT", "SANDBOX") class AuthService: @@ -47,6 +50,39 @@ class AuthService: return ErrorType.AUTH_FAILED, None return ErrorType.SUCCESS, user + async def toss_login(self, authorization_code: str, referrer: str) -> tuple[ErrorType, Optional[User]]: + """토스 userKey 로 계정을 찾고, 없으면 만든다. 이름·전화번호 같은 개인정보는 받지 않는다.""" + if not authorization_code or referrer not in TOSS_REFERRERS: + return ErrorType.INVALID_INPUT, None + try: + key = str(await toss_login.user_key(authorization_code, referrer)) + except toss_login.TossLoginError as e: + LOG.error(f"[auth] toss login: {e}") + return ErrorType.AUTH_FAILED, None + provider = AuthProvider.TOSS.value + err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_provider_uid(s, provider, key)) + if err is not ErrorType.SUCCESS: + return err, None + if user is None: + err, user = await DB_SESSION_MNG.execute_lambda_write( + lambda s: self.crud.create_social(s, provider, key, f"toss_{key}", f"토스{key[-4:]}") + ) + if err is not ErrorType.SUCCESS: + # 같은 사람이 동시에 두 번 들어온 경우 먼저 만든 계정을 쓴다 + err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_provider_uid(s, provider, key)) + if err is not ErrorType.SUCCESS or user is None: + return err if err is not ErrorType.SUCCESS else ErrorType.DB_ERROR, None + if user.status != 1: + return ErrorType.AUTH_FAILED, None + return ErrorType.SUCCESS, user + + async def toss_unlink(self, user_key: str) -> ErrorType: + """토스에서 연결을 끊으면 그 계정의 모든 토큰을 무효로 만든다. 계정이 없어도 성공으로 본다.""" + err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_provider_uid(s, AuthProvider.TOSS.value, user_key)) + if err is not ErrorType.SUCCESS or user is None: + return err + return await self.logout(user) + async def refresh(self, refresh_token: str) -> tuple[ErrorType, Optional[User]]: claims = decode(refresh_token, settings.jwt_refresh_secret, "refresh") if claims is None: diff --git a/backend/services/external/toss_login.py b/backend/services/external/toss_login.py new file mode 100644 index 0000000..f39c902 --- /dev/null +++ b/backend/services/external/toss_login.py @@ -0,0 +1,52 @@ +import ssl +from functools import lru_cache + +import httpx + +from common.logger import LOG +from config.settings import settings + +TIMEOUT_SEC = 10.0 +_PATH = "/api-partner/v1/apps-in-toss/user/oauth2" + + +class TossLoginError(Exception): + pass + + +@lru_cache(maxsize=1) +def _mtls() -> ssl.SSLContext: + if not settings.toss_mtls_cert or not settings.toss_mtls_key: + raise TossLoginError("TOSS_MTLS_CERT / TOSS_MTLS_KEY is empty") + ctx = ssl.create_default_context() + ctx.load_cert_chain(settings.toss_mtls_cert, settings.toss_mtls_key) + return ctx + + +def _success(res: httpx.Response, step: str) -> dict: + """토스는 업무 오류도 HTTP 200 + resultType=FAIL 로 준다. 로그에 토큰·개인정보를 남기지 않는다.""" + res.raise_for_status() + body = res.json() + if body.get("resultType") != "SUCCESS": + err = body.get("error") + code = err.get("errorCode") if isinstance(err, dict) else err + raise TossLoginError(f"{step} failed: {code}") + return body["success"] + + +async def user_key(authorization_code: str, referrer: str) -> int: + """앱에서 받은 인가 코드로 토스 토큰을 받고, 그 토큰으로 이 앱 전용 사용자 키(userKey)만 읽는다.""" + try: + async with httpx.AsyncClient(base_url=settings.toss_api_base, verify=_mtls(), timeout=TIMEOUT_SEC, follow_redirects=False) as client: + token = _success( + await client.post(f"{_PATH}/generate-token", json={"authorizationCode": authorization_code, "referrer": referrer}), + "generate-token", + ) + me = _success( + await client.get(f"{_PATH}/login-me", headers={"Authorization": f"Bearer {token['accessToken']}"}), + "login-me", + ) + return int(me["userKey"]) + except (httpx.HTTPError, ssl.SSLError, OSError, KeyError, ValueError) as e: + LOG.error(f"[toss] login failed: {type(e).__name__}") + raise TossLoginError(type(e).__name__) from None diff --git a/backend/tests/test_auth_toss.py b/backend/tests/test_auth_toss.py new file mode 100644 index 0000000..78587b8 --- /dev/null +++ b/backend/tests/test_auth_toss.py @@ -0,0 +1,87 @@ +import base64 + +import httpx +import pytest +from httpx import ASGITransport, AsyncClient + +from config.settings import settings +from router.router import app +from services.external import toss_login + + +def client(): + return AsyncClient(transport=ASGITransport(app=app), base_url="http://test") + + +@pytest.fixture +def toss(monkeypatch): + """토스 서버 대신 코드별로 정해 둔 userKey 를 돌려준다.""" + keys = {"code-a": 1234567, "code-b": 7654321} + + async def fake_user_key(code: str, referrer: str) -> int: + if code not in keys: + raise toss_login.TossLoginError("generate-token failed: invalid_grant") + return keys[code] + + monkeypatch.setattr(toss_login, "user_key", fake_user_key) + monkeypatch.setattr(settings, "toss_unlink_auth", "toss:unlink-secret") + + +def _basic(value: str) -> dict: + return {"Authorization": "Basic " + base64.b64encode(value.encode()).decode()} + + +@pytest.mark.anyio +async def test_toss_login_creates_once_and_reuses(toss): + async with client() as c: + first = (await c.post("/v1/auth/toss", json={"authorization_code": "code-a", "referrer": "SANDBOX"})).json() + again = (await c.post("/v1/auth/toss", json={"authorization_code": "code-a", "referrer": "DEFAULT"})).json() + other = (await c.post("/v1/auth/toss", json={"authorization_code": "code-b", "referrer": "DEFAULT"})).json() + me = (await c.get("/v1/auth/me", headers={"Authorization": f"Bearer {first['access_token']}"})).json() + assert first["result"]["success"] is True and first["me"]["provider"] == 3 + assert first["me"]["login_id"] == again["me"]["login_id"] == "toss_1234567" + assert other["me"]["login_id"] == "toss_7654321" + assert me["me"]["login_id"] == "toss_1234567" + + +@pytest.mark.anyio +async def test_toss_login_rejects_bad_code_and_referrer(toss): + async with client() as c: + bad_code = (await c.post("/v1/auth/toss", json={"authorization_code": "nope", "referrer": "DEFAULT"})).json() + bad_ref = (await c.post("/v1/auth/toss", json={"authorization_code": "code-a", "referrer": "WEB"})).json() + assert bad_code["result"]["desc"] == "AUTH_FAILED" + assert bad_ref["result"]["desc"] == "INVALID_INPUT" + + +@pytest.mark.anyio +async def test_toss_unlink_needs_basic_auth_and_kills_tokens(toss): + async with client() as c: + login = (await c.post("/v1/auth/toss", json={"authorization_code": "code-a", "referrer": "DEFAULT"})).json() + body = {"userKey": 1234567, "referrer": "UNLINK"} + assert (await c.post("/v1/auth/toss/unlink", json=body)).status_code == 401 + assert (await c.post("/v1/auth/toss/unlink", json=body, headers=_basic("toss:wrong"))).status_code == 401 + ok = await c.post("/v1/auth/toss/unlink", json=body, headers=_basic("toss:unlink-secret")) + unknown = await c.post("/v1/auth/toss/unlink", json={"userKey": 1, "referrer": "WITHDRAWAL_TOSS"}, headers=_basic("toss:unlink-secret")) + me = await c.get("/v1/auth/me", headers={"Authorization": f"Bearer {login['access_token']}"}) + assert ok.status_code == 200 and ok.json()["result"]["success"] is True + assert unknown.status_code == 200 + assert me.status_code == 401 + + +@pytest.mark.anyio +async def test_toss_unlink_rejects_all_when_not_configured(toss, monkeypatch): + monkeypatch.setattr(settings, "toss_unlink_auth", "") + async with client() as c: + r = await c.post("/v1/auth/toss/unlink", json={"userKey": 1, "referrer": "UNLINK"}, headers=_basic(":")) + assert r.status_code == 401 + + +def test_success_reads_toss_wrapper(): + ok = httpx.Response(200, json={"resultType": "SUCCESS", "success": {"userKey": 1}}, request=httpx.Request("GET", "https://x")) + fail = httpx.Response(200, json={"resultType": "FAIL", "error": {"errorCode": "4050", "reason": "x"}}, request=httpx.Request("GET", "https://x")) + grant = httpx.Response(200, json={"error": "invalid_grant"}, request=httpx.Request("GET", "https://x")) + assert toss_login._success(ok, "login-me") == {"userKey": 1} + with pytest.raises(toss_login.TossLoginError, match="4050"): + toss_login._success(fail, "login-me") + with pytest.raises(toss_login.TossLoginError, match="invalid_grant"): + toss_login._success(grant, "generate-token") diff --git a/compose.yaml b/compose.yaml index 67d2d47..263130c 100644 --- a/compose.yaml +++ b/compose.yaml @@ -43,6 +43,8 @@ services: REDIS_PORT: "6379" ports: - "${API_BIND:-9810}:9800" + volumes: + - ./secrets/toss:/run/secrets/toss:ro depends_on: postgres: condition: service_healthy diff --git a/docs/앱인토스_진행계획.md b/docs/앱인토스_진행계획.md index 894fa70..4de61dc 100644 --- a/docs/앱인토스_진행계획.md +++ b/docs/앱인토스_진행계획.md @@ -7,7 +7,7 @@ - 토스판은 **WebView**로 만든다. React Native(Granite)는 쓰지 않는다. RN은 토스와 무관한 독립 앱으로만 진행한다. - 프로젝트를 따로 만들지 않는다. 지금 `frontend/` 하나에서 **웹 빌드**와 **토스 빌드** 두 가지를 낸다. - 웹을 먼저 출시하고, 토스판은 그 뒤에 낸다. -- 토스판 1차는 **보기 전용**이다. 로그인·좋아요·댓글은 끈다. +- 토스판 1차부터 **토스 로그인**을 넣는다(10/14 결정). 좋아요·댓글도 웹과 같이 켠다. 아이디 로그인은 토스판에서 쓰지 않는다. ## 구조 @@ -31,7 +31,8 @@ frontend/ |---|---|---|---| | 공유 | `navigator.share` (이미지 카드 + 링크) | 이미지는 기기에 저장(`File.saveBase64`), 링크는 `Share.createLink` + `Share.sendMessage`. SDK 공유는 글만 보낼 수 있다 | `frontend/src/b/Sheets.tsx` | | 위치 | `navigator.geolocation` | `Device.getLocation`. 처음 들어올 때는 권한 창을 띄우지 않고, 이미 허용한 사람만 위치로 맞춘다. '내 위치' 버튼을 누를 때 권한 창을 띄운다 | `frontend/src/b/region.tsx` | -| 로그인·좋아요·댓글 | 있음 | 숨김 (상단 로그인, 카드의 하트·댓글·좋아요 수, 두 번 눌러 좋아요, 지역 창 아래 로그인 줄) | `frontend/src/b/Post.tsx`, `frontend/src/b/Sheets.tsx`, `frontend/src/b/BLayout.tsx` | +| 로그인 | 아이디·비밀번호 | 토스 로그인(`TossAuth.login` → `POST /v1/auth/toss`). 토스가 주는 개인정보는 받지 않고 `userKey`만 저장한다 | `frontend/src/b/Sheets.tsx` (`TossLoginSheet`), `backend/services/external/toss_login.py` | +| 좋아요·댓글 | 있음 | 있음. 신고·차단은 필수가 아니라 만들지 않는다(검수에서 요청하면 만든다) | `frontend/src/b/Post.tsx`, `frontend/src/b/Sheets.tsx` | | 네이버 지도 링크 | 있음 | 장소 이름만 표시. Q4 답이 '예외 해당'이면 되돌린다 | `frontend/src/b/ui.tsx` (`MapLink`) | | 밤 배경 | 어두운 남색 | Q3 답 보고 결정 | `frontend/src/b/BLayout.tsx` | | GA4 | `index.html`에 태그 | Q2 답 보고 결정 | `frontend/index.html`, `frontend/src/lib/analytics.ts` | @@ -72,10 +73,13 @@ frontend/ ### 2. 플랫폼 분기 - [x] `src/lib/platform.ts`: `IS_TOSS`, `SOCIAL`, `tossShare`, `tossLocation` -- [x] 공유·위치·로그인·좋아요·댓글·지도 링크를 토스에서 분기 +- [x] 공유·위치·지도 링크를 토스에서 분기 +- [x] 토스 로그인: 백엔드 `POST /v1/auth/toss`, 연결 끊기 콜백 `POST /v1/auth/toss/unlink`, 프론트 `TossLoginSheet` (10/14) +- [ ] 운영 서버에 mTLS 인증서 두기, `.env`에 `TOSS_MTLS_CERT`·`TOSS_MTLS_KEY`·`TOSS_UNLINK_AUTH`, compose 마운트 +- [ ] 콘솔: 토스 로그인 약관 동의·동의 항목·연결 끊기 콜백 등록 - [ ] Q1~Q3 답에 따라 라우터·GA4·밤 배경을 처리한다 (지금은 웹과 같음) -완료 기준: 웹은 지금과 똑같이 동작한다. 토스에서는 로그인 관련 화면이 하나도 보이지 않는다. +완료 기준: 웹은 지금과 똑같이 동작한다. 토스에서는 토스 로그인으로만 로그인한다. ### 3. 토스판 피드 줄이기 — 결정 대기 diff --git a/frontend/src/api/client/@tanstack/react-query.gen.ts b/frontend/src/api/client/@tanstack/react-query.gen.ts index 1cb695b..dab67ad 100644 --- a/frontend/src/api/client/@tanstack/react-query.gen.ts +++ b/frontend/src/api/client/@tanstack/react-query.gen.ts @@ -3,8 +3,8 @@ import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; -import { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from '../sdk.gen'; -import type { AddCommentData, AddCommentError, AddCommentResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse } from '../types.gen'; +import { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, toss, tossUnlink, unlikeComment, unlikePost, unsavePost, updateMe } from '../sdk.gen'; +import type { AddCommentData, AddCommentError, AddCommentResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, TossData, TossError, TossResponse, TossUnlinkData, TossUnlinkError, TossUnlinkResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse } from '../types.gen'; export type QueryKey = [ Pick & { @@ -379,6 +379,40 @@ export const loginMutation = (options?: Partial>): UseMutatio return mutationOptions; }; +/** + * 토스 로그인 (앱인토스 TossAuth.login 의 authorizationCode·referrer) + */ +export const tossMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await toss({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * 토스 연결 끊기 콜백 (토스 서버가 Basic Auth 로 부름) + */ +export const tossUnlinkMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await tossUnlink({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + /** * 토큰 재발급 */ diff --git a/frontend/src/api/client/index.ts b/frontend/src/api/client/index.ts index bb70c7a..7656463 100644 --- a/frontend/src/api/client/index.ts +++ b/frontend/src/api/client/index.ts @@ -1,4 +1,4 @@ // This file is auto-generated by @hey-api/openapi-ts -export { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe } from './sdk.gen'; -export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqRefresh, type ReqSignup, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, type SlotPoint, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostError, type UnlikePostErrors, type UnlikePostResponse, type UnlikePostResponses, type UnsavePostData, type UnsavePostError, type UnsavePostErrors, type UnsavePostResponse, type UnsavePostResponses, type UpdateMeData, type UpdateMeError, type UpdateMeErrors, type UpdateMeResponse, type UpdateMeResponses, type ValidationError, type WarningData, WarningLevel, WarningType, type WatchEvent, type WatchNow, type WatchSlot, type WatchSunset, type WatchTimeline, type WeatherSlot, type WeekDay, type WeekGak, type WeekRankDay, type WeekRankItem, type WeekSlide } from './types.gen'; +export { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, toss, tossUnlink, unlikeComment, unlikePost, unsavePost, updateMe } from './sdk.gen'; +export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqRefresh, type ReqSignup, type ReqTossLogin, type ReqTossUnlink, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResTossUnlink, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, type SlotPoint, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TossData, type TossError, type TossErrors, type TossResponse, type TossResponses, type TossUnlinkData, type TossUnlinkError, type TossUnlinkErrors, type TossUnlinkResponse, type TossUnlinkResponses, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostError, type UnlikePostErrors, type UnlikePostResponse, type UnlikePostResponses, type UnsavePostData, type UnsavePostError, type UnsavePostErrors, type UnsavePostResponse, type UnsavePostResponses, type UpdateMeData, type UpdateMeError, type UpdateMeErrors, type UpdateMeResponse, type UpdateMeResponses, type ValidationError, type WarningData, WarningLevel, WarningType, type WatchEvent, type WatchNow, type WatchSlot, type WatchSunset, type WatchTimeline, type WeatherSlot, type WeekDay, type WeekGak, type WeekRankDay, type WeekRankItem, type WeekSlide } from './types.gen'; diff --git a/frontend/src/api/client/sdk.gen.ts b/frontend/src/api/client/sdk.gen.ts index 3e6ebe7..fcdecd0 100644 --- a/frontend/src/api/client/sdk.gen.ts +++ b/frontend/src/api/client/sdk.gen.ts @@ -2,7 +2,7 @@ import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client'; import { client } from './client.gen'; -import type { AddCommentData, AddCommentErrors, AddCommentResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses } from './types.gen'; +import type { AddCommentData, AddCommentErrors, AddCommentResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, TossData, TossErrors, TossResponses, TossUnlinkData, TossUnlinkErrors, TossUnlinkResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses } from './types.gen'; export type Options = Options2 & { /** @@ -127,6 +127,30 @@ export const login = (options: Options(options: Options): RequestResult => (options.client ?? client).post({ + url: '/v1/auth/toss', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +/** + * 토스 연결 끊기 콜백 (토스 서버가 Basic Auth 로 부름) + */ +export const tossUnlink = (options: Options): RequestResult => (options.client ?? client).post({ + url: '/v1/auth/toss/unlink', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + /** * 토큰 재발급 */ diff --git a/frontend/src/api/client/types.gen.ts b/frontend/src/api/client/types.gen.ts index 17f3389..35a49f8 100644 --- a/frontend/src/api/client/types.gen.ts +++ b/frontend/src/api/client/types.gen.ts @@ -123,13 +123,20 @@ export type ArticleSummary = { /** * AuthProvider */ -export const AuthProvider = { /** +export const AuthProvider = { + /** * LOCAL */ - LOCAL: 1, /** + LOCAL: 1, + /** * GOOGLE */ - GOOGLE: 2 } as const; + GOOGLE: 2, + /** + * TOSS + */ + TOSS: 3 +} as const; /** * AuthProvider @@ -1247,6 +1254,36 @@ export type ReqSignup = { nickname: string; }; +/** + * Req_TossLogin + */ +export type ReqTossLogin = { + /** + * Authorization Code + */ + authorization_code: string; + /** + * Referrer + */ + referrer: string; +}; + +/** + * Req_TossUnlink + * + * 토스가 보내는 모양 그대로 (camelCase) + */ +export type ReqTossUnlink = { + /** + * Userkey + */ + userKey: number; + /** + * Referrer + */ + referrer: string; +}; + /** * Req_UpdateMe */ @@ -1760,6 +1797,17 @@ export type ResSkyRanking = { items?: Array; }; +/** + * Res_TossUnlink + */ +export type ResTossUnlink = { + result?: ErrorInfo; + /** + * Msg + */ + msg?: string | null; +}; + /** * Res_WatchSummary */ @@ -2635,6 +2683,10 @@ export type WatchNow = { * Rain 2H */ rain_2h?: boolean | null; + /** + * Thunder + */ + thunder?: boolean | null; /** * Text */ @@ -3472,6 +3524,62 @@ export type LoginResponses = { export type LoginResponse = LoginResponses[keyof LoginResponses]; +export type TossData = { + body: ReqTossLogin; + path?: never; + query?: never; + url: '/v1/auth/toss'; +}; + +export type TossErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type TossError = TossErrors[keyof TossErrors]; + +export type TossResponses = { + /** + * Successful Response + */ + 200: ResAuth; +}; + +export type TossResponse = TossResponses[keyof TossResponses]; + +export type TossUnlinkData = { + body: ReqTossUnlink; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path?: never; + query?: never; + url: '/v1/auth/toss/unlink'; +}; + +export type TossUnlinkErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type TossUnlinkError = TossUnlinkErrors[keyof TossUnlinkErrors]; + +export type TossUnlinkResponses = { + /** + * Successful Response + */ + 200: ResTossUnlink; +}; + +export type TossUnlinkResponse = TossUnlinkResponses[keyof TossUnlinkResponses]; + export type RefreshData = { body: ReqRefresh; path?: never; diff --git a/frontend/src/b/BLayout.tsx b/frontend/src/b/BLayout.tsx index 9b52c03..fca9a25 100644 --- a/frontend/src/b/BLayout.tsx +++ b/frontend/src/b/BLayout.tsx @@ -2,7 +2,6 @@ import { useCallback, useEffect, useMemo, useState, type ReactNode } from 'react import { NavLink, Outlet, useLocation } from 'react-router' import { useIsFetching, useQuery } from '@tanstack/react-query' import { getSeasonWeekOptions } from '../api/client/@tanstack/react-query.gen' -import { SOCIAL } from '../lib/platform' import { cx } from '../lib/utils' import { kindOfHour, kst, seasonOf, type TimeKind } from './lib' import './b.css' @@ -61,7 +60,7 @@ function TopBar() { {locateStatus === 'locating' ? : region.name} - {SOCIAL && (mePending ? ( + {mePending ? ( ) : me ? ( - ))} + )} ) } diff --git a/frontend/src/b/Post.tsx b/frontend/src/b/Post.tsx index b65fd72..06f77fc 100644 --- a/frontend/src/b/Post.tsx +++ b/frontend/src/b/Post.tsx @@ -1,7 +1,6 @@ import { useEffect, useRef, useState, type CSSProperties, type MouseEvent, type ReactNode } from 'react' import { createPortal } from 'react-dom' import { PostType, SlotTone, type GakSlide, type HoursSlide, type PlanSlide, type PostData, type ResFeed, type RowsSlide, type SunsetSlide, type WeekSlide } from '../api/client/types.gen' -import { SOCIAL } from '../lib/platform' import { cx } from '../lib/utils' import { cardBg, clockShort, fall } from './lib' import type { SlideBg } from './types' @@ -361,7 +360,7 @@ function FullCard({ post }: PostProps) { } const onTap = (e: MouseEvent) => { - if (!SOCIAL || (e.target as HTMLElement).closest('button')) return + if ((e.target as HTMLElement).closest('button')) return const now = Date.now() if (now - lastTap.current < 320) { if (liked && loggedIn) setPop((p) => p + 1) @@ -436,30 +435,24 @@ function FullCard({ post }: PostProps) { )}
- {SOCIAL && ( - <> - - - - )} + +
- {SOCIAL &&

좋아요 {likeCount.toLocaleString()}개

} +

좋아요 {likeCount.toLocaleString()}개

날씨각 {post.caption}

- {SOCIAL && ( - - )} +

오늘

) diff --git a/frontend/src/b/Sheets.tsx b/frontend/src/b/Sheets.tsx index 840f950..1546a83 100644 --- a/frontend/src/b/Sheets.tsx +++ b/frontend/src/b/Sheets.tsx @@ -16,12 +16,13 @@ import { loginMutation, meQueryKey, signupMutation, + tossMutation, unlikeCommentMutation, updateMeMutation, } from '../api/client/@tanstack/react-query.gen' -import type { CommentData, Factor, ResAuth, ResCommentList, ResIndexDetail } from '../api/client/types.gen' +import { AuthProvider, type CommentData, type Factor, type ResAuth, type ResCommentList, type ResIndexDetail } from '../api/client/types.gen' import { track } from '../lib/analytics' -import { IS_TOSS, SOCIAL, tossShare } from '../lib/platform' +import { IS_TOSS, tossLogin, tossShare } from '../lib/platform' import { cx } from '../lib/utils' import { useAuth } from './authContext' import { ago, ARTICLE_CAT, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from './lib' @@ -840,6 +841,7 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () } if (me) return + if (IS_TOSS) return const field = 'w-full rounded-[14px] border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-3' return ( @@ -875,6 +877,56 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () ) } +/** 앱인토스는 토스 로그인만 쓸 수 있다 */ +function TossLoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () => void }) { + const [error, setError] = useState('') + const [opening, setOpening] = useState(false) + const toss = useMutation(tossMutation()) + const pending = opening || toss.isPending + + const start = async () => { + setError('') + setOpening(true) + let code: Awaited> + try { + code = await tossLogin() + } catch (e) { + console.error('[login] toss', e) + setError('토스 로그인을 마치지 못했어요. 한 번 더 눌러 주세요.') + return + } finally { + setOpening(false) + } + toss.mutate( + { body: { authorization_code: code.authorizationCode, referrer: code.referrer } }, + { + onSuccess: (res) => { + if (!res.result?.success || !res.access_token) return setError('토스 로그인을 마치지 못했어요. 한 번 더 눌러 주세요.') + setTokens(res.access_token, res.refresh_token ?? null) + track('login', { method: 'toss' }) + onLoggedIn() + }, + onError: () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.'), + }, + ) + } + + return ( + +

좋아요·댓글은 로그인한 뒤에 할 수 있어요.

+

+ {error} +

+ + + + ) +} + /* ---------- 내 정보: 캐릭터·닉네임·로그아웃 ---------- */ function MeSheet({ onDone }: { onDone: () => void }) { const { me, logout } = useAuth() @@ -910,7 +962,7 @@ function MeSheet({ onDone }: { onDone: () => void }) {
-

{me.login_id}(으)로 로그인했어요

+

{me.provider === AuthProvider.TOSS ? '토스로 로그인했어요' : `${me.login_id}(으)로 로그인했어요`}

내 캐릭터

@@ -1048,14 +1100,12 @@ function RegionSheet({ onDone }: { onDone: () => void }) { ))} - {SOCIAL && ( -

- {me ? `${me.nickname}(으)로 로그인했어요` : '로그인하면 좋아요·댓글을 쓸 수 있어요'} - -

- )} +

+ {me ? `${me.nickname}(으)로 로그인했어요` : '로그인하면 좋아요·댓글을 쓸 수 있어요'} + +

) } diff --git a/frontend/src/lib/analytics.ts b/frontend/src/lib/analytics.ts index b8d2cf9..69065c1 100644 --- a/frontend/src/lib/analytics.ts +++ b/frontend/src/lib/analytics.ts @@ -3,7 +3,7 @@ type Events = { view_gak: { index_id: number; gak_name: string; score: number; rank: number } select_content: { content_type: 'article'; item_id: number; category: string } share: { content_type: 'image'; item_id: string; method: 'share_sheet' | 'download'; ratio: string } - login: { method: 'id' } + login: { method: 'id' | 'toss' } sign_up: { method: 'id' } region_change: { region_name: string; method: 'list' | 'location' } } diff --git a/frontend/src/lib/platform.ts b/frontend/src/lib/platform.ts index 4f859ce..5b8ce52 100644 --- a/frontend/src/lib/platform.ts +++ b/frontend/src/lib/platform.ts @@ -1,9 +1,6 @@ /** 웹/앱인토스 차이를 모으는 곳. 토스 SDK 는 토스 빌드(`vite build --mode toss`)에서만 불러온다 */ export const IS_TOSS = import.meta.env.MODE === 'toss' -/** 로그인·좋아요·댓글. 토스판 1차는 보기 전용이라 끈다 */ -export const SOCIAL = !IS_TOSS - const TOSS_APP = 'intoss://nalssigak' // 웹 빌드에서는 이 분기가 지워져 SDK 가 번들에 들어가지 않는다 @@ -31,6 +28,12 @@ export async function tossShare(image: Blob, fileName: string, title: string): P return saved ? 'saved' : 'link-only' } +/** 토스: 토스 로그인 창을 띄우고 서버로 보낼 인가 코드를 받는다 */ +export async function tossLogin() { + const { TossAuth } = await sdk() + return TossAuth.login() +} + export type TossLocation = { lat: number; lon: number } | 'denied' /** 토스: 위치를 읽는다. 권한이 없으면 ask 일 때만 권한 창을 띄운다 */