diff --git a/.env.example b/.env.example index 78144b6..fbc4b1a 100644 --- a/.env.example +++ b/.env.example @@ -20,6 +20,8 @@ PORT=9810 # ── 백엔드: 로그인 토큰 서명 키. 비우면 로그인이 동작하지 않는다 # 생성: python -c "import secrets; print(secrets.token_urlsafe(48))" +# 구글 로그인 OAuth 클라이언트 ID (console.cloud.google.com/apis/credentials, 웹 애플리케이션) +GOOGLE_CLIENT_ID= JWT_ACCESS_SECRET= JWT_REFRESH_SECRET= diff --git a/TODO.md b/TODO.md index 2e2005a..9a5bce5 100644 --- a/TODO.md +++ b/TODO.md @@ -176,7 +176,18 @@ | [ ] | 백엔드 테스트 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` | +| [x] | 앱 ID: 안드로이드 패키지 `kr.o2o.nalssigak` — Play Console 기존 '날씨각'(Wear OS 트랙에 워치 앱 있음)에 휴대전화 앱으로 추가하려면 패키지명이 같아야 함. iOS 번들 ID는 미정 | 스토어에 올리면 못 바꿈 | `mobile/app.json` | +| [x] | Play 제출: 휴대전화 versionCode 1000부터 (10/23 `app.json` versionCode 1000, 로컬 빌드)(워치가 1 사용) — `eas login` 후 `eas build:version:set -p android` | 같은 앱 안에서 versionCode 겹치면 안 됨 | `mobile/eas.json` | +| [x] | Play 제출: 워치 앱과 같은 업로드 키 (10/23 로컬 빌드로 서명 확인, SHA-1 D3:51…44:79. 비밀번호는 ~/.gradle/gradle.properties `NALSSIGAK_UPLOAD_*`)(.jks)를 `eas credentials -p android`로 등록 (사용자: 키 파일·비밀번호 준비, 분실 시 Play Console에서 업로드 키 재설정) | EAS는 안 넣으면 새 키를 만듦 | | +| [ ] | 출시 aab 서명 설정이 생성 폴더 `mobile/android/app/build.gradle`에만 있음 — `expo prebuild --clean` 하면 지워지니 다시 넣거나 config plugin으로 옮기기 | `android/`는 gitignore·재생성 | `mobile/android/app/build.gradle` | +| [ ] | 앱 구글 로그인 기기 확인: 네이티브 다시 빌드 → 구글 계정 로그인된 에뮬레이터(Play 서비스 이미지)에서 구글로 계속하기 | 새 네이티브 모듈이라 지금 설치된 개발 빌드엔 없음. Android 클라이언트(개발·Play SHA-1)는 콘솔에 등록됨 | `mobile/src/components/sheets/google.tsx` | +| [ ] | 운영 서버 `.env`에 `GOOGLE_CLIENT_ID`(웹 클라이언트 ID) 넣고 구글 로그인 백엔드 배포 | 비어 있으면 `/v1/auth/config`가 ID를 안 줘서 앱·웹 구글 버튼이 숨음 | `backend/config/settings.py` | +| [ ] | Play 제출(사용자): 휴대전화 스크린샷 2장+, 개인정보처리방침 URL, 계정 삭제 URL(웹 '탈퇴하기' 운영 배포 후), 데이터 보안 양식(대략 위치·계정 정보·댓글), 콘텐츠 등급, 앱 액세스용 심사 테스트 계정. 개인 계정(2023.11 이후)이면 비공개 테스트 12명·14일 | | | +| [x] | Play UGC 정책(댓글): 처음 댓글 쓸 때 이용약관 동의(`POST /v1/auth/terms`), 남의 댓글 ⋯ → 신고(이유 4가지, 신고한 사람에겐 바로 숨김, 3건이면 모두에게 숨김) / 이 사람 차단, 내 정보 '차단한 사람'·풀기, 운영 조치 `scripts/moderate.py`(숨김·되살림·정지), 탈퇴 때 신고·차단도 삭제 | Play 'User Generated Content' 정책 | `backend/`, `frontend/src/b/Sheets.tsx`, `frontend/public/terms.html`, `mobile/src/components/sheets/` | +| [ ] | 운영 DB 반영: `init.sql`의 `users.terms_agreed_at`, `comment.report_count`·`is_hidden`, `comment_report`, `user_block` (ALTER·CREATE IF NOT EXISTS) — 코드 배포 전에 먼저 | 새 코드가 이 칼럼을 읽음 | `backend/postgres-init/init.sql` | +| [ ] | **[검토 필요]** 이용약관 초안 문구 검토 | 법무 문구라 확인 필요 | `frontend/public/terms.html` | +| [ ] | 개인정보처리방침에 휴대전화 앱·댓글·신고·차단 기록 추가 (지금은 웹·워치 앱만 적혀 있음) | Play 데이터 보안 양식과 맞아야 함 | `frontend/public/privacy.html` | +| [x] | 앱 신고·차단·약관 화면 안드로이드 확인: ⋯ 메뉴, 차단 확인·안내·목록에서 빠짐, 약관 동의 후 바로 게시, 내 정보 '차단한 사람' 풀기 (신고 흐름은 백엔드 테스트로만). 새 패키지 `kr.o2o.nalssigak` 개발 빌드로 다시 설치함 | | `mobile/` | | [ ] | 오늘 날씨 칸(3시·6시 등)이 '?' — 백엔드가 며칠 꺼져 있다 켜지면 최신 발표(예: 8시, 9시부터 예보)만 받아 새벽 칸 행이 없음. 0시 재수신(`_midnight_missing`)은 0시에 묵은 값이 있으면 안 돎. 운영은 늘 켜져 있어 드묾 — 고칠 땐 오늘 칸 중 비거나 묵은 칸이 있으면 다시 받기 | 10/19 로컬(9811)에서 확인, 앱·웹 버그 아님 | `backend/services/weather_service.py` (`today`, `ensure_vilage`, `_midnight_missing`) | | [x] | 앱 아이콘 3D 해 그림(600px 원본)으로: iOS 1024, 안드로이드 적응형(앞·뒤·단색), 스플래시. Expo Go 에선 안 보이고 개발 빌드부터 보임. 스토어용으로는 1024px 이상 원본이 있으면 더 선명 | | `mobile/assets/images/` | | [x] | 3단계-1: 탭 5개 구조·위 막대·하늘 배경·밤 테마(Uniwind dark), Today 히어로·각 순위·행사/TOP5/계절 띠 | | `mobile/src/app/`, `mobile/src/components/` | diff --git a/backend/common/database/model/models.py b/backend/common/database/model/models.py index 3e2bca0..cd215d0 100644 --- a/backend/common/database/model/models.py +++ b/backend/common/database/model/models.py @@ -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" diff --git a/backend/common/enums.py b/backend/common/enums.py index 19d43ec..edadb4a 100644 --- a/backend/common/enums.py +++ b/backend/common/enums.py @@ -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 diff --git a/backend/common/google_id.py b/backend/common/google_id.py new file mode 100644 index 0000000..a01529b --- /dev/null +++ b/backend/common/google_id.py @@ -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"]) diff --git a/backend/config/settings.py b/backend/config/settings.py index f56e97b..025a102 100644 --- a/backend/config/settings.py +++ b/backend/config/settings.py @@ -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 diff --git a/backend/crud/reaction_crud.py b/backend/crud/reaction_crud.py index 753e757..871a832 100644 --- a/backend/crud/reaction_crud.py +++ b/backend/crud/reaction_crud.py @@ -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()) diff --git a/backend/crud/user_crud.py b/backend/crud/user_crud.py index 61797f3..1a20590 100644 --- a/backend/crud/user_crud.py +++ b/backend/crud/user_crud.py @@ -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)) diff --git a/backend/postgres-init/init.sql b/backend/postgres-init/init.sql index 14452c1..2a87c0e 100644 --- a/backend/postgres-init/init.sql +++ b/backend/postgres-init/init.sql @@ -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, diff --git a/backend/router/v1/auth/account.py b/backend/router/v1/auth/account.py index 81a4fc0..d60a927 100644 --- a/backend/router/v1/auth/account.py +++ b/backend/router/v1/auth/account.py @@ -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) diff --git a/backend/router/v1/auth/protocol.py b/backend/router/v1/auth/protocol.py index 5e0352f..1b551f6 100644 --- a/backend/router/v1/auth/protocol.py +++ b/backend/router/v1/auth/protocol.py @@ -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. 없으면 구글 로그인을 숨긴다") diff --git a/backend/router/v1/reaction/protocol.py b/backend/router/v1/reaction/protocol.py index cfbf179..e1515bc 100644 --- a/backend/router/v1/reaction/protocol.py +++ b/backend/router/v1/reaction/protocol.py @@ -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] = [] diff --git a/backend/router/v1/reaction/reaction.py b/backend/router/v1/reaction/reaction.py index c6187a0..28dc892 100644 --- a/backend/router/v1/reaction/reaction.py +++ b/backend/router/v1/reaction/reaction.py @@ -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))) diff --git a/backend/scripts/moderate.py b/backend/scripts/moderate.py new file mode 100644 index 0000000..c71187d --- /dev/null +++ b/backend/scripts/moderate.py @@ -0,0 +1,64 @@ +"""운영자용 댓글·사용자 조치. + + python scripts/moderate.py reports 신고 받은 댓글 (많은 순 30개) + python scripts/moderate.py hide 댓글 숨김 + python scripts/moderate.py show 숨긴 댓글 되살림 + python scripts/moderate.py suspend 이용 정지 (로그인·토큰 막힘) + python scripts/moderate.py resume 정지 풀기 +""" +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:]))) diff --git a/backend/services/auth_service.py b/backend/services/auth_service.py index c079c55..b54a04a 100644 --- a/backend/services/auth_service.py +++ b/backend/services/auth_service.py @@ -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)]) diff --git a/backend/services/reaction_service.py b/backend/services/reaction_service.py index 5592902..e487038 100644 --- a/backend/services/reaction_service.py +++ b/backend/services/reaction_service.py @@ -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 [] diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 4b433f2..495a7d1 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -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", ) diff --git a/backend/tests/test_auth_reaction.py b/backend/tests/test_auth_reaction.py index 15aa248..277f597 100644 --- a/backend/tests/test_auth_reaction.py +++ b/backend/tests/test_auth_reaction.py @@ -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) == ["남아요"] diff --git a/backend/tests/test_google_login.py b/backend/tests/test_google_login.py new file mode 100644 index 0000000..2802afb --- /dev/null +++ b/backend/tests/test_google_login.py @@ -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()) diff --git a/backend/tests/test_post_scope.py b/backend/tests/test_post_scope.py index e981c46..14df053 100644 --- a/backend/tests/test_post_scope.py +++ b/backend/tests/test_post_scope.py @@ -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 diff --git a/frontend/public/terms.html b/frontend/public/terms.html new file mode 100644 index 0000000..cad4356 --- /dev/null +++ b/frontend/public/terms.html @@ -0,0 +1,61 @@ + + + + + +이용약관 - 날씨각 + + + + +
+

