feat: 토스판 토스 로그인(mTLS 토큰 교환·연결 끊기 콜백)과 좋아요·댓글 다시 열기
This commit is contained in:
1 parent
e180d9651c
commit
ea5376820c
23 files changed
+530
-56
No files matched your search
@@ -159,3 +159,4 @@ class RefType(CodeEnum):
|
||||
class AuthProvider(CodeEnum):
|
||||
LOCAL = 1
|
||||
GOOGLE = 2
|
||||
TOSS = 3
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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_<sub>
|
||||
provider SMALLINT NOT NULL DEFAULT 1, -- AuthProvider: 1=일반 2=구글 3=토스
|
||||
login_id VARCHAR(64) NOT NULL, -- 일반은 아이디, 구글은 google_<sub>, 토스는 toss_<userKey>
|
||||
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,
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
+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
|
||||
@@ -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")
|
||||
Reference in new issue
Block a user