[feat] solution/backend: 카카오 로그인 — 회원번호로 카톡 채널을 코드 없이 잇는다

★★ 챗봇 웹훅의 user.properties.appUserId 는 카카오 로그인의 회원번호와 **같은 값**이다
(카카오 공식 문서, 봇에 앱키가 물려 있을 때). 그래서 카카오로 로그인만 해 두면 채널에
말을 거는 순간 누구인지 알 수 있고, 6자리 코드 절차가 필요 없어진다.

- external/kakao_identity: 액세스 토큰을 카카오에 되물어 확인한다. ★ 응답의 app_id 를
  우리 앱과 대조하는 것이 구글의 aud 검사에 해당한다 — 이게 없으면 남의 앱 토큰으로
  우리 계정이 된다. 이름·이메일은 동의 항목이라 못 받아도 로그인은 되게 했다
- auth_service.kakao_login: google_login 과 같은 세 갈래. 이메일이 겹쳐도 자동으로
  잇지 않는다(DECISIONS 1 — 계정 선점)
- kakao_link_service.link_by_app_user_id: 자동 매칭. ★ 이미 다른 사장님에게 묶인
  카톡은 빼앗지 않는다 — 조용히 빼앗으면 앞사람이 남의 가게를 보게 된다
- ★ 코드 경로는 그대로 둔다: id/pw·구글 가입자에겐 appUserId 가 없고, 봇에 앱키가
  안 물린 환경에서는 값 자체가 안 온다

★ 함께 고친 것 — services/agent/tools.py 가 사라진 site_payload._DEFAULT_THEME 를
보고 있었다(c690862 템플릿 정의 통합에서 이름이 없어졌는데 이 한 줄만 남았다).
**대화의 섹션 기능이 통째로 죽어 있었고** 웹훅이 AttributeError 를 삼켜 "지금은
처리할 수 없어요" 로만 보였다 — common/template_catalog.industry_of 로 바꿨다.

test_kakao_link·test_kakao_webhook·test_agent_runtime·test_auth 194 passed
(신규 4: 자동 매칭·미가입자·빼앗지 않음·재진입). 남은 1건은 컨테이너에 실제
GOOGLE_CLIENT_ID 가 있어 나는 기존 실패다.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
HyeongBaeYangandClaude Opus 5 committed 2026-09-30 16:27:54 +09:00
1 parent 283970b2ba
commit ca0bea77a7
15 files changed
+373 -16

No files matched your search

