feat: 댓글 신고·차단·약관 동의(관리 스크립트 포함), 구글 로그인(서버·웹·안드로이드 앱), 앱 패키지 kr.o2o.nalssigak·versionCode 1000
This commit is contained in:
1 parent
fbebdcb796
commit
3f3a3ea039
35 files changed
+1723
-115
No files matched your search
@@ -322,6 +322,7 @@ class User(Base):
|
||||
color: Mapped[str] = mapped_column(String(20), default="orange")
|
||||
mood: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
|
||||
status: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
terms_agreed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
token_version: Mapped[int] = mapped_column(SmallInteger, default=1)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
@@ -352,10 +353,29 @@ class Comment(Base):
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True))
|
||||
body: Mapped[str] = mapped_column(String(60))
|
||||
like_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
report_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
is_hidden: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
deleted: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
|
||||
|
||||
class CommentReport(Base):
|
||||
__tablename__ = "comment_report"
|
||||
|
||||
comment_id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
reason: Mapped[int] = mapped_column(SmallInteger)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class UserBlock(Base):
|
||||
__tablename__ = "user_block"
|
||||
|
||||
user_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
blocked_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
|
||||
|
||||
|
||||
class CommentLike(Base):
|
||||
__tablename__ = "comment_like"
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ class ErrorType(Enum):
|
||||
AUTH_FAILED = 4002
|
||||
AUTH_DUPLICATE_ID = 4003
|
||||
AUTH_TOKEN_INVALID = 4004
|
||||
TERMS_REQUIRED = 4005
|
||||
|
||||
|
||||
class Sky(CodeEnum):
|
||||
@@ -159,3 +160,10 @@ class RefType(CodeEnum):
|
||||
class AuthProvider(CodeEnum):
|
||||
LOCAL = 1
|
||||
GOOGLE = 2
|
||||
|
||||
|
||||
class ReportReason(CodeEnum):
|
||||
ABUSE = 1
|
||||
AD = 2
|
||||
PRIVACY = 3
|
||||
OTHER = 4
|
||||
@@ -0,0 +1,43 @@
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
from jose import JWTError, jwt
|
||||
|
||||
from common.logger import LOG
|
||||
from config.settings import settings
|
||||
|
||||
CERTS_URL = "https://www.googleapis.com/oauth2/v3/certs"
|
||||
ISSUERS = ("accounts.google.com", "https://accounts.google.com")
|
||||
_CERTS_TTL = 3600
|
||||
_certs: dict = {"keys": [], "at": 0.0}
|
||||
|
||||
|
||||
async def _keys(force: bool = False) -> list[dict]:
|
||||
"""구글 서명 공개키. 한 시간 캐시하고, 모르는 키가 오면 한 번 다시 받는다."""
|
||||
if force or not _certs["keys"] or time.monotonic() - _certs["at"] > _CERTS_TTL:
|
||||
async with httpx.AsyncClient(timeout=5) as c:
|
||||
res = await c.get(CERTS_URL)
|
||||
res.raise_for_status()
|
||||
_certs["keys"], _certs["at"] = res.json()["keys"], time.monotonic()
|
||||
return _certs["keys"]
|
||||
|
||||
|
||||
async def verify(credential: str) -> Optional[str]:
|
||||
"""구글 로그인 버튼이 준 ID 토큰을 확인하고 구글 사용자 고유 번호(sub)를 돌려준다. 서명·발급처·우리 클라이언트 ID·만료가 하나라도 안 맞으면 None."""
|
||||
if not settings.google_client_id:
|
||||
LOG.error("[google] GOOGLE_CLIENT_ID is empty")
|
||||
return None
|
||||
try:
|
||||
kid = jwt.get_unverified_header(credential).get("kid")
|
||||
keys = await _keys()
|
||||
key = next((k for k in keys if k.get("kid") == kid), None) or next((k for k in await _keys(force=True) if k.get("kid") == kid), None)
|
||||
if key is None:
|
||||
return None
|
||||
claims = jwt.decode(credential, key, algorithms=["RS256"], audience=settings.google_client_id, options={"verify_at_hash": False})
|
||||
except (JWTError, httpx.HTTPError, KeyError, ValueError) as e:
|
||||
LOG.warning("[google] id token rejected: %s", type(e).__name__)
|
||||
return None
|
||||
if claims.get("iss") not in ISSUERS or not claims.get("sub"):
|
||||
return None
|
||||
return str(claims["sub"])
|
||||
@@ -34,6 +34,9 @@ class Settings(BaseSettings):
|
||||
# 지역 검색 페이지의 정적 HTML 을 받아 올 프론트 주소 (같은 docker 망 안)
|
||||
frontend_internal_url: str = "http://frontend"
|
||||
|
||||
# 구글 로그인 OAuth 클라이언트 ID (공개값). 비면 구글 로그인을 받지 않는다
|
||||
google_client_id: str = ""
|
||||
|
||||
jwt_access_secret: str = ""
|
||||
jwt_refresh_secret: str = ""
|
||||
jwt_access_minutes: int = 60
|
||||
|
||||
@@ -5,7 +5,9 @@ from sqlalchemy import delete, select, update
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import Comment, CommentLike, Post, PostLike, PostSave, User
|
||||
from common.database.model.models import Comment, CommentLike, CommentReport, Post, PostLike, PostSave, User, UserBlock
|
||||
|
||||
HIDE_AT = 3 # 신고가 이만큼 쌓이면 모두에게서 숨긴다
|
||||
|
||||
|
||||
class ReactionCRUD:
|
||||
@@ -40,8 +42,16 @@ class ReactionCRUD:
|
||||
stmt = stmt.where(Post.post_id < cursor)
|
||||
return list((await s.execute(stmt.order_by(Post.post_id.desc()).limit(limit))).all())
|
||||
|
||||
async def comments(self, s: AsyncSession, post_id: int, cursor: Optional[int], limit: int) -> list[tuple[Comment, str, str, str, Optional[str]]]:
|
||||
stmt = select(Comment, User.nickname, User.character, User.color, User.mood).join(User, User.user_id == Comment.user_id).where(Comment.post_id == post_id, Comment.deleted.is_(False))
|
||||
async def comments(self, s: AsyncSession, post_id: int, viewer: Optional[uuid.UUID], cursor: Optional[int], limit: int) -> list[tuple[Comment, str, str, str, Optional[str]]]:
|
||||
"""숨긴 댓글은 빼고, 보는 사람이 신고한 댓글·차단한 사람의 댓글도 뺀다."""
|
||||
stmt = select(Comment, User.nickname, User.character, User.color, User.mood).join(User, User.user_id == Comment.user_id).where(
|
||||
Comment.post_id == post_id, Comment.deleted.is_(False), Comment.is_hidden.is_(False)
|
||||
)
|
||||
if viewer is not None:
|
||||
stmt = stmt.where(
|
||||
Comment.comment_id.not_in(select(CommentReport.comment_id).where(CommentReport.user_id == viewer)),
|
||||
Comment.user_id.not_in(select(UserBlock.blocked_id).where(UserBlock.user_id == viewer)),
|
||||
)
|
||||
if cursor is not None:
|
||||
stmt = stmt.where(Comment.comment_id > cursor)
|
||||
return list((await s.execute(stmt.order_by(Comment.comment_id).limit(limit))).all())
|
||||
@@ -60,16 +70,18 @@ class ReactionCRUD:
|
||||
async def delete_comment(self, s: AsyncSession, comment_id: int, user_id: uuid.UUID) -> bool:
|
||||
res = await s.execute(
|
||||
update(Comment).where(Comment.comment_id == comment_id, Comment.user_id == user_id, Comment.deleted.is_(False))
|
||||
.values(deleted=True).returning(Comment.post_id)
|
||||
.values(deleted=True).returning(Comment.post_id, Comment.is_hidden)
|
||||
)
|
||||
post_id = res.scalar()
|
||||
if post_id is None:
|
||||
row = res.first()
|
||||
if row is None:
|
||||
return False
|
||||
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - 1))
|
||||
# 숨긴 댓글은 이미 댓글 수에서 빠져 있다
|
||||
if not row.is_hidden:
|
||||
await s.execute(update(Post).where(Post.post_id == row.post_id).values(comment_count=Post.comment_count - 1))
|
||||
return True
|
||||
|
||||
async def toggle_comment_like(self, s: AsyncSession, comment_id: int, user_id: uuid.UUID, on: bool) -> Optional[int]:
|
||||
exists = await s.scalar(select(Comment.comment_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False)))
|
||||
exists = await s.scalar(select(Comment.comment_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False), Comment.is_hidden.is_(False)))
|
||||
if exists is None:
|
||||
return None
|
||||
if on:
|
||||
@@ -79,3 +91,43 @@ class ReactionCRUD:
|
||||
if res.first() is not None:
|
||||
await s.execute(update(Comment).where(Comment.comment_id == comment_id).values(like_count=Comment.like_count + (1 if on else -1)))
|
||||
return await s.scalar(select(Comment.like_count).where(Comment.comment_id == comment_id))
|
||||
|
||||
async def comment_author(self, s: AsyncSession, comment_id: int) -> Optional[uuid.UUID]:
|
||||
return await s.scalar(select(Comment.user_id).where(Comment.comment_id == comment_id, Comment.deleted.is_(False), Comment.is_hidden.is_(False)))
|
||||
|
||||
async def report_comment(self, s: AsyncSession, comment_id: int, user_id: uuid.UUID, reason: int) -> None:
|
||||
"""같은 사람이 두 번 신고해도 한 번만 센다. HIDE_AT 건이 되면 숨기고 댓글 수에서 뺀다."""
|
||||
res = await s.execute(insert(CommentReport).values(comment_id=comment_id, user_id=user_id, reason=reason).on_conflict_do_nothing().returning(CommentReport.comment_id))
|
||||
if res.first() is None:
|
||||
return
|
||||
await s.execute(update(Comment).where(Comment.comment_id == comment_id).values(report_count=Comment.report_count + 1))
|
||||
res = await s.execute(
|
||||
update(Comment).where(Comment.comment_id == comment_id, Comment.report_count >= HIDE_AT, Comment.is_hidden.is_(False), Comment.deleted.is_(False))
|
||||
.values(is_hidden=True).returning(Comment.post_id)
|
||||
)
|
||||
post_id = res.scalar()
|
||||
if post_id is not None:
|
||||
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count - 1))
|
||||
|
||||
async def set_hidden(self, s: AsyncSession, comment_id: int, hidden: bool) -> bool:
|
||||
"""운영자가 댓글을 숨기거나 되살린다. 실제로 바뀌었을 때만 댓글 수를 고친다."""
|
||||
res = await s.execute(
|
||||
update(Comment).where(Comment.comment_id == comment_id, Comment.is_hidden.is_(not hidden), Comment.deleted.is_(False))
|
||||
.values(is_hidden=hidden).returning(Comment.post_id)
|
||||
)
|
||||
post_id = res.scalar()
|
||||
if post_id is None:
|
||||
return False
|
||||
await s.execute(update(Post).where(Post.post_id == post_id).values(comment_count=Post.comment_count + (-1 if hidden else 1)))
|
||||
return True
|
||||
|
||||
async def block(self, s: AsyncSession, user_id: uuid.UUID, blocked_id: uuid.UUID) -> None:
|
||||
await s.execute(insert(UserBlock).values(user_id=user_id, blocked_id=blocked_id).on_conflict_do_nothing())
|
||||
|
||||
async def unblock(self, s: AsyncSession, user_id: uuid.UUID, blocked_id: uuid.UUID) -> bool:
|
||||
res = await s.execute(delete(UserBlock).where(UserBlock.user_id == user_id, UserBlock.blocked_id == blocked_id).returning(UserBlock.blocked_id))
|
||||
return res.first() is not None
|
||||
|
||||
async def blocked(self, s: AsyncSession, user_id: uuid.UUID) -> list[User]:
|
||||
stmt = select(User).join(UserBlock, UserBlock.blocked_id == User.user_id).where(UserBlock.user_id == user_id).order_by(UserBlock.created_at.desc())
|
||||
return list((await s.scalars(stmt)).all())
|
||||
@@ -6,7 +6,7 @@ from typing import Optional
|
||||
from sqlalchemy import delete, select, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.model.models import Comment, CommentLike, Post, PostLike, PostSave, User
|
||||
from common.database.model.models import Comment, CommentLike, CommentReport, Post, PostLike, PostSave, User, UserBlock
|
||||
|
||||
|
||||
class UserCRUD:
|
||||
@@ -23,6 +23,12 @@ class UserCRUD:
|
||||
await s.flush()
|
||||
return user
|
||||
|
||||
async def create_google(self, s: AsyncSession, sub: str, nickname: str) -> User:
|
||||
user = User(login_id=f"google_{sub}", provider_uid=sub, nickname=nickname, provider=2)
|
||||
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:
|
||||
@@ -33,8 +39,11 @@ class UserCRUD:
|
||||
await s.flush()
|
||||
return user
|
||||
|
||||
async def agree_terms(self, s: AsyncSession, user_id: uuid.UUID) -> None:
|
||||
await s.execute(update(User).where(User.user_id == user_id, User.terms_agreed_at.is_(None)).values(terms_agreed_at=datetime.now(timezone.utc)))
|
||||
|
||||
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))
|
||||
@@ -42,10 +51,16 @@ class UserCRUD:
|
||||
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()
|
||||
reported = (await s.scalars(delete(CommentReport).where(CommentReport.user_id == user_id).returning(CommentReport.comment_id))).all()
|
||||
if reported:
|
||||
await s.execute(update(Comment).where(Comment.comment_id.in_(reported)).values(report_count=Comment.report_count - 1))
|
||||
await s.execute(delete(UserBlock).where((UserBlock.user_id == user_id) | (UserBlock.blocked_id == user_id)))
|
||||
mine = (await s.execute(delete(Comment).where(Comment.user_id == user_id).returning(Comment.comment_id, Comment.post_id, Comment.deleted, Comment.is_hidden))).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():
|
||||
ids = [c for c, _, _, _ in mine]
|
||||
await s.execute(delete(CommentLike).where(CommentLike.comment_id.in_(ids)))
|
||||
await s.execute(delete(CommentReport).where(CommentReport.comment_id.in_(ids)))
|
||||
# 이미 지웠거나 숨긴 댓글은 댓글 수에서 빠져 있다
|
||||
for post_id, n in Counter(p for _, p, deleted, hidden in mine if not deleted and not hidden).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))
|
||||
@@ -196,6 +196,7 @@ CREATE TABLE IF NOT EXISTS public.users (
|
||||
color VARCHAR(20) NOT NULL DEFAULT 'orange', -- 프로필 배경색: orange·blue·green·purple·pink·brown
|
||||
mood VARCHAR(20) NULL, -- 오늘 기분: clear·partly·cloudy·rain·thunder·snow·fog·rainbow. NULL = 안 고름
|
||||
status SMALLINT NOT NULL DEFAULT 1, -- UserStatus: 1=정상 2=정지
|
||||
terms_agreed_at TIMESTAMPTZ NULL, -- 이용약관 동의 시각. NULL 이면 댓글을 못 쓴다
|
||||
token_version SMALLINT NOT NULL DEFAULT 1, -- 올리면 이전 refresh 토큰이 모두 무효
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
@@ -230,16 +231,28 @@ CREATE TABLE IF NOT EXISTS public.comment (
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_comment_post ON public.comment (post_id, created_at) WHERE deleted = FALSE;
|
||||
|
||||
-- 댓글 신고 (보류)
|
||||
-- ALTER TABLE public.comment ADD COLUMN report_count INTEGER NOT NULL DEFAULT 0;
|
||||
-- ALTER TABLE public.comment ADD COLUMN is_hidden BOOLEAN NOT NULL DEFAULT FALSE;
|
||||
-- CREATE TABLE IF NOT EXISTS public.comment_report (
|
||||
-- comment_id BIGINT NOT NULL,
|
||||
-- user_id UUID NOT NULL,
|
||||
-- reason SMALLINT NOT NULL, -- ReportReason: 1=욕설·비하 2=광고 3=개인정보 노출 4=기타
|
||||
-- created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
-- PRIMARY KEY (comment_id, user_id)
|
||||
-- );
|
||||
ALTER TABLE public.users ADD COLUMN IF NOT EXISTS terms_agreed_at TIMESTAMPTZ NULL;
|
||||
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS report_count INTEGER NOT NULL DEFAULT 0;
|
||||
ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS is_hidden BOOLEAN NOT NULL DEFAULT FALSE; -- 신고 3건이면 숨김. 숨긴 댓글은 댓글 수에서 빠진다
|
||||
|
||||
-- 댓글 신고. 신고한 사람에게는 그 댓글이 바로 안 보인다
|
||||
CREATE TABLE IF NOT EXISTS public.comment_report (
|
||||
comment_id BIGINT NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
reason SMALLINT NOT NULL, -- ReportReason: 1=욕설·비하 2=광고 3=개인정보 노출 4=기타
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (comment_id, user_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_comment_report_user ON public.comment_report (user_id);
|
||||
|
||||
-- 사용자 차단. 차단한 사람의 댓글이 내게 안 보인다
|
||||
CREATE TABLE IF NOT EXISTS public.user_block (
|
||||
user_id UUID NOT NULL, -- 차단한 사람
|
||||
blocked_id UUID NOT NULL, -- 차단당한 사람
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (user_id, blocked_id)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_block_blocked ON public.user_block (blocked_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS public.comment_like (
|
||||
comment_id BIGINT NOT NULL,
|
||||
|
||||
@@ -4,14 +4,15 @@ 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, Res_Withdraw
|
||||
from config.settings import settings
|
||||
from router.v1.auth.protocol import Me, Req_Google, Req_Login, Req_Refresh, Req_Signup, Req_UpdateMe, Res_Auth, Res_AuthConfig, Res_Logout, Res_Me, Res_Withdraw
|
||||
from services.auth_service import AuthService
|
||||
|
||||
router = APIRouter(prefix="/v1/auth", tags=["auth"])
|
||||
|
||||
|
||||
def _me(u: User) -> Me:
|
||||
return Me(login_id=u.login_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, provider=AuthProvider(u.provider))
|
||||
return Me(login_id=u.login_id, nickname=u.nickname, character=u.character, color=u.color, mood=u.mood, provider=AuthProvider(u.provider), terms_agreed=u.terms_agreed_at is not None)
|
||||
|
||||
|
||||
def _auth(err: ErrorType, user, service: AuthService) -> Res_Auth:
|
||||
@@ -33,6 +34,17 @@ async def login(req: Req_Login, service: AuthService = Depends()) -> Res_Auth:
|
||||
return _auth(err, user, service)
|
||||
|
||||
|
||||
@router.post("/google", response_model=Res_Auth, response_model_exclude_none=True, summary="구글 로그인 (처음이면 자동 닉네임으로 가입)")
|
||||
async def google_login(req: Req_Google, service: AuthService = Depends()) -> Res_Auth:
|
||||
err, user = await service.google(req.credential)
|
||||
return _auth(err, user, service)
|
||||
|
||||
|
||||
@router.get("/config", response_model=Res_AuthConfig, response_model_exclude_none=True, summary="로그인 화면 설정 (구글 클라이언트 ID)")
|
||||
async def auth_config() -> Res_AuthConfig:
|
||||
return Res_AuthConfig(google_client_id=settings.google_client_id or None)
|
||||
|
||||
|
||||
@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)
|
||||
@@ -58,6 +70,14 @@ async def update_me(req: Req_UpdateMe, user: User = Depends(current_user), servi
|
||||
return Res_Me(me=_me(updated))
|
||||
|
||||
|
||||
@router.post("/terms", response_model=Res_Me, response_model_exclude_none=True, summary="이용약관 동의 (댓글 쓰기 전에 한 번)")
|
||||
async def agree_terms(user: User = Depends(current_user), service: AuthService = Depends()) -> Res_Me:
|
||||
err, updated = await service.agree_terms(user)
|
||||
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)
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from common.enums import AuthProvider
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
@@ -15,6 +17,10 @@ class Req_Login(Req_WebPacketProtocol):
|
||||
password: str
|
||||
|
||||
|
||||
class Req_Google(Req_WebPacketProtocol):
|
||||
credential: str = Field(min_length=20, max_length=4096, description="구글 로그인 버튼이 준 ID 토큰")
|
||||
|
||||
|
||||
class Req_Refresh(Req_WebPacketProtocol):
|
||||
refresh_token: str
|
||||
|
||||
@@ -33,6 +39,7 @@ class Me(WebPacketProtocol):
|
||||
color: str
|
||||
mood: Optional[str] = None
|
||||
provider: AuthProvider
|
||||
terms_agreed: bool = False
|
||||
|
||||
|
||||
class Res_Auth(Res_WebPacketProtocol):
|
||||
@@ -51,3 +58,7 @@ class Res_Withdraw(Res_WebPacketProtocol):
|
||||
|
||||
class Res_Me(Res_WebPacketProtocol):
|
||||
me: Optional[Me] = None
|
||||
|
||||
|
||||
class Res_AuthConfig(Res_WebPacketProtocol):
|
||||
google_client_id: Optional[str] = Field(None, description="구글 로그인 버튼에 쓸 OAuth 클라이언트 ID. 없으면 구글 로그인을 숨긴다")
|
||||
@@ -1,7 +1,8 @@
|
||||
import uuid
|
||||
from datetime import date, datetime
|
||||
from typing import Optional
|
||||
|
||||
from common.enums import PostType
|
||||
from common.enums import PostType, ReportReason
|
||||
from common.models.gmodel import Req_WebPacketProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
@@ -55,3 +56,18 @@ class Res_Comment(Res_WebPacketProtocol):
|
||||
class Res_CommentLike(Res_WebPacketProtocol):
|
||||
liked: Optional[bool] = None
|
||||
like_count: Optional[int] = None
|
||||
|
||||
|
||||
class Req_Report(Req_WebPacketProtocol):
|
||||
reason: ReportReason
|
||||
|
||||
|
||||
class BlockedUser(WebPacketProtocol):
|
||||
user_id: uuid.UUID
|
||||
nickname: str
|
||||
character: str
|
||||
color: str
|
||||
|
||||
|
||||
class Res_BlockedList(Res_WebPacketProtocol):
|
||||
users: list[BlockedUser] = []
|
||||
@@ -1,3 +1,4 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, Path, Query
|
||||
@@ -9,7 +10,8 @@ from common.models.errors import error_info
|
||||
from common.models.gmodel import Res_WebPacketProtocol
|
||||
from common.utils.kma_time import KST
|
||||
from router.v1.reaction.protocol import (
|
||||
CommentData, Req_Comment, Res_Comment, Res_CommentLike, Res_CommentList, Res_PostLike, Res_PostSave, Res_SavedList, SavedPost,
|
||||
BlockedUser, CommentData, Req_Comment, Req_Report, Res_BlockedList, Res_Comment, Res_CommentLike, Res_CommentList, Res_PostLike, Res_PostSave,
|
||||
Res_SavedList, SavedPost,
|
||||
)
|
||||
from services.reaction_service import PAGE, CommentView, ReactionService
|
||||
|
||||
@@ -67,7 +69,7 @@ async def list_comments(
|
||||
return Res_CommentList(comments=[_comment(v) for v in items], next_cursor=items[-1].comment.comment_id if len(items) == PAGE else None)
|
||||
|
||||
|
||||
@router.post("/post/{post_id}/comment", response_model=Res_Comment, response_model_exclude_none=True, summary="댓글 쓰기 (60자)")
|
||||
@router.post("/post/{post_id}/comment", response_model=Res_Comment, response_model_exclude_none=True, summary="댓글 쓰기 (60자, 이용약관 동의 전이면 TERMS_REQUIRED)")
|
||||
async def add_comment(post_id: int = Path(...), req: Req_Comment = ..., user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_Comment:
|
||||
err, v = await service.add_comment(post_id, user, req.body)
|
||||
return Res_Comment(result=error_info(err)) if err is not ErrorType.SUCCESS else Res_Comment(comment=_comment(v))
|
||||
@@ -91,3 +93,26 @@ async def like_comment(comment_id: int = Path(...), user: User = Depends(current
|
||||
@router.delete("/comment/{comment_id}/like", response_model=Res_CommentLike, response_model_exclude_none=True, summary="댓글 좋아요 취소")
|
||||
async def unlike_comment(comment_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_CommentLike:
|
||||
return await _clike(comment_id, user, False, service)
|
||||
|
||||
|
||||
@router.post("/comment/{comment_id}/report", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="남의 댓글 신고 (신고한 사람에겐 바로 안 보이고, 3건이면 모두에게 숨김)")
|
||||
async def report_comment(comment_id: int = Path(...), req: Req_Report = ..., user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.report_comment(comment_id, user, req.reason)))
|
||||
|
||||
|
||||
@router.post("/comment/{comment_id}/block", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="이 댓글 쓴 사람 차단 (그 사람 댓글이 내게 안 보임)")
|
||||
async def block_author(comment_id: int = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.block_author(comment_id, user)))
|
||||
|
||||
|
||||
@router.get("/block/list", response_model=Res_BlockedList, response_model_exclude_none=True, summary="내가 차단한 사람")
|
||||
async def list_blocked(user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_BlockedList:
|
||||
err, users = await service.blocked(user)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return Res_BlockedList(result=error_info(err))
|
||||
return Res_BlockedList(users=[BlockedUser(user_id=u.user_id, nickname=u.nickname, character=u.character, color=u.color) for u in users])
|
||||
|
||||
|
||||
@router.delete("/block/{user_id}", response_model=Res_WebPacketProtocol, response_model_exclude_none=True, summary="차단 풀기")
|
||||
async def unblock(user_id: uuid.UUID = Path(...), user: User = Depends(current_user), service: ReactionService = Depends()) -> Res_WebPacketProtocol:
|
||||
return Res_WebPacketProtocol(result=error_info(await service.unblock(user, user_id)))
|
||||
@@ -0,0 +1,64 @@
|
||||
"""운영자용 댓글·사용자 조치.
|
||||
|
||||
python scripts/moderate.py reports 신고 받은 댓글 (많은 순 30개)
|
||||
python scripts/moderate.py hide <comment_id> 댓글 숨김
|
||||
python scripts/moderate.py show <comment_id> 숨긴 댓글 되살림
|
||||
python scripts/moderate.py suspend <login_id> 이용 정지 (로그인·토큰 막힘)
|
||||
python scripts/moderate.py resume <login_id> 정지 풀기
|
||||
"""
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from sqlalchemy import select, update # noqa: E402
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG # noqa: E402
|
||||
from common.database.model.models import Comment, User # noqa: E402
|
||||
from common.enums import ErrorType # noqa: E402
|
||||
from crud.reaction_crud import ReactionCRUD # noqa: E402
|
||||
|
||||
|
||||
async def _reports(s):
|
||||
stmt = (
|
||||
select(Comment.comment_id, Comment.report_count, Comment.is_hidden, User.login_id, Comment.body)
|
||||
.join(User, User.user_id == Comment.user_id)
|
||||
.where(Comment.report_count > 0, Comment.deleted.is_(False))
|
||||
.order_by(Comment.report_count.desc(), Comment.comment_id.desc())
|
||||
.limit(30)
|
||||
)
|
||||
return (await s.execute(stmt)).all()
|
||||
|
||||
|
||||
async def _set_status(s, login_id: str, status: int) -> bool:
|
||||
res = await s.execute(
|
||||
update(User).where(User.login_id == login_id, User.deleted.is_(False)).values(status=status, token_version=User.token_version + 1).returning(User.user_id)
|
||||
)
|
||||
return res.first() is not None
|
||||
|
||||
|
||||
async def main(argv: list[str]) -> int:
|
||||
if len(argv) < 1 or argv[0] not in {"reports", "hide", "show", "suspend", "resume"} or (argv[0] != "reports" and len(argv) != 2):
|
||||
print(__doc__)
|
||||
return 2
|
||||
cmd = argv[0]
|
||||
if cmd == "reports":
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(_reports)
|
||||
for comment_id, count, hidden, login_id, body in rows or []:
|
||||
print(f"{comment_id}\t신고 {count}\t{'숨김' if hidden else '보임'}\t{login_id}\t{body}")
|
||||
elif cmd in {"hide", "show"}:
|
||||
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: ReactionCRUD().set_hidden(s, int(argv[1]), cmd == "hide"))
|
||||
print("바뀜" if ok else "그대로 (없는 댓글이거나 이미 그 상태)")
|
||||
else:
|
||||
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: _set_status(s, argv[1], 2 if cmd == "suspend" else 1))
|
||||
print("바뀜" if ok else "없는 아이디")
|
||||
await DB_SESSION_MNG.stop()
|
||||
if err is not ErrorType.SUCCESS:
|
||||
print(err.name)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(asyncio.run(main(sys.argv[1:])))
|
||||
@@ -1,4 +1,5 @@
|
||||
import re
|
||||
import secrets
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
@@ -6,6 +7,7 @@ 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.google_id import verify as verify_google
|
||||
from common.database.model.models import User
|
||||
from common.enums import ErrorType
|
||||
from config.settings import settings
|
||||
@@ -19,6 +21,15 @@ COLORS = ("orange", "blue", "green", "purple", "pink", "brown")
|
||||
MOODS = ("clear", "partly", "cloudy", "rain", "thunder", "snow", "fog", "rainbow")
|
||||
|
||||
|
||||
_NICK_WORDS = ("맑은", "포근한", "산들", "반짝", "느긋한", "보슬", "선선한", "따끈한")
|
||||
_NICK_ANIMALS = {"rabbit": "토끼", "bear": "곰", "dog": "강아지", "sun": "해님", "moon": "달님", "cloud": "구름"}
|
||||
|
||||
|
||||
def auto_nickname() -> str:
|
||||
"""구글로 처음 들어온 사람의 이름: 맑은토끼 482. 내 정보에서 바꿀 수 있다."""
|
||||
return f"{secrets.choice(_NICK_WORDS)}{secrets.choice(list(_NICK_ANIMALS.values()))} {secrets.randbelow(900) + 100}"
|
||||
|
||||
|
||||
class AuthService:
|
||||
def __init__(self, crud: UserCRUD = Depends(UserCRUD)) -> None:
|
||||
self.crud = crud
|
||||
@@ -47,6 +58,26 @@ class AuthService:
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
return ErrorType.SUCCESS, user
|
||||
|
||||
async def google(self, credential: str) -> tuple[ErrorType, Optional[User]]:
|
||||
"""구글 ID 토큰으로 로그인. 처음이면 자동 닉네임으로 계정을 만든다. 구글 이름·이메일은 저장하지 않는다."""
|
||||
sub = await verify_google(credential)
|
||||
if sub is None:
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
login_id = f"google_{sub}"
|
||||
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
|
||||
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_google(s, sub, auto_nickname()))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
# 같은 계정이 동시에 처음 들어온 경우엔 먼저 만들어진 쪽을 쓴다
|
||||
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
|
||||
if err is not ErrorType.SUCCESS or user is None:
|
||||
return ErrorType.DB_ERROR, None
|
||||
if user.status != 1:
|
||||
return ErrorType.AUTH_FAILED, None
|
||||
return ErrorType.SUCCESS, 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:
|
||||
@@ -60,6 +91,12 @@ 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 agree_terms(self, user: User) -> tuple[ErrorType, Optional[User]]:
|
||||
err = await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.agree_terms(s, user.user_id)])
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.get(s, user.user_id))
|
||||
|
||||
async def withdraw(self, user: User) -> ErrorType:
|
||||
"""탈퇴: 계정과 남긴 댓글·좋아요를 한 번에 지운다. 계정이 없어지니 가진 토큰도 바로 못 쓴다."""
|
||||
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.withdraw(s, user.user_id)])
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
@@ -6,7 +7,7 @@ from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import Comment, Post, User
|
||||
from common.enums import ErrorType
|
||||
from common.enums import ErrorType, ReportReason
|
||||
from crud.feed_crud import FeedCRUD
|
||||
from crud.reaction_crud import ReactionCRUD
|
||||
|
||||
@@ -72,7 +73,7 @@ class ReactionService:
|
||||
return err, [SavedView(post=p, saved_at=ps.created_at) for p, ps in rows or []]
|
||||
|
||||
async def comments(self, post_id: int, user: Optional[User], cursor: Optional[int]) -> tuple[ErrorType, list[CommentView]]:
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comments(s, post_id, cursor, PAGE))
|
||||
err, rows = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comments(s, post_id, user.user_id if user else None, cursor, PAGE))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, []
|
||||
liked: set[int] = set()
|
||||
@@ -87,6 +88,8 @@ class ReactionService:
|
||||
body = body.strip()
|
||||
if not body or len(body) > COMMENT_MAX:
|
||||
return ErrorType.INVALID_INPUT, None
|
||||
if user.terms_agreed_at is None:
|
||||
return ErrorType.TERMS_REQUIRED, None
|
||||
err = await self._post_exists(post_id)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
@@ -104,3 +107,34 @@ class ReactionService:
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
return (ErrorType.NOT_FOUND, None) if count is None else (ErrorType.SUCCESS, count)
|
||||
|
||||
async def _others_comment(self, comment_id: int, user: User) -> tuple[ErrorType, Optional[uuid.UUID]]:
|
||||
"""남이 쓴, 지금 보이는 댓글의 작성자. 내 댓글이면 INVALID_INPUT."""
|
||||
err, author = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.comment_author(s, comment_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err, None
|
||||
if author is None:
|
||||
return ErrorType.NOT_FOUND, None
|
||||
return (ErrorType.INVALID_INPUT, None) if author == user.user_id else (ErrorType.SUCCESS, author)
|
||||
|
||||
async def report_comment(self, comment_id: int, user: User, reason: ReportReason) -> ErrorType:
|
||||
err, _ = await self._others_comment(comment_id, user)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.report_comment(s, comment_id, user.user_id, reason.value)])
|
||||
|
||||
async def block_author(self, comment_id: int, user: User) -> ErrorType:
|
||||
err, author = await self._others_comment(comment_id, user)
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
return await DB_SESSION_MNG.execute_lambda_run([lambda s: self.crud.block(s, user.user_id, author)])
|
||||
|
||||
async def unblock(self, user: User, blocked_id: uuid.UUID) -> ErrorType:
|
||||
err, ok = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.unblock(s, user.user_id, blocked_id))
|
||||
if err is not ErrorType.SUCCESS:
|
||||
return err
|
||||
return ErrorType.SUCCESS if ok else ErrorType.NOT_FOUND
|
||||
|
||||
async def blocked(self, user: User) -> tuple[ErrorType, list[User]]:
|
||||
err, users = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.blocked(s, user.user_id))
|
||||
return err, users or []
|
||||
@@ -43,7 +43,7 @@ def anyio_backend():
|
||||
|
||||
_VOLATILE = (
|
||||
"weather_hourly", "weather_daily", "cloud_hourly", "openmeteo_hourly", "air_station", "air_quality", "weather_warning", "sun_time",
|
||||
"sky_score", "index_score", "post", "post_like", "post_save", "comment", "comment_like", "holiday", "solar_term", "users",
|
||||
"sky_score", "index_score", "post", "post_like", "post_save", "comment", "comment_like", "comment_report", "user_block", "holiday", "solar_term", "users",
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -10,8 +10,12 @@ def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
async def _signup(c, login_id="mina_01", nickname="망원동주민"):
|
||||
return (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": nickname})).json()
|
||||
async def _signup(c, login_id="mina_01", nickname="망원동주민", agree=True):
|
||||
"""가입하고, 댓글을 쓸 수 있게 이용약관에도 동의한다 (agree=False 면 안 함)."""
|
||||
body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": nickname})).json()
|
||||
if agree and body.get("access_token"):
|
||||
await c.post("/v1/auth/terms", headers={"Authorization": f"Bearer {body['access_token']}"})
|
||||
return body
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -149,3 +153,90 @@ async def test_withdraw_deletes_account_and_reactions(offline):
|
||||
assert p["like_count"] == 0 and p["comment_count"] == 1
|
||||
# 같은 아이디로 다시 가입할 수 있다
|
||||
assert (await _signup(c, login_id="mina_bye"))["result"]["success"] is True
|
||||
|
||||
|
||||
def _h(body):
|
||||
return {"Authorization": f"Bearer {body['access_token']}"}
|
||||
|
||||
|
||||
async def _comment(c, post_id, h, text):
|
||||
return (await c.post(f"/v1/reaction/post/{post_id}/comment", headers=h, json={"body": text})).json()
|
||||
|
||||
|
||||
async def _bodies(c, post_id, h=None):
|
||||
return [x["body"] for x in (await c.get(f"/v1/reaction/post/{post_id}/comment/list", headers=h or {})).json()["comments"]]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_comment_needs_terms_agreement(offline):
|
||||
async with client() as c:
|
||||
h = _h(await _signup(c, agree=False))
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
assert (await c.get("/v1/auth/me", headers=h)).json()["me"]["terms_agreed"] is False
|
||||
assert (await _comment(c, post_id, h, "안녕"))["result"]["desc"] == "TERMS_REQUIRED"
|
||||
assert (await c.post("/v1/auth/terms", headers=h)).json()["me"]["terms_agreed"] is True
|
||||
assert (await _comment(c, post_id, h, "안녕"))["comment"]["body"] == "안녕"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_report_hides_for_reporter_then_for_all_at_three(offline):
|
||||
async with client() as c:
|
||||
writer = _h(await _signup(c, "writer_1", "쓴사람"))
|
||||
r = [_h(await _signup(c, f"reporter_{i}", f"신고자{i}")) for i in range(3)]
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
bad = (await _comment(c, post_id, writer, "광고입니다"))["comment"]
|
||||
url = f"/v1/reaction/comment/{bad['comment_id']}/report"
|
||||
|
||||
assert (await c.post(url, headers=writer, json={"reason": 2})).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
assert (await c.post(url, headers=r[0], json={"reason": 9})).status_code == 422
|
||||
assert (await c.post(url, headers=r[0], json={"reason": 2})).json()["result"]["success"] is True
|
||||
assert (await c.post(url, headers=r[0], json={"reason": 2})).json()["result"]["success"] is True # 두 번 신고해도 한 번
|
||||
assert await _bodies(c, post_id, r[0]) == [] and await _bodies(c, post_id, r[1]) == ["광고입니다"]
|
||||
|
||||
await c.post(url, headers=r[1], json={"reason": 1})
|
||||
assert await _bodies(c, post_id) == ["광고입니다"]
|
||||
await c.post(url, headers=r[2], json={"reason": 1})
|
||||
assert await _bodies(c, post_id) == [] and await _bodies(c, post_id, writer) == []
|
||||
p = next(x for x in (await c.get("/v1/feed", params={"region": REGION})).json()["posts"] if x["post_id"] == post_id)
|
||||
assert p["comment_count"] == 0
|
||||
# 숨긴 댓글을 지워도 댓글 수가 한 번 더 줄지 않는다
|
||||
assert (await c.delete(f"/v1/reaction/comment/{bad['comment_id']}", headers=writer)).json()["result"]["success"] is True
|
||||
p = next(x for x in (await c.get("/v1/feed", params={"region": REGION})).json()["posts"] if x["post_id"] == post_id)
|
||||
assert p["comment_count"] == 0
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_block_hides_author_comments_and_can_be_undone(offline):
|
||||
async with client() as c:
|
||||
me = _h(await _signup(c))
|
||||
other = _h(await _signup(c, "rude_1", "무례한"))
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
rude = (await _comment(c, post_id, other, "흥"))["comment"]
|
||||
mine = (await _comment(c, post_id, me, "좋아요"))["comment"]
|
||||
|
||||
assert (await c.post(f"/v1/reaction/comment/{mine['comment_id']}/block", headers=me)).json()["result"]["desc"] == "INVALID_INPUT"
|
||||
assert (await c.post(f"/v1/reaction/comment/{rude['comment_id']}/block")).status_code == 401
|
||||
assert (await c.post(f"/v1/reaction/comment/{rude['comment_id']}/block", headers=me)).json()["result"]["success"] is True
|
||||
assert await _bodies(c, post_id, me) == ["좋아요"] and await _bodies(c, post_id) == ["흥", "좋아요"]
|
||||
|
||||
blocked = (await c.get("/v1/reaction/block/list", headers=me)).json()["users"]
|
||||
assert [u["nickname"] for u in blocked] == ["무례한"]
|
||||
assert (await c.delete(f"/v1/reaction/block/{blocked[0]['user_id']}", headers=me)).json()["result"]["success"] is True
|
||||
assert (await c.delete(f"/v1/reaction/block/{blocked[0]['user_id']}", headers=me)).json()["result"]["desc"] == "NOT_FOUND"
|
||||
assert await _bodies(c, post_id, me) == ["흥", "좋아요"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_withdraw_removes_reports_and_blocks(offline):
|
||||
async with client() as c:
|
||||
leaver = _h(await _signup(c, "leaver_1", "떠날사람"))
|
||||
stay = _h(await _signup(c, "stay_1", "남는사람"))
|
||||
post_id = (await c.get("/v1/feed", params={"region": REGION})).json()["posts"][0]["post_id"]
|
||||
kept = (await _comment(c, post_id, stay, "남아요"))["comment"]
|
||||
gone = (await _comment(c, post_id, leaver, "떠나요"))["comment"]
|
||||
await c.post(f"/v1/reaction/comment/{kept['comment_id']}/report", headers=leaver, json={"reason": 4})
|
||||
await c.post(f"/v1/reaction/comment/{kept['comment_id']}/block", headers=leaver)
|
||||
await c.post(f"/v1/reaction/comment/{gone['comment_id']}/block", headers=stay)
|
||||
assert (await c.delete("/v1/auth/me", headers=leaver)).json()["result"]["success"] is True
|
||||
assert (await c.get("/v1/reaction/block/list", headers=stay)).json()["users"] == []
|
||||
assert await _bodies(c, post_id, stay) == ["남아요"]
|
||||
@@ -0,0 +1,80 @@
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from jose import jwk, jwt
|
||||
|
||||
import common.google_id as google_id
|
||||
import services.auth_service as auth_service
|
||||
from config.settings import settings
|
||||
from router.router import app
|
||||
|
||||
CLIENT_ID = "test-client.apps.googleusercontent.com"
|
||||
|
||||
|
||||
def client():
|
||||
return AsyncClient(transport=ASGITransport(app=app), base_url="http://test")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def google_keys(monkeypatch):
|
||||
"""가짜 구글 서명키. 공개키는 _keys 대신 돌려준다."""
|
||||
monkeypatch.setattr(settings, "google_client_id", CLIENT_ID)
|
||||
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
pem = key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())
|
||||
public = jwk.construct(key.public_key().public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo), "RS256").to_dict()
|
||||
public["kid"] = "k1"
|
||||
|
||||
async def keys(force: bool = False):
|
||||
return [public]
|
||||
|
||||
monkeypatch.setattr(google_id, "_keys", keys)
|
||||
|
||||
def sign(**over):
|
||||
claims = {"iss": "https://accounts.google.com", "aud": CLIENT_ID, "sub": "1234567890", "exp": int(time.time()) + 600, "iat": int(time.time()), "name": "홍길동", "email": "a@example.com"}
|
||||
claims.update(over)
|
||||
return jwt.encode(claims, pem, algorithm="RS256", headers={"kid": "k1"})
|
||||
|
||||
return sign
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_verify_accepts_only_our_valid_tokens(google_keys):
|
||||
assert await google_id.verify(google_keys()) == "1234567890"
|
||||
assert await google_id.verify(google_keys(aud="other.apps.googleusercontent.com")) is None
|
||||
assert await google_id.verify(google_keys(iss="https://evil.example")) is None
|
||||
assert await google_id.verify(google_keys(exp=int(time.time()) - 10)) is None
|
||||
assert await google_id.verify(google_keys()[:-4] + "abcd") is None
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_google_login_creates_once_with_auto_nickname_and_no_real_name(google_keys):
|
||||
async with client() as c:
|
||||
first = (await c.post("/v1/auth/google", json={"credential": google_keys()})).json()
|
||||
assert first["access_token"] and first["me"]["provider"] == 2
|
||||
nick = first["me"]["nickname"]
|
||||
assert "홍길동" not in nick and "@" not in nick
|
||||
again = (await c.post("/v1/auth/google", json={"credential": google_keys()})).json()
|
||||
assert again["me"]["nickname"] == nick and again["me"]["login_id"] == first["me"]["login_id"]
|
||||
other = (await c.post("/v1/auth/google", json={"credential": google_keys(sub="999")})).json()
|
||||
assert other["me"]["login_id"] != first["me"]["login_id"]
|
||||
bad = (await c.post("/v1/auth/google", json={"credential": google_keys(aud="x")})).json()
|
||||
assert bad["result"]["desc"] == "AUTH_FAILED"
|
||||
me = (await c.get("/v1/auth/me", headers={"Authorization": f"Bearer {first['access_token']}"})).json()["me"]
|
||||
assert me["nickname"] == nick
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_config_exposes_client_id_only_when_set(monkeypatch):
|
||||
async with client() as c:
|
||||
monkeypatch.setattr(settings, "google_client_id", "")
|
||||
assert "google_client_id" not in (await c.get("/v1/auth/config")).json()
|
||||
monkeypatch.setattr(settings, "google_client_id", CLIENT_ID)
|
||||
assert (await c.get("/v1/auth/config")).json()["google_client_id"] == CLIENT_ID
|
||||
|
||||
|
||||
def test_auto_nickname_fits_nickname_rule():
|
||||
for _ in range(50):
|
||||
assert auth_service.NICKNAME.match(auth_service.auto_nickname())
|
||||
@@ -84,6 +84,7 @@ async def test_like_in_one_sido_not_seen_in_another(offline):
|
||||
async with client() as c:
|
||||
token = (await c.post("/v1/auth/signup", json={"login_id": "scope_01", "password": "password1", "nickname": "시도테스트"})).json()["access_token"]
|
||||
h = {"Authorization": f"Bearer {token}"}
|
||||
await c.post("/v1/auth/terms", headers=h)
|
||||
seoul = (await c.get("/v1/feed", params={"region": SEOUL_A}, headers=h)).json()
|
||||
post_id = next(p["post_id"] for p in seoul["posts"] if p["post_type"] == PostType.WEATHER.value)
|
||||
assert (await c.post(f"/v1/reaction/post/{post_id}/like", headers=h)).json()["like_count"] == 1
|
||||
|
||||
Reference in new issue
Block a user