feat: 토스판 토스 로그인(mTLS 토큰 교환·연결 끊기 콜백)과 좋아요·댓글 다시 열기
This commit is contained in:
1 parent
e180d9651c
commit
ea5376820c
23 files changed
+530
-56
No files matched your search
+52
@@ -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
|
||||
Reference in new issue
Block a user