feat: 회원 탈퇴 (DELETE /v1/auth/me, 웹·앱 내 정보 시트 '탈퇴하기')
- 계정과 남긴 댓글·좋아요·저장을 한 트랜잭션으로 지우고 게시물·댓글 수를 맞춘다 - 로그아웃·탈퇴 때 내 정보 캐시를 먼저 버려 401 로 로그인 창이 뜨지 않게 - 탈퇴 테스트 추가, 공용 API 클라이언트 다시 생성
This commit is contained in:
1 parent
dd2d02758b
commit
86a0ea26ca
15 files changed
+313
-17
No files matched your search
@@ -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))
|
||||
@@ -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))
|
||||
@@ -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
|
||||
@@ -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 = {}
|
||||
|
||||
@@ -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
|
||||
Reference in new issue
Block a user