diff --git a/TODO.md b/TODO.md index eb6a945..2e2005a 100644 --- a/TODO.md +++ b/TODO.md @@ -171,6 +171,9 @@ | [ ] | 안드로이드 댓글 쓰기·내 정보 바꾸기·로그아웃 확인 | 아직 안 눌러 봄 | `mobile/src/components/sheets/` | | [x] | 출시 빌드 설정: `eas.json`(production 은 운영 API·사이트 주소, 빌드 번호 자동 증가), iOS 수출 규정 암호화 없음, 안드로이드 권한은 대략 위치만(정밀 위치·저장소·다른 앱 위에 그리기 뺌) | | `mobile/eas.json`, `mobile/app.json` | | [ ] | 출시 빌드 전 준비(사용자): Apple Developer·Google Play Console·Expo 계정, 스토어 스크린샷·설명·데이터 안전 양식 | 서명·제출에 필요 | | +| [x] | 회원 탈퇴(스토어 심사 필수): `DELETE /v1/auth/me` — 계정·댓글·좋아요·저장 모두 삭제, 게시물·댓글 수 맞춤. 웹·앱 내 정보 시트 '탈퇴하기'(한 번 더 확인) | Apple 5.1.1(v), Google Play 계정 삭제 정책 | `backend/crud/user_crud.py`, `backend/services/auth_service.py`, `frontend/src/b/Sheets.tsx`, `mobile/src/components/sheets/me.tsx` | +| [ ] | 운영 배포 때 탈퇴 API 같이 나감 — 배포 전 웹 내 정보 시트 '탈퇴하기' 화면 확인 (앱은 안드로이드에서 확인, 웹은 빌드·린트만) | | `frontend/src/b/Sheets.tsx` | +| [ ] | 백엔드 테스트 3개가 날짜 때문에 실패 (10/19): `test_feed`(제철 각 수 42≠40), `test_watch`, `test_weather_today`(10월 하순 18시가 일몰 뒤라 'sunset' 아이콘 아님) — 탈퇴 작업과 무관 | 기대값을 날짜에 안 묶이게 고쳐야 함 | `backend/tests/` | | [ ] | Xcode 설치 후 iOS 시뮬레이터에서 전체 확인 | | `mobile/` | | [x] | 안드로이드 개발 빌드(`expo run:android`) 설치 확인: 홈 화면 해 아이콘·'날씨각' 이름, 실데이터 화면 | | `mobile/` | | [ ] | **[결정 필요]** 앱 ID(안드로이드 패키지·iOS 번들 ID) — 지금 `com.anonymous.nalssigak`. 후보 `kr.o2o.nalssigak` / `kr.o2o.weather`. 스토어에 올리면 못 바꿈 | 스토어 등록 때 정하기로 | `mobile/app.json` | diff --git a/backend/crud/user_crud.py b/backend/crud/user_crud.py index 6cd95fa..61797f3 100644 --- a/backend/crud/user_crud.py +++ b/backend/crud/user_crud.py @@ -1,11 +1,12 @@ import uuid +from collections import Counter from datetime import datetime, timezone from typing import Optional -from sqlalchemy import select +from sqlalchemy import delete, select, update from sqlalchemy.ext.asyncio import AsyncSession -from common.database.model.models import User +from common.database.model.models import Comment, CommentLike, Post, PostLike, PostSave, User class UserCRUD: @@ -31,3 +32,20 @@ class UserCRUD: user.updated_at = datetime.now(timezone.utc) await s.flush() return user + + async def withdraw(self, s: AsyncSession, user_id: uuid.UUID) -> None: + """계정과 그 사람이 남긴 좋아요·저장·댓글을 모두 지우고, 게시물·댓글에 쌓인 수를 그만큼 줄인다.""" + liked_posts = (await s.scalars(delete(PostLike).where(PostLike.user_id == user_id).returning(PostLike.post_id))).all() + if liked_posts: + await s.execute(update(Post).where(Post.post_id.in_(liked_posts)).values(like_count=Post.like_count - 1)) + liked_comments = (await s.scalars(delete(CommentLike).where(CommentLike.user_id == user_id).returning(CommentLike.comment_id))).all() + if liked_comments: + await s.execute(update(Comment).where(Comment.comment_id.in_(liked_comments)).values(like_count=Comment.like_count - 1)) + await s.execute(delete(PostSave).where(PostSave.user_id == user_id)) + mine = (await s.execute(delete(Comment).where(Comment.user_id == user_id).returning(Comment.comment_id, Comment.post_id, Comment.deleted))).all() + if mine: + await s.execute(delete(CommentLike).where(CommentLike.comment_id.in_([c for c, _, _ in mine]))) + # 이미 지운 댓글은 댓글 수에서 빠져 있다 + for post_id, n in Counter(p for _, p, deleted in mine if not deleted).items(): + await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - n)) + await s.execute(delete(User).where(User.user_id == user_id)) diff --git a/backend/router/v1/auth/account.py b/backend/router/v1/auth/account.py index c99dd7a..81a4fc0 100644 --- a/backend/router/v1/auth/account.py +++ b/backend/router/v1/auth/account.py @@ -4,7 +4,7 @@ from common.auth import current_user from common.database.model.models import User from common.enums import AuthProvider, ErrorType 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 router.v1.auth.protocol import Me, Req_Login, Req_Refresh, Req_Signup, Req_UpdateMe, Res_Auth, Res_Logout, Res_Me, Res_Withdraw from services.auth_service import AuthService router = APIRouter(prefix="/v1/auth", tags=["auth"]) @@ -56,3 +56,9 @@ async def update_me(req: Req_UpdateMe, user: User = Depends(current_user), servi if err is not ErrorType.SUCCESS: return Res_Me(result=error_info(err)) return Res_Me(me=_me(updated)) + + +@router.delete("/me", response_model=Res_Withdraw, response_model_exclude_none=True, summary="탈퇴 (계정과 남긴 댓글·좋아요를 모두 지운다)") +async def withdraw(user: User = Depends(current_user), service: AuthService = Depends()) -> Res_Withdraw: + err = await service.withdraw(user) + return Res_Withdraw() if err is ErrorType.SUCCESS else Res_Withdraw(result=error_info(err)) diff --git a/backend/router/v1/auth/protocol.py b/backend/router/v1/auth/protocol.py index f8bb6bc..5e0352f 100644 --- a/backend/router/v1/auth/protocol.py +++ b/backend/router/v1/auth/protocol.py @@ -45,5 +45,9 @@ class Res_Logout(Res_WebPacketProtocol): pass +class Res_Withdraw(Res_WebPacketProtocol): + pass + + class Res_Me(Res_WebPacketProtocol): me: Optional[Me] = None diff --git a/backend/services/auth_service.py b/backend/services/auth_service.py index 92b3423..c079c55 100644 --- a/backend/services/auth_service.py +++ b/backend/services/auth_service.py @@ -60,6 +60,10 @@ class AuthService: """이 사용자의 모든 기기 토큰을 무효로 만든다.""" return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.update(s, user.user_id, {"token_version": user.token_version + 1})]) + async def withdraw(self, user: User) -> ErrorType: + """탈퇴: 계정과 남긴 댓글·좋아요를 한 번에 지운다. 계정이 없어지니 가진 토큰도 바로 못 쓴다.""" + return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.withdraw(s, user.user_id)]) + async def update_me(self, user: User, nickname: Optional[str], character: Optional[str], color: Optional[str] = None, mood: Optional[str] = None) -> tuple[ErrorType, Optional[User]]: """닉네임·캐릭터·배경색·기분 중 보낸 것만 바꾼다. 기분을 빈 문자열로 보내면 지운다.""" values: dict = {} diff --git a/backend/tests/test_auth_reaction.py b/backend/tests/test_auth_reaction.py index fd8f1af..15aa248 100644 --- a/backend/tests/test_auth_reaction.py +++ b/backend/tests/test_auth_reaction.py @@ -121,3 +121,31 @@ async def test_logout_invalidates_access_and_refresh_tokens(): assert (await c.post("/v1/auth/refresh", json={"refresh_token": body["refresh_token"]})).json()["result"]["desc"] == "AUTH_TOKEN_INVALID" again = (await c.post("/v1/auth/login", json={"login_id": "mina_out", "password": "password1"})).json() assert (await c.get("/v1/auth/me", headers={"Authorization": f"Bearer {again['access_token']}"})).status_code == 200 + + +@pytest.mark.anyio +async def test_withdraw_deletes_account_and_reactions(offline): + async with client() as c: + body = await _signup(c, login_id="mina_bye") + h = {"Authorization": f"Bearer {body['access_token']}"} + other = {"Authorization": f"Bearer {(await _signup(c, 'other_bye', '남는사람'))['access_token']}"} + post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"] + await c.post(f"/v1/reaction/post/{post_id}/like", headers=h) + await c.post(f"/v1/reaction/post/{post_id}/save", headers=h) + mine = (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=h, json={"body": "곧 떠나요"})).json()["comment"] + kept = (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=other, json={"body": "남아요"})).json()["comment"] + await c.post(f"/v1/reaction/comment/{kept['comment_id']}/like", headers=h) + await c.post(f"/v1/reaction/comment/{mine['comment_id']}/like", headers=other) + + assert (await c.delete("/v1/auth/me")).status_code == 401 + assert (await c.delete("/v1/auth/me", headers=h)).json()["result"]["success"] is True + + assert (await c.get("/v1/auth/me", headers=h)).status_code == 401 + assert (await c.post("/v1/auth/refresh", json={"refresh_token": body["refresh_token"]})).json()["result"]["desc"] == "AUTH_TOKEN_INVALID" + assert (await c.post("/v1/auth/login", json={"login_id": "mina_bye", "password": "password1"})).json()["result"]["desc"] == "AUTH_FAILED" + comments = (await c.get(f"/v1/reaction/post/{post_id}/comment/list")).json()["comments"] + assert [x["body"] for x in comments] == ["남아요"] and comments[0]["like_count"] == 0 + p = next(x for x in (await c.get("/v1/feed", params={"region": REGION})).json()["posts"] if x["post_id"] == post_id) + assert p["like_count"] == 0 and p["comment_count"] == 1 + # 같은 아이디로 다시 가입할 수 있다 + assert (await _signup(c, login_id="mina_bye"))["result"]["success"] is True diff --git a/frontend/src/b/Sheets.tsx b/frontend/src/b/Sheets.tsx index cd543f6..f65e784 100644 --- a/frontend/src/b/Sheets.tsx +++ b/frontend/src/b/Sheets.tsx @@ -1,6 +1,6 @@ import { useInfiniteQuery, useMutation, useQuery, useQueryClient, type InfiniteData } from '@tanstack/react-query' import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react' -import { setTokens, subscribeAuth } from '@nalssigak/shared/api/auth' +import { clearTokens, setTokens, subscribeAuth } from '@nalssigak/shared/api/auth' import { SITE_URL } from '../api/setup' import { addCommentMutation, @@ -18,6 +18,7 @@ import { signupMutation, unlikeCommentMutation, updateMeMutation, + withdrawMutation, } from '@nalssigak/shared/api/client/@tanstack/react-query.gen' import type { CommentData, Factor, ResAuth, ResCommentList, ResIndexDetail } from '@nalssigak/shared/api/client/types.gen' import { track } from '../lib/analytics' @@ -862,7 +863,52 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () ) } -/* ---------- 내 정보: 캐릭터·닉네임·로그아웃 ---------- */ +/* ---------- 내 정보: 캐릭터·닉네임·로그아웃·탈퇴 ---------- */ +/** 탈퇴: 한 번 더 묻고 지운다. 계정이 없어지니 이 기기 토큰도 지운다 */ +function Withdraw({ onDone }: { onDone: () => void }) { + const withdraw = useMutation(withdrawMutation()) + const [asking, setAsking] = useState(false) + const [failed, setFailed] = useState(false) + if (!asking) + return ( + + ) + const run = () => { + setFailed(false) + withdraw.mutate( + {}, + { + onSuccess: (res) => { + if (!res.result?.success) return setFailed(true) + clearTokens() + onDone() + }, + onError: () => setFailed(true), + }, + ) + } + return ( +
+ 탈퇴하면 계정과 남긴 댓글·좋아요가
+
+ 모두 지워져요. 되돌릴 수 없어요.
+
탈퇴하지 못했어요. 잠시 뒤에 다시 해 주세요.
} +