+9 -10
View File
@@ -101,15 +101,16 @@ def _authorize(secret_in_path: str | None, header_secret: str | None, body: dict
raise HTTPException(404)
async def _answer(utterance: str, speaker: str, deadline: float) -> dict:
async def _answer(utterance: str, speaker: str, deadline: float, app_user_id: str = '') -> dict:
"""대화 한 턴을 SkillResponse 로. 어떤 실패도 문구로 바꾼다."""
try:
answer = await asyncio.wait_for(channel.handle(utterance, speaker), timeout=deadline)
answer = await asyncio.wait_for(
channel.handle(utterance, speaker, app_user_id), timeout=deadline)
except asyncio.TimeoutError:
LOG.w("[agent/kakao] 응답 시간 초과 — 안내로 끊음")
return _reply(_TIMEOUT_TEXT)
except Exception as ex: # noqa: BLE001 — 메신저에서는 500 도 침묵으로 보인다
LOG.w(f"[agent/kakao] 처리 실패: {type(ex).__name__}")
LOG.w(f"[agent/kakao] 처리 실패: {type(ex).__name__}: {ex}")
return _reply(_ERROR_TEXT)
return _reply_from(answer)
@@ -158,12 +159,12 @@ async def _approve_click(extra: dict, speaker: str) -> dict:
return _reply_from(answer)
async def _push(callback_url: str, utterance: str, speaker: str) -> None:
async def _push(callback_url: str, utterance: str, speaker: str, app_user_id: str = '') -> None:
"""답을 다 만든 뒤 콜백 주소로 보낸다.
★ 주소는 1분 · 1회만 유효하다. 실패해도 재시도하지 않는다 — 두 번째 POST 는 어차피
거절되고, 사장님에게는 이미 "확인하고 있어요" 가 가 있다."""
payload = await _answer(utterance, speaker, CALLBACK_DEADLINE_SEC)
payload = await _answer(utterance, speaker, CALLBACK_DEADLINE_SEC, app_user_id)
try:
async with httpx.AsyncClient(timeout=10.0) as client:
res = await client.post(callback_url, json=payload)
@@ -187,9 +188,7 @@ async def _handle(body: dict, tasks: BackgroundTasks) -> dict:
# 오면 6자리 코드 절차 없이 사장님을 바로 알아볼 수 있다.
# ★ 값 자체는 남기지 않는다 — 사용자 식별자다. 어떤 키가 왔는지와 길이만 본다.
props = user.get("properties") or {}
if isinstance(props, dict):
LOG.i(f"[agent/kakao] 발화자 키 — properties={sorted(props)} "
f"appUserId={'있음(%d자)' % len(str(props['appUserId'])) if props.get('appUserId') else '없음'}")
app_user_id = str(props.get("appUserId") or "") if isinstance(props, dict) else ""
# ★ [승인] 버튼(action: block)의 extra 는 그 블록의 스킬 요청에 action.clientExtra 로 돌아온다.
# 글 ID 값은 남기지 않고 어떤 키가 왔는지만 남긴다.
@@ -213,10 +212,10 @@ async def _handle(body: dict, tasks: BackgroundTasks) -> dict:
LOG.i(f"[agent/kakao] 요청 — callbackUrl={'있음' if callback_url else '없음'} "
f"block={(request.get('block') or {}).get('name')!r}")
if callback_url:
tasks.add_task(_push, callback_url, utterance, speaker)
tasks.add_task(_push, callback_url, utterance, speaker, app_user_id)
return {"version": "2.0", "useCallback": True, "data": {"text": _WAIT_TEXT}}
return await _answer(utterance, speaker, DEADLINE_SEC)
return await _answer(utterance, speaker, DEADLINE_SEC, app_user_id)
@router.post("/webhook")
+16 -1
View File
@@ -4,7 +4,10 @@ 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_GoogleLogin, Req_Login, Req_Signup, Req_UpdateMe, Res_Login, Res_Me, Res_RefreshToken
from .protocol import (
Req_GoogleLogin, Req_KakaoLogin, Req_Login, Req_Signup, Req_UpdateMe,
Res_Login, Res_Me, Res_RefreshToken,
)
security = HTTPBearer()
@@ -37,6 +40,18 @@ async def google_login(req: Req_GoogleLogin, service: AuthService = Depends()):
return RemoveNoneResponse(await service.google_login(req))
@router.post(
path="/kakao",
response_model=Res_Login,
summary="카카오 로그인",
description="카카오 **액세스 토큰**을 카카오에 되물어 검증하고 JWT 를 발급한다. 처음 온 계정은 그 자리에서 만든다. "
"★ 챗봇에 물린 앱과 같은 앱이어야 한다 — 회원번호가 챗봇 웹훅의 appUserId 와 같은 값이라, "
"그래야 카톡 채널 발화자와 이 계정이 자동으로 이어진다(docs/AGENT.md).",
)
async def kakao_login(req: Req_KakaoLogin, service: AuthService = Depends()):
return RemoveNoneResponse(await service.kakao_login(req))
@router.post(
path="/refresh_token",
dependencies=[Depends(IsValidRefreshToken)],
@@ -29,6 +29,15 @@ class Req_GoogleLogin(AuthProtocol):
credential: str = ""
class Req_KakaoLogin(AuthProtocol):
"""카카오 로그인.
★ 구글은 ID 토큰(credential)을 우리가 직접 검증하지만, 카카오는 **액세스 토큰**을
카카오에 되물어 확인한다 — 그래서 필드 이름이 다르다."""
access_token: str = ""
class Res_Login(Res_WebPacketProtocol):
access_token: str = ""
refresh_token: str = ""