이용약관

+

시행일: 2026년 10월 20일

+ +

이 약관은 AIO2O(이하 "회사")가 운영하는 날씨각 웹·앱 서비스(이하 "서비스")를 이용하는 조건을 정합니다. 댓글을 쓰려면 이 약관에 동의해야 합니다.

+ +

1. 서비스

+

서비스는 지역별 날씨, 하늘·노을 예보, 생활 지수, 주변 행사 같은 정보를 제공합니다. 날씨 정보는 기상청 등 외부 자료를 바탕으로 한 예보이며 실제 날씨와 다를 수 있습니다.

+ +

2. 계정

+

회원은 자신의 계정을 직접 관리해야 하며, 다른 사람에게 빌려주거나 넘길 수 없습니다. 회원은 언제든지 내 정보에서 탈퇴할 수 있고, 탈퇴하면 계정과 남긴 댓글·좋아요·저장·신고·차단 기록이 모두 지워집니다.

+ +

3. 댓글에 쓰면 안 되는 내용

+

아래 내용은 댓글로 쓸 수 없습니다.

+
    +
  • 욕설, 비하, 혐오, 따돌림, 위협
  • +
  • 광고, 홍보, 같은 내용 반복 게시
  • +
  • 전화번호·주소 등 자신이나 다른 사람의 개인정보
  • +
  • 음란하거나 폭력적인 내용, 불법 행위를 부추기는 내용
  • +
  • 다른 사람의 권리(저작권·초상권·명예 등)를 침해하는 내용
  • +
+ +

4. 신고·차단과 조치

+

회원은 댓글마다 신고하거나 그 댓글을 쓴 사람을 차단할 수 있습니다. 신고한 댓글과 차단한 사람의 댓글은 본인에게 더는 보이지 않습니다. 신고가 여러 건 쌓인 댓글은 자동으로 숨겨지고, 회사가 확인해 3항을 어긴 댓글은 숨기거나 지우며, 반복해서 어긴 회원은 서비스 이용을 제한할 수 있습니다. 조치에 이의가 있으면 아래 연락처로 알려 주세요.

+ +

5. 게시물의 권리와 책임

+

댓글의 권리와 책임은 작성한 회원에게 있습니다. 회사는 서비스 화면에 댓글을 보여 주는 범위에서만 이를 사용합니다.

+ +

6. 서비스 변경·중단

+

회사는 운영상 필요하면 서비스 내용을 바꾸거나 중단할 수 있으며, 중요한 변경은 미리 서비스 안에 알립니다.

+ +

7. 책임의 한계

+

회사는 예보와 실제 날씨의 차이, 회원 사이의 다툼, 회원이 쓴 댓글로 생긴 손해에 대해 회사의 고의나 중대한 과실이 없으면 책임지지 않습니다.

+ +

8. 개인정보

+

개인정보 처리는 개인정보처리방침을 따릅니다.

+ +

9. 문의

+

운영자: AIO2O
이메일: o2odev@o2o.kr

+ +

10. 약관 변경

+

이 약관이 바뀌면 시행 7일 전부터 이 페이지에 알립니다.

+
+ + diff --git a/frontend/src/b/Sheets.tsx b/frontend/src/b/Sheets.tsx index f65e784..fc4ede8 100644 --- a/frontend/src/b/Sheets.tsx +++ b/frontend/src/b/Sheets.tsx @@ -4,6 +4,8 @@ import { clearTokens, setTokens, subscribeAuth } from '@nalssigak/shared/api/aut import { SITE_URL } from '../api/setup' import { addCommentMutation, + agreeTermsMutation, + blockAuthorMutation, deleteCommentMutation, getArticleOptions, getFeedQueryKey, @@ -11,20 +13,25 @@ import { getSeasonWeekOptions, likeCommentMutation, listCommentsInfiniteOptions, + listBlockedOptions, + listBlockedQueryKey, listCommentsInfiniteQueryKey, listRegionsOptions, loginMutation, meQueryKey, + reportCommentMutation, signupMutation, + unblockMutation, 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 { ReportReason, type CommentData, type Factor, type ResAuth, type ResCommentList, type ResIndexDetail } from '@nalssigak/shared/api/client/types.gen' import { track } from '../lib/analytics' import { cx } from '../lib/utils' import { useAuth } from './authContext' import { ago, articleMeta, AVATAR_COLORS, cardBg, CHARACTERS, dateRange, loadOf, MOODS, shortDay } from '@nalssigak/shared/lib' +import { GoogleButton } from './googleLogin' import { ARTICLE_CAT } from './lib' import { useRegion } from './regionContext' import { useSky } from './skyContext' @@ -611,8 +618,88 @@ function ShareSheet({ share }: { share: SharePayload }) { /* ---------- 댓글 ---------- */ const NOT_FOUND = 3001 // 서버 ErrorType.NOT_FOUND const EMOJIS = ['☀️', '🌂', '🍻', '🌇', '😍', '👍'] +const REPORT_REASONS = [ + [ReportReason.ABUSE, '욕설·비하'], + [ReportReason.AD, '광고'], + [ReportReason.PRIVACY, '개인정보 노출'], + [ReportReason.OTHER, '기타'], +] as const +const isCommentList = (q: { queryKey: readonly unknown[] }) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'listComments' -function CommentRow({ c, postId }: { c: CommentData; postId: number }) { +/** 남의 댓글: ⋯ → 신고하기(이유 고르기) / 이 사람 차단하기(한 번 더 묻기). 끝나면 목록을 다시 받아 그 댓글이 빠진다 */ +function CommentMenu({ c, postId, onNotice }: { c: CommentData; postId: number; onNotice: (text: string) => void }) { + const { loggedIn } = useAuth() + const { open } = useSheet() + const queryClient = useQueryClient() + const [step, setStep] = useState<'closed' | 'menu' | 'report' | 'block'>('closed') + const [failed, setFailed] = useState(false) + const report = useMutation(reportCommentMutation()) + const block = useMutation(blockAuthorMutation()) + const pending = report.isPending || block.isPending + + const finish = (notice: string) => ({ + onSuccess: (res: { result?: { success?: boolean } }) => { + if (!res.result?.success) return setFailed(true) + setStep('closed') + onNotice(notice) + queryClient.invalidateQueries({ predicate: isCommentList }) + queryClient.invalidateQueries({ queryKey: listBlockedQueryKey() }) + }, + onError: () => setFailed(true), + }) + const go = (next: typeof step) => { + setFailed(false) + if (next !== 'closed' && !loggedIn) return open({ type: 'login', then: { type: 'comments', postId } }) + setStep(next) + } + const btn = 'cursor-pointer rounded-[12px] bg-[#f3f6fb] px-3 py-2 text-[13px] font-extrabold text-(--ink) disabled:opacity-50' + + return ( + <> + + {step !== 'closed' && ( + + {step === 'menu' && ( + <> + + + + )} + {step === 'report' && + REPORT_REASONS.map(([reason, label]) => ( + + ))} + {step === 'block' && ( + <> + {c.nickname}님 댓글을 더는 안 볼까요? + + + + )} + {failed && ( + + 잠시 뒤에 다시 해 주세요. + + )} + + )} + + ) +} + +function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; onNotice: (text: string) => void }) { const { region } = useRegion() const { loggedIn } = useAuth() const { open } = useSheet() @@ -697,6 +784,7 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) { )} + {!c.mine && } - ))} - -

- {addFailed && '댓글을 올리지 못했어요. 다시 해 주세요.'} + {askTerms ? ( +

+

댓글을 쓰려면 이용약관에 동의해 주세요. 욕설·광고·개인정보 노출은 숨겨지고, 계속되면 이용이 제한돼요.

+
+ + 이용약관 보기 + + +
+
+ ) : ( +
+ {EMOJIS.map((e) => ( + + ))} +
+ )} +

+ {addFailed ? '댓글을 올리지 못했어요. 다시 해 주세요.' : notice}

setText(e.target.value)} readOnly={add.isPending} maxLength={60} placeholder={me ? `${me.nickname}(으)로 댓글 달기…` : '댓글 달기…'} aria-label="댓글" className="min-w-0 flex-1 rounded-full border border-[#dfe5ee] bg-[#f7f9fc] px-3.5 py-2.5" /> @@ -809,13 +942,13 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () const signup = useMutation(signupMutation()) const pending = login.isPending || signup.isPending - const done = (res: ResAuth) => { + const done = (res: ResAuth, method: 'id' | 'google' = 'id') => { if (!res.result?.success || !res.access_token) { - setError(AUTH_ERRORS[res.result?.desc ?? ''] ?? '잠시 뒤에 다시 해 주세요.') + setError(method === 'google' ? '구글로 로그인하지 못했어요. 다시 해 주세요.' : (AUTH_ERRORS[res.result?.desc ?? ''] ?? '잠시 뒤에 다시 해 주세요.')) return } setTokens(res.access_token, res.refresh_token ?? null) - track(mode === 'login' ? 'login' : 'sign_up', { method: 'id' }) + track(method === 'google' ? 'login' : mode === 'login' ? 'login' : 'sign_up', { method }) onLoggedIn() } const fail = () => setError('서버에 닿지 못했어요. 잠시 뒤에 다시 해 주세요.') @@ -823,8 +956,8 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () const submit = (e: FormEvent) => { e.preventDefault() setError('') - if (mode === 'login') login.mutate({ body: { login_id: loginId.trim(), password } }, { onSuccess: done, onError: fail }) - else signup.mutate({ body: { login_id: loginId.trim(), password, nickname: nickname.trim() } }, { onSuccess: done, onError: fail }) + if (mode === 'login') login.mutate({ body: { login_id: loginId.trim(), password } }, { onSuccess: (res) => done(res), onError: fail }) + else signup.mutate({ body: { login_id: loginId.trim(), password, nickname: nickname.trim() } }, { onSuccess: (res) => done(res), onError: fail }) } if (me) return @@ -833,7 +966,8 @@ function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLoggedIn: () return ( -

좋아요·댓글은 로그인한 뒤에 할 수 있어요.

+

글쓰기·댓글은 로그인한 뒤에 할 수 있어요.

+ done(res, 'google')} onFail={fail} />
{( [ @@ -909,6 +1043,47 @@ function Withdraw({ onDone }: { onDone: () => void }) { ) } +/** 차단한 사람: 있을 때만 보이고, 풀면 그 사람 댓글이 다시 보인다 */ +function Blocked() { + const queryClient = useQueryClient() + const list = useQuery(listBlockedOptions()) + const unblock = useMutation(unblockMutation()) + const [failed, setFailed] = useState(false) + const users = list.data?.users ?? [] + if (!users.length) return null + const release = (user_id: string) => { + setFailed(false) + unblock.mutate( + { path: { user_id } }, + { + onSuccess: (res) => { + if (!res.result?.success) return setFailed(true) + queryClient.invalidateQueries({ queryKey: listBlockedQueryKey() }) + queryClient.invalidateQueries({ predicate: isCommentList }) + }, + onError: () => setFailed(true), + }, + ) + } + return ( +
+

차단한 사람

+
    + {users.map((u) => ( +
  • + + {u.nickname} + +
  • + ))} +
+ {failed &&

잠시 뒤에 다시 해 주세요.

} +
+ ) +} + function MeSheet({ onDone }: { onDone: () => void }) { const { me, logout } = useAuth() const queryClient = useQueryClient() @@ -1027,6 +1202,7 @@ function MeSheet({ onDone }: { onDone: () => void }) { > 로그아웃 + ) diff --git a/frontend/src/b/googleLogin.tsx b/frontend/src/b/googleLogin.tsx new file mode 100644 index 0000000..067b07c --- /dev/null +++ b/frontend/src/b/googleLogin.tsx @@ -0,0 +1,83 @@ +import { useMutation, useQuery } from '@tanstack/react-query' +import { useEffect, useRef, useState } from 'react' +import { authConfigOptions, googleLoginMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen' +import type { ResAuth } from '@nalssigak/shared/api/client/types.gen' + +type GoogleId = { + initialize: (o: { client_id: string; callback: (r: { credential?: string }) => void; ux_mode?: 'popup' }) => void + renderButton: (el: HTMLElement, o: Record) => void +} +declare global { + interface Window { + google?: { accounts: { id: GoogleId } } + } +} + +const SCRIPT = 'https://accounts.google.com/gsi/client' +let loading: Promise | null = null + +/** 구글 로그인 스크립트는 로그인 창을 처음 열 때 한 번만 받는다 */ +function loadGoogle(): Promise { + if (window.google?.accounts.id) return Promise.resolve(window.google.accounts.id) + loading ??= new Promise((resolve, reject) => { + const s = document.createElement('script') + s.src = SCRIPT + s.async = true + s.onload = () => (window.google?.accounts.id ? resolve(window.google.accounts.id) : reject(new Error('gsi missing'))) + s.onerror = () => { + loading = null + reject(new Error('gsi load failed')) + } + document.head.appendChild(s) + }) + return loading +} + +/** 구글로 계속하기 버튼. 서버에 클라이언트 ID가 없으면 아무것도 그리지 않는다 */ +export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) { + const clientId = useQuery({ ...authConfigOptions(), staleTime: Infinity }).data?.google_client_id + const login = useMutation(googleLoginMutation()) + const box = useRef(null) + const [broken, setBroken] = useState(false) + const { mutate } = login + // 로그인 창이 다시 그려질 때마다 버튼을 새로 만들지 않게 콜백은 ref 로 들고 있는다 + const cb = useRef({ onResult, onFail }) + useEffect(() => { + cb.current = { onResult, onFail } + }, [onResult, onFail]) + + useEffect(() => { + if (!clientId || !box.current) return + let alive = true + loadGoogle().then( + (g) => { + if (!alive || !box.current) return + g.initialize({ + client_id: clientId, + ux_mode: 'popup', + callback: (r) => { + if (!r.credential) return cb.current.onFail() + mutate({ body: { credential: r.credential } }, { onSuccess: (res) => cb.current.onResult(res), onError: () => cb.current.onFail() }) + }, + }) + g.renderButton(box.current, { theme: 'outline', size: 'large', shape: 'pill', text: 'continue_with', locale: 'ko', width: box.current.offsetWidth }) + }, + (e: unknown) => { + console.error('[google] script', e) + if (alive) setBroken(true) + }, + ) + return () => { + alive = false + } + }, [clientId, mutate]) + + if (!clientId) return null + return ( +
+
+ {broken &&

구글 로그인을 불러오지 못했어요. 아이디로 로그인해 주세요.

} +

또는 아이디로

+
+ ) +} diff --git a/frontend/src/lib/analytics.ts b/frontend/src/lib/analytics.ts index b8d2cf9..2c44413 100644 --- a/frontend/src/lib/analytics.ts +++ b/frontend/src/lib/analytics.ts @@ -3,7 +3,7 @@ type Events = { view_gak: { index_id: number; gak_name: string; score: number; rank: number } select_content: { content_type: 'article'; item_id: number; category: string } share: { content_type: 'image'; item_id: string; method: 'share_sheet' | 'download'; ratio: string } - login: { method: 'id' } + login: { method: 'id' | 'google' } sign_up: { method: 'id' } region_change: { region_name: string; method: 'list' | 'location' } } diff --git a/mobile/app.json b/mobile/app.json index 11b1630..c3567df 100644 --- a/mobile/app.json +++ b/mobile/app.json @@ -14,6 +14,7 @@ } }, "android": { + "versionCode": 1000, "adaptiveIcon": { "backgroundColor": "#bbeafd", "foregroundImage": "./assets/images/android-icon-foreground.png", @@ -24,7 +25,7 @@ "permissions": [ "android.permission.ACCESS_COARSE_LOCATION" ], - "package": "com.anonymous.nalssigak", + "package": "kr.o2o.nalssigak", "blockedPermissions": [ "android.permission.ACCESS_FINE_LOCATION", "android.permission.SYSTEM_ALERT_WINDOW", @@ -53,7 +54,8 @@ { "locationWhenInUsePermission": "가장 가까운 동네 날씨를 보여 드리려고 위치를 써요." } - ] + ], + "@react-native-google-signin/google-signin" ], "experiments": { "typedRoutes": true, diff --git a/mobile/package.json b/mobile/package.json index 474ea4c..9d86f31 100644 --- a/mobile/package.json +++ b/mobile/package.json @@ -8,6 +8,7 @@ "@expo-google-fonts/jua": "^0.4.1", "@expo/ui": "~57.0.23", "@nalssigak/shared": "*", + "@react-native-google-signin/google-signin": "^16.1.5", "@tanstack/react-query": "^5.104.2", "expo": "~57.0.28", "expo-constants": "~57.0.21", diff --git a/mobile/src/components/sheets/comments.tsx b/mobile/src/components/sheets/comments.tsx index 5881e18..00fb10f 100644 --- a/mobile/src/components/sheets/comments.tsx +++ b/mobile/src/components/sheets/comments.tsx @@ -1,29 +1,114 @@ import { addCommentMutation, + agreeTermsMutation, + blockAuthorMutation, deleteCommentMutation, getFeedQueryKey, likeCommentMutation, + listBlockedQueryKey, listCommentsInfiniteOptions, listCommentsInfiniteQueryKey, + meQueryKey, + reportCommentMutation, unlikeCommentMutation, } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'; -import type { CommentData, ResCommentList } from '@nalssigak/shared/api/client/types.gen'; +import { ReportReason, type CommentData, type ResCommentList } from '@nalssigak/shared/api/client/types.gen'; import { ago, loadOf } from '@nalssigak/shared/lib'; import { useInfiniteQuery, useMutation, useQueryClient, type InfiniteData } from '@tanstack/react-query'; -import { useRef, useState } from 'react'; -import { Pressable, Text, TextInput, View } from 'react-native'; +import { useEffect, useRef, useState } from 'react'; +import { Linking, Pressable, TextInput, View } from 'react-native'; +import { Text } from '@/components/text'; import { useCSSVariable } from 'uniwind'; import { Avatar, Skel, StateBox } from '@/components/ui'; import { useAuth } from '@/lib/auth'; import { useRegion } from '@/lib/region'; import { useSheet } from '@/lib/sheet'; +import { SITE_URL } from '@/lib/site'; -import { Body, ErrorLine, Field, HeartIcon } from './parts'; +import { Body, ErrorLine, Field, HeartIcon, useSoft } from './parts'; const NOT_FOUND = 3001; // 서버 ErrorType.NOT_FOUND const EMOJIS = ['☀️', '🌂', '🍻', '🌇', '😍', '👍']; const N3 = [0, 1, 2]; +const REPORT_REASONS = [ + [ReportReason.ABUSE, '욕설·비하'], + [ReportReason.AD, '광고'], + [ReportReason.PRIVACY, '개인정보 노출'], + [ReportReason.OTHER, '기타'], +] as const; +export const isCommentList = (q: { queryKey: readonly unknown[] }) => (q.queryKey[0] as { _id?: string } | undefined)?._id === 'listComments'; + +function Chip({ label, onPress, disabled, danger }: { label: string; onPress: () => void; disabled?: boolean; danger?: boolean }) { + const s = useSoft(); + return ( + + {label} + + ); +} + +/** 남의 댓글: ⋯ → 신고하기(이유 고르기) / 이 사람 차단하기(한 번 더 묻기). 끝나면 목록을 다시 받아 그 댓글이 빠진다 */ +function CommentMenu({ c, postId, onNotice }: { c: CommentData; postId: number; onNotice: (text: string) => void }) { + const { loggedIn } = useAuth(); + const { open } = useSheet(); + const queryClient = useQueryClient(); + const [step, setStep] = useState<'closed' | 'menu' | 'report' | 'block'>('closed'); + const [failed, setFailed] = useState(false); + const report = useMutation(reportCommentMutation()); + const block = useMutation(blockAuthorMutation()); + const pending = report.isPending || block.isPending; + + const finish = (notice: string) => ({ + onSuccess: (res: { result?: { success?: boolean } }) => { + if (!res.result?.success) return setFailed(true); + setStep('closed'); + onNotice(notice); + queryClient.invalidateQueries({ predicate: isCommentList }); + queryClient.invalidateQueries({ queryKey: listBlockedQueryKey() }); + }, + onError: () => setFailed(true), + }); + const go = (next: typeof step) => { + setFailed(false); + if (next !== 'closed' && !loggedIn) return open({ type: 'login', then: { type: 'comments', postId } }); + setStep(next); + }; + + return ( + <> + go(step === 'closed' ? 'menu' : 'closed')} hitSlop={10} accessibilityRole="button" accessibilityState={{ expanded: step !== 'closed' }} accessibilityLabel="댓글 메뉴" className="px-1"> + ⋯ + + {step !== 'closed' && ( + + {step === 'menu' && ( + <> + go('report')} /> + go('block')} /> + + )} + {step === 'report' && + REPORT_REASONS.map(([reason, label]) => ( + report.mutate({ path: { comment_id: c.comment_id }, body: { reason } }, finish('신고했어요. 확인하고 조치할게요.'))} /> + ))} + {step === 'block' && ( + <> + {c.nickname}님 댓글을 더는 안 볼까요? + block.mutate({ path: { comment_id: c.comment_id } }, finish('차단했어요. 내 정보에서 풀 수 있어요.'))} /> + go('closed')} /> + + )} + {failed && ( + + 잠시 뒤에 다시 해 주세요. + + )} + + )} + + ); +} function CommentsSkel() { return ( @@ -41,7 +126,7 @@ function CommentsSkel() { ); } -function CommentRow({ c, postId }: { c: CommentData; postId: number }) { +function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; onNotice: (text: string) => void }) { const { region } = useRegion(); const { loggedIn } = useAuth(); const { open } = useSheet(); @@ -117,17 +202,20 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) { {c.nickname} {c.body} - - {ago(c.created_at)} · {likeFailed ? 좋아요를 못 했어요. 잠시 뒤에 다시 눌러 주세요 : `좋아요 ${count}개`} - {c.mine && ( - <> - {' · '} - - {remove.isPending ? '지우는 중…' : removeFailed ? '못 지웠어요 · 다시' : '지우기'} - - - )} - + + + {ago(c.created_at)} · {likeFailed ? 좋아요를 못 했어요. 잠시 뒤에 다시 눌러 주세요 : `좋아요 ${count}개`} + {c.mine && ( + <> + {' · '} + + {remove.isPending ? '지우는 중…' : removeFailed ? '못 지웠어요 · 다시' : '지우기'} + + + )} + + {!c.mine && } + @@ -147,13 +235,22 @@ export function CommentsSheet({ postId, draft }: { postId: number; draft?: strin getNextPageParam: (last) => last.next_cursor ?? undefined, }); const add = useMutation(addCommentMutation()); + const agree = useMutation(agreeTermsMutation()); + const s = useSoft(); const [addFailed, setAddFailed] = useState(false); + const [askTerms, setAskTerms] = useState(false); + const [notice, setNotice] = useState(''); const [text, setText] = useState(draft ?? ''); const inputRef = useRef(null); const comments = list.data?.pages.flatMap((p) => p.comments ?? []) ?? []; - const submit = () => { - if (!loggedIn) return open({ type: 'login', then: { type: 'comments', postId, draft: text } }); + useEffect(() => { + if (!notice) return; + const t = setTimeout(() => setNotice(''), 3000); + return () => clearTimeout(t); + }, [notice]); + + const send = () => { const body = text.trim(); if (!body || add.isPending) return; setAddFailed(false); @@ -161,6 +258,7 @@ export function CommentsSheet({ postId, draft }: { postId: number; draft?: strin { path: { post_id: postId }, body: { body } }, { onSuccess: (res) => { + if (res.result?.desc === 'TERMS_REQUIRED') return setAskTerms(true); setAddFailed(!res.result?.success); if (!res.result?.success) return; setText(''); @@ -172,6 +270,28 @@ export function CommentsSheet({ postId, draft }: { postId: number; draft?: strin ); }; + // 약관에 동의해야 댓글을 쓸 수 있다. 동의하면 쓰던 댓글을 바로 올린다 + const submit = () => { + if (!loggedIn) return open({ type: 'login', then: { type: 'comments', postId, draft: text } }); + if (me && !me.terms_agreed) return setAskTerms(true); + send(); + }; + const agreeAndSend = () => { + setAddFailed(false); + agree.mutate( + {}, + { + onSuccess: (res) => { + if (!res.result?.success) return setAddFailed(true); + queryClient.setQueryData(meQueryKey(), res); + setAskTerms(false); + send(); + }, + onError: () => setAddFailed(true), + }, + ); + }; + return ( <> @@ -179,7 +299,7 @@ export function CommentsSheet({ postId, draft }: { postId: number; draft?: strin <> {/* 다시 받은 좋아요 상태(로그인 바뀜 등)가 행에 반영되도록 key 에 넣는다 */} {comments.map((c) => ( - + ))} {list.hasNextPage && ( list.fetchNextPage()} disabled={list.isFetchingNextPage} className="my-2 disabled:opacity-50"> @@ -193,22 +313,36 @@ export function CommentsSheet({ postId, draft }: { postId: number; draft?: strin list.refetch()} empty="아직 댓글이 없어요. 첫 댓글을 남겨 보세요." hold={} boxClassName="inset-0" /> )} - - {EMOJIS.map((e) => ( - { - setText((t) => (t + e).slice(0, 60)); - inputRef.current?.focus(); - }} - > - {e} - - ))} - - + {askTerms ? ( + + 댓글을 쓰려면 이용약관에 동의해 주세요. 욕설·광고·개인정보 노출은 숨겨지고, 계속되면 이용이 제한돼요. + + void Linking.openURL(`${SITE_URL}/terms.html`)} accessibilityRole="link" className="flex-1 rounded-[12px] bg-card p-2.5"> + 이용약관 보기 + + + 동의하고 쓰기 + + + + ) : ( + + {EMOJIS.map((e) => ( + { + setText((t) => (t + e).slice(0, 60)); + inputRef.current?.focus(); + }} + > + {e} + + ))} + + )} + {addFailed ? : {notice}} diff --git a/mobile/src/components/sheets/google.tsx b/mobile/src/components/sheets/google.tsx new file mode 100644 index 0000000..7455949 --- /dev/null +++ b/mobile/src/components/sheets/google.tsx @@ -0,0 +1,52 @@ +import { authConfigOptions, googleLoginMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'; +import type { ResAuth } from '@nalssigak/shared/api/client/types.gen'; +import { GoogleSignin, isErrorWithCode, isSuccessResponse, statusCodes } from '@react-native-google-signin/google-signin'; +import { useMutation, useQuery } from '@tanstack/react-query'; +import { useState } from 'react'; +import { Platform, Pressable, View } from 'react-native'; +import { Text } from '@/components/text'; + +/** 구글로 계속하기. 서버에 클라이언트 ID가 없거나 안드로이드가 아니면 그리지 않는다 */ +export function GoogleButton({ onResult, onFail }: { onResult: (res: ResAuth) => void; onFail: () => void }) { + const clientId = useQuery({ ...authConfigOptions(), staleTime: Infinity, enabled: Platform.OS === 'android' }).data?.google_client_id; + const login = useMutation(googleLoginMutation()); + const [busy, setBusy] = useState(false); + const [broken, setBroken] = useState(false); + + const press = async () => { + if (!clientId) return; + setBroken(false); + setBusy(true); + try { + GoogleSignin.configure({ webClientId: clientId }); + await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true }); + const res = await GoogleSignin.signIn(); + if (!isSuccessResponse(res)) return; + const token = res.data.idToken; + if (!token) return onFail(); + login.mutate({ body: { credential: token } }, { onSuccess: onResult, onError: onFail }); + } catch (e) { + if (isErrorWithCode(e) && e.code === statusCodes.IN_PROGRESS) return; + console.error('[google] sign in', e); + setBroken(true); + } finally { + setBusy(false); + } + }; + + if (Platform.OS !== 'android' || !clientId) return null; + const pending = busy || login.isPending; + return ( + + + {pending ? '구글로 로그인 중…' : '구글로 계속하기'} + + {broken && 구글 로그인을 하지 못했어요. 아이디로 로그인해 주세요.} + + + 또는 아이디로 + + + + ); +} diff --git a/mobile/src/components/sheets/login.tsx b/mobile/src/components/sheets/login.tsx index 9d0ff85..f756a99 100644 --- a/mobile/src/components/sheets/login.tsx +++ b/mobile/src/components/sheets/login.tsx @@ -3,10 +3,12 @@ import { loginMutation, signupMutation } from '@nalssigak/shared/api/client/@tan import type { ResAuth } from '@nalssigak/shared/api/client/types.gen'; import { useMutation } from '@tanstack/react-query'; import { useState } from 'react'; -import { Pressable, Text, View } from 'react-native'; +import { Pressable, View } from 'react-native'; +import { Text } from '@/components/text'; import { useAuth } from '@/lib/auth'; +import { GoogleButton } from './google'; import { MeSheet } from './me'; import { Body, ErrorLine, Field, useSoft } from './parts'; @@ -60,6 +62,7 @@ export function LoginSheet({ onDone, onLoggedIn }: { onDone: () => void; onLogge return ( 좋아요·댓글은 로그인한 뒤에 할 수 있어요. + {MODES.map(([m, l]) => ( setMode(m)} className={`flex-1 rounded-full py-2 ${mode === m ? 'bg-ink-btn' : ''}`}> diff --git a/mobile/src/components/sheets/me.tsx b/mobile/src/components/sheets/me.tsx index 87a0540..1755504 100644 --- a/mobile/src/components/sheets/me.tsx +++ b/mobile/src/components/sheets/me.tsx @@ -1,13 +1,15 @@ import { clearTokens } from '@nalssigak/shared/api/auth'; -import { meQueryKey, updateMeMutation, withdrawMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'; +import { listBlockedOptions, listBlockedQueryKey, meQueryKey, unblockMutation, updateMeMutation, withdrawMutation } from '@nalssigak/shared/api/client/@tanstack/react-query.gen'; import { AVATAR_COLORS, CHARACTERS, MOODS } from '@nalssigak/shared/lib'; -import { useMutation, useQueryClient } from '@tanstack/react-query'; +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { useState } from 'react'; -import { Pressable, Text, View } from 'react-native'; +import { Pressable, View } from 'react-native'; +import { Text } from '@/components/text'; import { Avatar, Ic } from '@/components/ui'; import { useAuth } from '@/lib/auth'; +import { isCommentList } from './comments'; import { Body, Field, useSoft } from './parts'; /** 탈퇴: 한 번 더 묻고 지운다. 계정이 없어지니 이 기기 토큰도 지운다 */ @@ -51,7 +53,49 @@ function Withdraw({ onDone }: { onDone: () => void }) { ); } -/** 내 정보: 캐릭터·배경색·기분·닉네임·로그아웃·탈퇴 */ +/** 차단한 사람: 있을 때만 보이고, 풀면 그 사람 댓글이 다시 보인다 */ +function Blocked() { + const s = useSoft(); + const queryClient = useQueryClient(); + const list = useQuery(listBlockedOptions()); + const unblock = useMutation(unblockMutation()); + const [failed, setFailed] = useState(false); + const users = list.data?.users ?? []; + if (!users.length) return null; + const release = (user_id: string) => { + setFailed(false); + unblock.mutate( + { path: { user_id } }, + { + onSuccess: (res) => { + if (!res.result?.success) return setFailed(true); + queryClient.invalidateQueries({ queryKey: listBlockedQueryKey() }); + queryClient.invalidateQueries({ predicate: isCommentList }); + }, + onError: () => setFailed(true), + }, + ); + }; + return ( + + 차단한 사람 + + {users.map((u) => ( + + + {u.nickname} + release(u.user_id)} disabled={unblock.isPending} className="rounded-[12px] px-3 py-2 disabled:opacity-50" style={{ backgroundColor: s.soft }}> + 풀기 + + + ))} + + {failed && 잠시 뒤에 다시 해 주세요.} + + ); +} + +/** 내 정보: 캐릭터·배경색·기분·닉네임·로그아웃·차단한 사람·탈퇴 */ export function MeSheet({ onDone }: { onDone: () => void }) { const { me, logout } = useAuth(); const s = useSoft(); @@ -165,6 +209,7 @@ export function MeSheet({ onDone }: { onDone: () => void }) { > 로그아웃 + ); diff --git a/package-lock.json b/package-lock.json index ec66e20..4b14e4a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -43,6 +43,7 @@ "@expo-google-fonts/jua": "^0.4.1", "@expo/ui": "~57.0.23", "@nalssigak/shared": "*", + "@react-native-google-signin/google-signin": "^16.1.5", "@tanstack/react-query": "^5.104.2", "expo": "~57.0.28", "expo-constants": "~57.0.21", @@ -3257,6 +3258,25 @@ } } }, + "node_modules/@react-native-google-signin/google-signin": { + "version": "16.1.5", + "resolved": "https://registry.npmjs.org/@react-native-google-signin/google-signin/-/google-signin-16.1.5.tgz", + "integrity": "sha512-9rmMwACzHK9Cbd0Yp7efg5uWgiYoLwmNAJh4gRCuMcSQH+qplpK7E4d1Q4tbsD8M9jvvVtRX2Z0AP9wwBKmPrQ==", + "license": "MIT", + "funding": { + "url": "https://universal-sign-in.com" + }, + "peerDependencies": { + "expo": ">=52.0.40", + "react": "*", + "react-native": "*" + }, + "peerDependenciesMeta": { + "expo": { + "optional": true + } + } + }, "node_modules/@react-native-masked-view/masked-view": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/@react-native-masked-view/masked-view/-/masked-view-0.3.2.tgz", diff --git a/shared/api/client/@tanstack/react-query.gen.ts b/shared/api/client/@tanstack/react-query.gen.ts index d803792..fae5945 100644 --- a/shared/api/client/@tanstack/react-query.gen.ts +++ b/shared/api/client/@tanstack/react-query.gen.ts @@ -3,8 +3,8 @@ import { type DefaultError, type InfiniteData, infiniteQueryOptions, queryOptions, type UseMutationOptions } from '@tanstack/react-query'; import { client } from '../client.gen'; -import { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe, withdraw } from '../sdk.gen'; -import type { AddCommentData, AddCommentError, AddCommentResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetTodayPageData, GetTodayPageError, GetTodayPageResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse, WithdrawData, WithdrawError, WithdrawResponse } from '../types.gen'; +import { addComment, agreeTerms, authConfig, blockAuthor, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, listArticles, listBlocked, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, reportComment, savePost, signup, unblock, unlikeComment, unlikePost, unsavePost, updateMe, withdraw } from '../sdk.gen'; +import type { AddCommentData, AddCommentError, AddCommentResponse, AgreeTermsData, AgreeTermsError, AgreeTermsResponse, AuthConfigData, AuthConfigResponse, BlockAuthorData, BlockAuthorError, BlockAuthorResponse, DeleteCommentData, DeleteCommentError, DeleteCommentResponse, GetArticleData, GetArticleError, GetArticleResponse, GetFeedData, GetFeedError, GetFeedResponse, GetImageData, GetImageError, GetIndexData, GetIndexError, GetIndexResponse, GetPostData, GetPostError, GetPostResponse, GetSeasonWeekData, GetSeasonWeekResponse, GetSkyData, GetSkyError, GetSkyRankingData, GetSkyRankingResponse, GetSkyResponse, GetTodayPageData, GetTodayPageError, GetTodayPageResponse, GetWatchSummaryData, GetWatchSummaryError, GetWatchSummaryResponse, GetWeatherNowData, GetWeatherNowError, GetWeatherNowResponse, GetWeatherTodayData, GetWeatherTodayError, GetWeatherTodayResponse, GetWeekData, GetWeekError, GetWeekRankingData, GetWeekRankingResponse, GetWeekResponse, GoogleLoginData, GoogleLoginError, GoogleLoginResponse, HealthzHealthzGetData, HealthzHealthzGetResponse, LikeCommentData, LikeCommentError, LikeCommentResponse, LikePostData, LikePostError, LikePostResponse, ListArticlesData, ListArticlesError, ListArticlesResponse, ListBlockedData, ListBlockedError, ListBlockedResponse, ListCommentsData, ListCommentsError, ListCommentsResponse, ListEventsData, ListEventsError, ListEventsResponse, ListIndicesData, ListIndicesError, ListIndicesResponse, ListPlacesData, ListPlacesError, ListPlacesResponse, ListRegionsData, ListRegionsError, ListRegionsResponse, ListSavedData, ListSavedError, ListSavedResponse, LoginData, LoginError, LoginResponse, LogoutData, LogoutError, LogoutResponse, MeData, MeError, MeResponse, NearestRegionData, NearestRegionError, NearestRegionResponse, RefreshData, RefreshError, RefreshResponse, ReportCommentData, ReportCommentError, ReportCommentResponse, SavePostData, SavePostError, SavePostResponse, SignupData, SignupError, SignupResponse, UnblockData, UnblockError, UnblockResponse, UnlikeCommentData, UnlikeCommentError, UnlikeCommentResponse, UnlikePostData, UnlikePostError, UnlikePostResponse, UnsavePostData, UnsavePostError, UnsavePostResponse, UpdateMeData, UpdateMeError, UpdateMeResponse, WithdrawData, WithdrawError, WithdrawResponse } from '../types.gen'; export type QueryKey = [ Pick & { @@ -379,6 +379,41 @@ export const loginMutation = (options?: Partial>): UseMutatio return mutationOptions; }; +/** + * 구글 로그인 (처음이면 자동 닉네임으로 가입) + */ +export const googleLoginMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await googleLogin({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const authConfigQueryKey = (options?: Options) => createQueryKey('authConfig', options); + +/** + * 로그인 화면 설정 (구글 클라이언트 ID) + */ +export const authConfigOptions = (options?: Options) => queryOptions>({ + queryFn: async ({ queryKey, signal }) => { + const { data } = await authConfig({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }, + queryKey: authConfigQueryKey(options) +}); + /** * 토큰 재발급 */ @@ -465,6 +500,23 @@ export const updateMeMutation = (options?: Partial>): UseM return mutationOptions; }; +/** + * 이용약관 동의 (댓글 쓰기 전에 한 번) + */ +export const agreeTermsMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await agreeTerms({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + /** * 좋아요 취소 */ @@ -659,7 +711,7 @@ export const listCommentsInfiniteOptions = (options: Options) }; /** - * 댓글 쓰기 (60자) + * 댓글 쓰기 (60자, 이용약관 동의 전이면 TERMS_REQUIRED) */ export const addCommentMutation = (options?: Partial>): UseMutationOptions> => { const mutationOptions: UseMutationOptions> = { @@ -726,6 +778,75 @@ export const likeCommentMutation = (options?: Partial>) return mutationOptions; }; +/** + * 남의 댓글 신고 (신고한 사람에겐 바로 안 보이고, 3건이면 모두에게 숨김) + */ +export const reportCommentMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await reportComment({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +/** + * 이 댓글 쓴 사람 차단 (그 사람 댓글이 내게 안 보임) + */ +export const blockAuthorMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await blockAuthor({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + +export const listBlockedQueryKey = (options?: Options) => createQueryKey('listBlocked', options); + +/** + * 내가 차단한 사람 + */ +export const listBlockedOptions = (options?: Options) => queryOptions>({ + queryFn: async ({ queryKey, signal }) => { + const { data } = await listBlocked({ + ...options, + ...queryKey[0], + signal, + throwOnError: true + }); + return data; + }, + queryKey: listBlockedQueryKey(options) +}); + +/** + * 차단 풀기 + */ +export const unblockMutation = (options?: Partial>): UseMutationOptions> => { + const mutationOptions: UseMutationOptions> = { + mutationFn: async (fnOptions) => { + const { data } = await unblock({ + ...options, + ...fnOptions, + throwOnError: true + }); + return data; + } + }; + return mutationOptions; +}; + export const getWatchSummaryQueryKey = (options: Options) => createQueryKey('getWatchSummary', options); /** diff --git a/shared/api/client/index.ts b/shared/api/client/index.ts index cc4474d..edc543e 100644 --- a/shared/api/client/index.ts +++ b/shared/api/client/index.ts @@ -1,4 +1,4 @@ // This file is auto-generated by @hey-api/openapi-ts -export { addComment, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, healthzHealthzGet, likeComment, likePost, listArticles, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, savePost, signup, unlikeComment, unlikePost, unsavePost, updateMe, withdraw } from './sdk.gen'; -export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReqComment, type ReqLogin, type ReqRefresh, type ReqSignup, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type ResWithdraw, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, type SlotPoint, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostError, type UnlikePostErrors, type UnlikePostResponse, type UnlikePostResponses, type UnsavePostData, type UnsavePostError, type UnsavePostErrors, type UnsavePostResponse, type UnsavePostResponses, type UpdateMeData, type UpdateMeError, type UpdateMeErrors, type UpdateMeResponse, type UpdateMeResponses, type ValidationError, type WarningData, WarningLevel, WarningType, type WatchEvent, type WatchNow, type WatchSlot, type WatchSunset, type WatchTimeline, type WeatherSlot, type WeekDay, type WeekGak, type WeekRankDay, type WeekRankItem, type WeekSlide, type WithdrawData, type WithdrawError, type WithdrawErrors, type WithdrawResponse, type WithdrawResponses } from './types.gen'; +export { addComment, agreeTerms, authConfig, blockAuthor, deleteComment, getArticle, getFeed, getImage, getIndex, getPost, getSeasonWeek, getSky, getSkyRanking, getTodayPage, getWatchSummary, getWeatherNow, getWeatherToday, getWeek, getWeekRanking, googleLogin, healthzHealthzGet, likeComment, likePost, listArticles, listBlocked, listComments, listEvents, listIndices, listPlaces, listRegions, listSaved, login, logout, me, nearestRegion, type Options, refresh, reportComment, savePost, signup, unblock, unlikeComment, unlikePost, unsavePost, updateMe, withdraw } from './sdk.gen'; +export { type AddCommentData, type AddCommentError, type AddCommentErrors, type AddCommentResponse, type AddCommentResponses, type AgreeTermsData, type AgreeTermsError, type AgreeTermsErrors, type AgreeTermsResponse, type AgreeTermsResponses, type AirData, AirGrade, ArticleCategory, type ArticleSummary, type AuthConfigData, type AuthConfigResponse, type AuthConfigResponses, AuthProvider, type BandArticle, type BandEvent, type Bands, type BestTime, type BlockAuthorData, type BlockAuthorError, type BlockAuthorErrors, type BlockAuthorResponse, type BlockAuthorResponses, type BlockedUser, type ClientOptions, type CommentData, type CommuteData, Confidence, type Cut, type DayData, type DeleteCommentData, type DeleteCommentError, type DeleteCommentErrors, type DeleteCommentResponse, type DeleteCommentResponses, type ErrorInfo, type EventData, type Factor, type GakSlide, type GetArticleData, type GetArticleError, type GetArticleErrors, type GetArticleResponse, type GetArticleResponses, type GetFeedData, type GetFeedError, type GetFeedErrors, type GetFeedResponse, type GetFeedResponses, type GetImageData, type GetImageError, type GetImageErrors, type GetImageResponses, type GetIndexData, type GetIndexError, type GetIndexErrors, type GetIndexResponse, type GetIndexResponses, type GetPostData, type GetPostError, type GetPostErrors, type GetPostResponse, type GetPostResponses, type GetSeasonWeekData, type GetSeasonWeekResponse, type GetSeasonWeekResponses, type GetSkyData, type GetSkyError, type GetSkyErrors, type GetSkyRankingData, type GetSkyRankingResponse, type GetSkyRankingResponses, type GetSkyResponse, type GetSkyResponses, type GetTodayPageData, type GetTodayPageError, type GetTodayPageErrors, type GetTodayPageResponse, type GetTodayPageResponses, type GetWatchSummaryData, type GetWatchSummaryError, type GetWatchSummaryErrors, type GetWatchSummaryResponse, type GetWatchSummaryResponses, type GetWeatherNowData, type GetWeatherNowError, type GetWeatherNowErrors, type GetWeatherNowResponse, type GetWeatherNowResponses, type GetWeatherTodayData, type GetWeatherTodayError, type GetWeatherTodayErrors, type GetWeatherTodayResponse, type GetWeatherTodayResponses, type GetWeekData, type GetWeekError, type GetWeekErrors, type GetWeekRankingData, type GetWeekRankingResponse, type GetWeekRankingResponses, type GetWeekResponse, type GetWeekResponses, type GoogleLoginData, type GoogleLoginError, type GoogleLoginErrors, type GoogleLoginResponse, type GoogleLoginResponses, type HealthzHealthzGetData, type HealthzHealthzGetResponse, type HealthzHealthzGetResponses, type Hero, type HeroStat, type HourCell, type HoursSlide, type HttpValidationError, IndexCategory, type IndexSummary, type LikeCommentData, type LikeCommentError, type LikeCommentErrors, type LikeCommentResponse, type LikeCommentResponses, type LikePostData, type LikePostError, type LikePostErrors, type LikePostResponse, type LikePostResponses, type ListArticlesData, type ListArticlesError, type ListArticlesErrors, type ListArticlesResponse, type ListArticlesResponses, type ListBlockedData, type ListBlockedError, type ListBlockedErrors, type ListBlockedResponse, type ListBlockedResponses, type ListCommentsData, type ListCommentsError, type ListCommentsErrors, type ListCommentsResponse, type ListCommentsResponses, type ListEventsData, type ListEventsError, type ListEventsErrors, type ListEventsResponse, type ListEventsResponses, type ListIndicesData, type ListIndicesError, type ListIndicesErrors, type ListIndicesResponse, type ListIndicesResponses, type ListPlacesData, type ListPlacesError, type ListPlacesErrors, type ListPlacesResponse, type ListPlacesResponses, type ListRegionsData, type ListRegionsError, type ListRegionsErrors, type ListRegionsResponse, type ListRegionsResponses, type ListSavedData, type ListSavedError, type ListSavedErrors, type ListSavedResponse, type ListSavedResponses, type LoginData, type LoginError, type LoginErrors, type LoginResponse, type LoginResponses, type LogoutData, type LogoutError, type LogoutErrors, type LogoutResponse, type LogoutResponses, type Me, type MeData, type MeError, type MeErrors, type MeResponse, type MeResponses, type NearestRegionData, type NearestRegionError, type NearestRegionErrors, type NearestRegionResponse, type NearestRegionResponses, type PlaceData, type PlanSlide, type PlanSpot, type PlanStep, type PostData, PostType, type Rain2h, type RainHourData, RainType, type RankData, type RefreshData, type RefreshError, type RefreshErrors, type RefreshResponse, type RefreshResponses, type RegionData, type ReportCommentData, type ReportCommentError, type ReportCommentErrors, type ReportCommentResponse, type ReportCommentResponses, ReportReason, type ReqComment, type ReqGoogle, type ReqLogin, type ReqRefresh, type ReqReport, type ReqSignup, type ReqUpdateMe, type ResArticle, type ResArticleList, type ResAuth, type ResAuthConfig, type ResBlockedList, type ResComment, type ResCommentLike, type ResCommentList, type ResEventList, type ResFeed, type ResHealth, type ResIndexDetail, type ResIndexList, type ResLogout, type ResMe, type ResPlaceList, type ResPost, type ResPostLike, type ResPostSave, type ResRegion, type ResRegionList, type ResSavedList, type ResSeasonWeek, type ResSky, type ResSkyRanking, type ResWatchSummary, type ResWeatherNow, type ResWeatherToday, type ResWebPacketProtocol, type ResWeek, type ResWeekRanking, type ResWithdraw, type Row, type RowsSlide, type SavedPost, type SavePostData, type SavePostError, type SavePostErrors, type SavePostResponse, type SavePostResponses, type ScoreBand, type SignupData, type SignupError, type SignupErrors, type SignupResponse, type SignupResponses, Sky, SkyGrade, type SkyPlanData, type SkyScoreData, SkySituation, SkyType, type SlotPoint, SlotTone, type SpotData, type SunsetSlide, type TermData, type Tomorrow, type TopIndex, type TrendPoint, type UnblockData, type UnblockError, type UnblockErrors, type UnblockResponse, type UnblockResponses, type UnlikeCommentData, type UnlikeCommentError, type UnlikeCommentErrors, type UnlikeCommentResponse, type UnlikeCommentResponses, type UnlikePostData, type UnlikePostError, type UnlikePostErrors, type UnlikePostResponse, type UnlikePostResponses, type UnsavePostData, type UnsavePostError, type UnsavePostErrors, type UnsavePostResponse, type UnsavePostResponses, type UpdateMeData, type UpdateMeError, type UpdateMeErrors, type UpdateMeResponse, type UpdateMeResponses, type ValidationError, type WarningData, WarningLevel, WarningType, type WatchEvent, type WatchNow, type WatchSlot, type WatchSunset, type WatchTimeline, type WeatherSlot, type WeekDay, type WeekGak, type WeekRankDay, type WeekRankItem, type WeekSlide, type WithdrawData, type WithdrawError, type WithdrawErrors, type WithdrawResponse, type WithdrawResponses } from './types.gen'; diff --git a/shared/api/client/sdk.gen.ts b/shared/api/client/sdk.gen.ts index 1660115..0f6915b 100644 --- a/shared/api/client/sdk.gen.ts +++ b/shared/api/client/sdk.gen.ts @@ -2,7 +2,7 @@ import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client'; import { client } from './client.gen'; -import type { AddCommentData, AddCommentErrors, AddCommentResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, WithdrawData, WithdrawErrors, WithdrawResponses } from './types.gen'; +import type { AddCommentData, AddCommentErrors, AddCommentResponses, AgreeTermsData, AgreeTermsErrors, AgreeTermsResponses, AuthConfigData, AuthConfigResponses, BlockAuthorData, BlockAuthorErrors, BlockAuthorResponses, DeleteCommentData, DeleteCommentErrors, DeleteCommentResponses, GetArticleData, GetArticleErrors, GetArticleResponses, GetFeedData, GetFeedErrors, GetFeedResponses, GetImageData, GetImageErrors, GetImageResponses, GetIndexData, GetIndexErrors, GetIndexResponses, GetPostData, GetPostErrors, GetPostResponses, GetSeasonWeekData, GetSeasonWeekResponses, GetSkyData, GetSkyErrors, GetSkyRankingData, GetSkyRankingResponses, GetSkyResponses, GetTodayPageData, GetTodayPageErrors, GetTodayPageResponses, GetWatchSummaryData, GetWatchSummaryErrors, GetWatchSummaryResponses, GetWeatherNowData, GetWeatherNowErrors, GetWeatherNowResponses, GetWeatherTodayData, GetWeatherTodayErrors, GetWeatherTodayResponses, GetWeekData, GetWeekErrors, GetWeekRankingData, GetWeekRankingResponses, GetWeekResponses, GoogleLoginData, GoogleLoginErrors, GoogleLoginResponses, HealthzHealthzGetData, HealthzHealthzGetResponses, LikeCommentData, LikeCommentErrors, LikeCommentResponses, LikePostData, LikePostErrors, LikePostResponses, ListArticlesData, ListArticlesErrors, ListArticlesResponses, ListBlockedData, ListBlockedErrors, ListBlockedResponses, ListCommentsData, ListCommentsErrors, ListCommentsResponses, ListEventsData, ListEventsErrors, ListEventsResponses, ListIndicesData, ListIndicesErrors, ListIndicesResponses, ListPlacesData, ListPlacesErrors, ListPlacesResponses, ListRegionsData, ListRegionsErrors, ListRegionsResponses, ListSavedData, ListSavedErrors, ListSavedResponses, LoginData, LoginErrors, LoginResponses, LogoutData, LogoutErrors, LogoutResponses, MeData, MeErrors, MeResponses, NearestRegionData, NearestRegionErrors, NearestRegionResponses, RefreshData, RefreshErrors, RefreshResponses, ReportCommentData, ReportCommentErrors, ReportCommentResponses, SavePostData, SavePostErrors, SavePostResponses, SignupData, SignupErrors, SignupResponses, UnblockData, UnblockErrors, UnblockResponses, UnlikeCommentData, UnlikeCommentErrors, UnlikeCommentResponses, UnlikePostData, UnlikePostErrors, UnlikePostResponses, UnsavePostData, UnsavePostErrors, UnsavePostResponses, UpdateMeData, UpdateMeErrors, UpdateMeResponses, WithdrawData, WithdrawErrors, WithdrawResponses } from './types.gen'; export type Options = Options2 & { /** @@ -127,6 +127,23 @@ export const login = (options: Options(options: Options): RequestResult => (options.client ?? client).post({ + url: '/v1/auth/google', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +/** + * 로그인 화면 설정 (구글 클라이언트 ID) + */ +export const authConfig = (options?: Options): RequestResult => (options?.client ?? client).get({ url: '/v1/auth/config', ...options }); + /** * 토큰 재발급 */ @@ -166,6 +183,11 @@ export const updateMe = (options: Options(options?: Options): RequestResult => (options?.client ?? client).post({ url: '/v1/auth/terms', ...options }); + /** * 좋아요 취소 */ @@ -197,7 +219,7 @@ export const listSaved = (options?: Options export const listComments = (options: Options): RequestResult => (options.client ?? client).get({ url: '/v1/reaction/post/{post_id}/comment/list', ...options }); /** - * 댓글 쓰기 (60자) + * 댓글 쓰기 (60자, 이용약관 동의 전이면 TERMS_REQUIRED) */ export const addComment = (options: Options): RequestResult => (options.client ?? client).post({ url: '/v1/reaction/post/{post_id}/comment', @@ -223,6 +245,33 @@ export const unlikeComment = (options: Opti */ export const likeComment = (options: Options): RequestResult => (options.client ?? client).post({ url: '/v1/reaction/comment/{comment_id}/like', ...options }); +/** + * 남의 댓글 신고 (신고한 사람에겐 바로 안 보이고, 3건이면 모두에게 숨김) + */ +export const reportComment = (options: Options): RequestResult => (options.client ?? client).post({ + url: '/v1/reaction/comment/{comment_id}/report', + ...options, + headers: { + 'Content-Type': 'application/json', + ...options.headers + } +}); + +/** + * 이 댓글 쓴 사람 차단 (그 사람 댓글이 내게 안 보임) + */ +export const blockAuthor = (options: Options): RequestResult => (options.client ?? client).post({ url: '/v1/reaction/comment/{comment_id}/block', ...options }); + +/** + * 내가 차단한 사람 + */ +export const listBlocked = (options?: Options): RequestResult => (options?.client ?? client).get({ url: '/v1/reaction/block/list', ...options }); + +/** + * 차단 풀기 + */ +export const unblock = (options: Options): RequestResult => (options.client ?? client).delete({ url: '/v1/reaction/block/{user_id}', ...options }); + /** * 워치 한 번에: 지금 날씨, 각 1~7위·내 각, 노을, 남은 3시간 칸, 컴플리케이션 시간표 */ diff --git a/shared/api/client/types.gen.ts b/shared/api/client/types.gen.ts index 914589d..23d7c37 100644 --- a/shared/api/client/types.gen.ts +++ b/shared/api/client/types.gen.ts @@ -238,6 +238,28 @@ export type BestTime = { end?: string | null; }; +/** + * BlockedUser + */ +export type BlockedUser = { + /** + * User Id + */ + user_id: string; + /** + * Nickname + */ + nickname: string; + /** + * Character + */ + character: string; + /** + * Color + */ + color: string; +}; + /** * CommentData */ @@ -828,6 +850,10 @@ export type Me = { */ mood?: string | null; provider: AuthProvider; + /** + * Terms Agreed + */ + terms_agreed?: boolean; }; /** @@ -1195,6 +1221,33 @@ export type RegionData = { lon: number; }; +/** + * ReportReason + */ +export const ReportReason = { + /** + * ABUSE + */ + ABUSE: 1, + /** + * AD + */ + AD: 2, + /** + * PRIVACY + */ + PRIVACY: 3, + /** + * OTHER + */ + OTHER: 4 +} as const; + +/** + * ReportReason + */ +export type ReportReason = typeof ReportReason[keyof typeof ReportReason]; + /** * Req_Comment */ @@ -1205,6 +1258,18 @@ export type ReqComment = { body: string; }; +/** + * Req_Google + */ +export type ReqGoogle = { + /** + * Credential + * + * 구글 로그인 버튼이 준 ID 토큰 + */ + credential: string; +}; + /** * Req_Login */ @@ -1229,6 +1294,13 @@ export type ReqRefresh = { refresh_token: string; }; +/** + * Req_Report + */ +export type ReqReport = { + reason: ReportReason; +}; + /** * Req_Signup */ @@ -1320,6 +1392,38 @@ export type ResAuth = { me?: Me | null; }; +/** + * Res_AuthConfig + */ +export type ResAuthConfig = { + result?: ErrorInfo; + /** + * Msg + */ + msg?: string | null; + /** + * Google Client Id + * + * 구글 로그인 버튼에 쓸 OAuth 클라이언트 ID. 없으면 구글 로그인을 숨긴다 + */ + google_client_id?: string | null; +}; + +/** + * Res_BlockedList + */ +export type ResBlockedList = { + result?: ErrorInfo; + /** + * Msg + */ + msg?: string | null; + /** + * Users + */ + users?: Array; +}; + /** * Res_Comment */ @@ -3487,6 +3591,47 @@ export type LoginResponses = { export type LoginResponse = LoginResponses[keyof LoginResponses]; +export type GoogleLoginData = { + body: ReqGoogle; + path?: never; + query?: never; + url: '/v1/auth/google'; +}; + +export type GoogleLoginErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type GoogleLoginError = GoogleLoginErrors[keyof GoogleLoginErrors]; + +export type GoogleLoginResponses = { + /** + * Successful Response + */ + 200: ResAuth; +}; + +export type GoogleLoginResponse = GoogleLoginResponses[keyof GoogleLoginResponses]; + +export type AuthConfigData = { + body?: never; + path?: never; + query?: never; + url: '/v1/auth/config'; +}; + +export type AuthConfigResponses = { + /** + * Successful Response + */ + 200: ResAuthConfig; +}; + +export type AuthConfigResponse = AuthConfigResponses[keyof AuthConfigResponses]; + export type RefreshData = { body: ReqRefresh; path?: never; @@ -3636,6 +3781,37 @@ export type UpdateMeResponses = { export type UpdateMeResponse = UpdateMeResponses[keyof UpdateMeResponses]; +export type AgreeTermsData = { + body?: never; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path?: never; + query?: never; + url: '/v1/auth/terms'; +}; + +export type AgreeTermsErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type AgreeTermsError = AgreeTermsErrors[keyof AgreeTermsErrors]; + +export type AgreeTermsResponses = { + /** + * Successful Response + */ + 200: ResMe; +}; + +export type AgreeTermsResponse = AgreeTermsResponses[keyof AgreeTermsResponses]; + export type UnlikePostData = { body?: never; headers?: { @@ -4001,6 +4177,145 @@ export type LikeCommentResponses = { export type LikeCommentResponse = LikeCommentResponses[keyof LikeCommentResponses]; +export type ReportCommentData = { + body: ReqReport; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path: { + /** + * Comment Id + */ + comment_id: number; + }; + query?: never; + url: '/v1/reaction/comment/{comment_id}/report'; +}; + +export type ReportCommentErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type ReportCommentError = ReportCommentErrors[keyof ReportCommentErrors]; + +export type ReportCommentResponses = { + /** + * Successful Response + */ + 200: ResWebPacketProtocol; +}; + +export type ReportCommentResponse = ReportCommentResponses[keyof ReportCommentResponses]; + +export type BlockAuthorData = { + body?: never; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path: { + /** + * Comment Id + */ + comment_id: number; + }; + query?: never; + url: '/v1/reaction/comment/{comment_id}/block'; +}; + +export type BlockAuthorErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type BlockAuthorError = BlockAuthorErrors[keyof BlockAuthorErrors]; + +export type BlockAuthorResponses = { + /** + * Successful Response + */ + 200: ResWebPacketProtocol; +}; + +export type BlockAuthorResponse = BlockAuthorResponses[keyof BlockAuthorResponses]; + +export type ListBlockedData = { + body?: never; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path?: never; + query?: never; + url: '/v1/reaction/block/list'; +}; + +export type ListBlockedErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type ListBlockedError = ListBlockedErrors[keyof ListBlockedErrors]; + +export type ListBlockedResponses = { + /** + * Successful Response + */ + 200: ResBlockedList; +}; + +export type ListBlockedResponse = ListBlockedResponses[keyof ListBlockedResponses]; + +export type UnblockData = { + body?: never; + headers?: { + /** + * Authorization + */ + authorization?: string | null; + }; + path: { + /** + * User Id + */ + user_id: string; + }; + query?: never; + url: '/v1/reaction/block/{user_id}'; +}; + +export type UnblockErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type UnblockError = UnblockErrors[keyof UnblockErrors]; + +export type UnblockResponses = { + /** + * Successful Response + */ + 200: ResWebPacketProtocol; +}; + +export type UnblockResponse = UnblockResponses[keyof UnblockResponses]; + export type GetWatchSummaryData = { body?: never; path?: never;