fix: 코드 재검토 반영 — 댓글 더 보기, 긴 비밀번호 500 방지, 토큰 갱신 실패 처리, 연타 막기

This commit is contained in:
minaChoi committed 2026-10-06 10:38:27 +09:00
1 parent ae6b06ac1f
commit be8f827556
7 files changed
+88 -30

No files matched your search

+5
View File
@@ -21,7 +21,12 @@ async def hash_password(password: str) -> str:
return (await asyncio.to_thread(bcrypt.hashpw, password.encode(), bcrypt.gensalt())).decode()
PASSWORD_MAX_BYTES = 72 # bcrypt 가 받는 최대 길이
async def verify_password(password: str, hashed: str) -> bool:
if len(password.encode()) > PASSWORD_MAX_BYTES:
return False
return await asyncio.to_thread(bcrypt.checkpw, password.encode(), hashed.encode())
+7 -3
View File
@@ -4,7 +4,7 @@ from typing import Optional
from fastapi import Depends
from common.auth import decode, hash_password, issue_tokens, verify_password
from common.auth import PASSWORD_MAX_BYTES, decode, hash_password, issue_tokens, verify_password
from common.database.db_session_manager import DB_SESSION_MNG
from common.database.model.models import User
from common.enums import ErrorType
@@ -24,7 +24,7 @@ class AuthService:
self.crud = crud
async def signup(self, login_id: str, password: str, nickname: str) -> tuple[ErrorType, Optional[User]]:
if not LOGIN_ID.match(login_id) or len(password) < PASSWORD_MIN or not NICKNAME.match(nickname):
if not LOGIN_ID.match(login_id) or len(password) < PASSWORD_MIN or len(password.encode()) > PASSWORD_MAX_BYTES or not NICKNAME.match(nickname):
return ErrorType.INVALID_INPUT, None
err, exists = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
if err is not ErrorType.SUCCESS:
@@ -33,7 +33,11 @@ class AuthService:
return ErrorType.AUTH_DUPLICATE_ID, None
hashed = await hash_password(password)
err, user = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.create(s, login_id, hashed, nickname))
return (err, user) if err is ErrorType.SUCCESS else (ErrorType.AUTH_DUPLICATE_ID, None)
if err is ErrorType.SUCCESS:
return err, user
# 같은 아이디가 동시에 가입된 경우만 중복으로, 나머지는 DB 오류 그대로
_, exists = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
return (ErrorType.AUTH_DUPLICATE_ID if exists is not None else err), None
async def login(self, login_id: str, password: str) -> tuple[ErrorType, Optional[User]]:
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
+11
View File
@@ -31,6 +31,17 @@ async def test_signup_login_refresh_me():
assert (await c.post("/v1/auth/refresh", json={"refresh_token": ok["access_token"]})).json()["result"]["desc"] == "AUTH_TOKEN_INVALID"
@pytest.mark.anyio
async def test_password_over_72_bytes_is_rejected_not_500():
long_pw = "비밀번호" * 7 # 84바이트
async with client() as c:
r = await c.post("/v1/auth/signup", json={"login_id": "mina_long", "password": long_pw, "nickname": "긴비번"})
assert r.status_code == 200 and r.json()["result"]["desc"] == "INVALID_INPUT"
await _signup(c, login_id="mina_02")
r = await c.post("/v1/auth/login", json={"login_id": "mina_02", "password": long_pw})
assert r.status_code == 200 and r.json()["result"]["desc"] == "AUTH_FAILED"
@pytest.mark.anyio
async def test_signup_rejects_bad_input():
async with client() as c:
+3 -1
View File
@@ -38,11 +38,13 @@ export function getAccessToken() {
return accessToken
}
/** 로그인·로그아웃처럼 로그인 여부가 바뀔 때만 알린다. 토큰 갱신은 알리지 않는다 */
export function setTokens(access: string | null, refreshToken?: string | null) {
const wasLoggedIn = !!accessToken
accessToken = access
writeStored(ACCESS_KEY, access)
if (refreshToken !== undefined) writeStored(REFRESH_KEY, refreshToken)
emit('change')
if (wasLoggedIn !== !!access) emit('change')
}
export function clearTokens() {
+37 -15
View File
@@ -3,38 +3,60 @@ import { clearTokens, emitAuthRequired, getAccessToken, getRefreshToken, setToke
export const API_BASE_URL: string = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9810'
// 401이 한꺼번에 와도 갱신은 한 번만
let refreshing: Promise<boolean> | null = null
type Refresh = 'ok' | 'rejected' | 'unreachable'
function refreshTokens(): Promise<boolean> {
refreshing ??= (async () => {
// 401이 한꺼번에 와도 갱신은 한 번만
let refreshing: Promise<Refresh> | null = null
/** 서버가 거절하면 'rejected', 네트워크 오류·5xx 면 'unreachable' (이때는 토큰을 지우지 않는다) */
function refreshTokens(): Promise<Refresh> {
refreshing ??= (async (): Promise<Refresh> => {
const token = getRefreshToken()
if (!token) return false
if (!token) return 'rejected'
const res = await fetch(`${API_BASE_URL}/v1/auth/refresh`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refresh_token: token }) })
if (res.status >= 500) return 'unreachable'
const body = res.ok ? await res.json() : null
if (!body?.result?.success || !body.access_token) return false
if (!body?.result?.success || !body.access_token) return 'rejected'
setTokens(body.access_token, body.refresh_token ?? token)
return true
return 'ok'
})()
.catch(() => false)
.catch((): Refresh => 'unreachable')
.finally(() => {
refreshing = null
})
return refreshing
}
/** 401이면 토큰을 한 번 갱신해 같은 요청을 다시 보내고, 안 되면 토큰을 지우고 로그인 창을 띄운다 */
const NO_REFRESH = ['/v1/auth/login', '/v1/auth/signup', '/v1/auth/refresh']
/** 같은 요청을 토큰만 바꿔(null 이면 빼고) 다시 보낼 수 있게 복사한다 */
function withToken(request: Request, token: string | null) {
const copy = request.clone()
if (token) copy.headers.set('Authorization', `Bearer ${token}`)
else copy.headers.delete('Authorization')
return copy
}
/**
* 401이면 토큰을 한 번 갱신해 같은 요청을 다시 보낸다.
* 갱신이 거절되면 토큰을 지우고, 로그인 없이 되는 요청은 그냥 다시 보내고, 로그인이 꼭 필요한 요청만 로그인 창을 띄운다.
*/
async function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
const request = input instanceof Request && !init ? input : new Request(input, init)
const retry = request.clone()
const response = await fetch(request)
if (response.status !== 401 || new URL(request.url).pathname.startsWith('/v1/auth/')) return response
if (request.headers.has('Authorization') && (await refreshTokens())) {
retry.headers.set('Authorization', `Bearer ${getAccessToken()}`)
const again = await fetch(retry)
if (again.status !== 401) return again
if (response.status !== 401 || NO_REFRESH.includes(new URL(request.url).pathname)) return response
if (request.headers.has('Authorization')) {
const result = await refreshTokens()
if (result === 'unreachable') return response
if (result === 'ok') {
const again = await fetch(withToken(retry, getAccessToken()))
if (again.status !== 401) return again
}
if (getAccessToken()) clearTokens()
const anonymous = await fetch(withToken(retry, null))
if (anonymous.status !== 401) return anonymous
}
if (getAccessToken()) clearTokens()
emitAuthRequired()
return response
}
+2 -1
View File
@@ -229,7 +229,7 @@ function FullCard({ post }: PostProps) {
// 화면을 먼저 바꾸고, 실패하면 되돌린다 (서버는 실패도 200 + result.success=false 로 준다)
const setLike = (on: boolean) => {
if (!loggedIn) return open({ type: 'login' })
if (on === liked) return
if (on === liked || like.isPending || unlike.isPending) return
if (on) setPop((p) => p + 1)
patch({ liked: on, like_count: likeCount + (on ? 1 : -1) })
;(on ? like : unlike).mutate(
@@ -246,6 +246,7 @@ function FullCard({ post }: PostProps) {
const toggleSave = () => {
if (!loggedIn) return open({ type: 'login' })
if (save.isPending || unsave.isPending) return
const on = !saved
patch({ saved: on })
;(on ? save : unsave).mutate(
+23 -10
View File
@@ -1,4 +1,4 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'
import { setTokens, subscribeAuth } from '../api/auth'
import {
@@ -9,8 +9,8 @@ import {
getIndexOptions,
getSeasonWeekOptions,
likeCommentMutation,
listCommentsQueryKey,
listCommentsOptions,
listCommentsInfiniteOptions,
listCommentsInfiniteQueryKey,
listRegionsOptions,
loginMutation,
meQueryKey,
@@ -426,6 +426,7 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
const toggle = () => {
if (!loggedIn) return open({ type: 'login' })
if (like.isPending || unlike.isPending) return
const next = !liked
setLiked(next)
setCount((n) => n + (next ? 1 : -1))
@@ -456,7 +457,7 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
onSuccess: (res) => {
setRemoveFailed(!res.result?.success)
if (!res.result?.success) return
queryClient.invalidateQueries({ queryKey: listCommentsQueryKey({ path: { post_id: postId } }) })
queryClient.invalidateQueries({ queryKey: listCommentsInfiniteQueryKey({ path: { post_id: postId } }) })
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) })
},
onError: () => setRemoveFailed(true),
@@ -496,12 +497,16 @@ function CommentsSheet({ postId }: { postId: number }) {
const { open } = useSheet()
const { loggedIn, me } = useAuth()
const queryClient = useQueryClient()
const list = useQuery(listCommentsOptions({ path: { post_id: postId } }))
const list = useInfiniteQuery({
...listCommentsInfiniteOptions({ path: { post_id: postId } }),
initialPageParam: { path: { post_id: postId } },
getNextPageParam: (last) => last.next_cursor ?? undefined,
})
const add = useMutation(addCommentMutation())
const [addFailed, setAddFailed] = useState(false)
const [text, setText] = useState('')
const inputRef = useRef<HTMLInputElement>(null)
const comments = list.data?.comments ?? []
const comments = list.data?.pages.flatMap((p) => p.comments ?? []) ?? []
const submit = (e: FormEvent) => {
e.preventDefault()
@@ -515,7 +520,7 @@ function CommentsSheet({ postId }: { postId: number }) {
setAddFailed(!res.result?.success)
if (!res.result?.success) return
setText('')
queryClient.invalidateQueries({ queryKey: listCommentsQueryKey({ path: { post_id: postId } }) })
queryClient.invalidateQueries({ queryKey: listCommentsInfiniteQueryKey({ path: { post_id: postId } }) })
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) })
},
onError: () => setAddFailed(true),
@@ -527,7 +532,15 @@ function CommentsSheet({ postId }: { postId: number }) {
<>
<Body>
{comments.length ? (
comments.map((c) => <CommentRow key={c.comment_id} c={c} postId={postId} />)
<>
{/* 다시 받은 좋아요 상태(로그인 바뀜 등)가 행에 반영되도록 key 에 넣는다 */}
{comments.map((c) => <CommentRow key={`${c.comment_id}:${c.liked}:${c.like_count}`} c={c} postId={postId} />)}
{list.hasNextPage && (
<button type="button" onClick={() => list.fetchNextPage()} disabled={list.isFetchingNextPage} className="my-2 w-full cursor-pointer text-center text-sm font-bold text-(--ink3) disabled:opacity-50">
{list.isFetchingNextPage ? '불러오는 중…' : '댓글 더 보기'}
</button>
)}
</>
) : list.isSuccess ? (
<p className="my-6 text-center font-semibold text-(--ink3)">
아직 댓글이 없어요.
@@ -571,7 +584,7 @@ function CommentsSheet({ postId }: { postId: number }) {
const AUTH_ERRORS: Record<string, string> = {
AUTH_FAILED: '아이디나 비밀번호가 맞지 않아요.',
AUTH_DUPLICATE_ID: '이미 쓰고 있는 아이디예요.',
INVALID_INPUT: '아이디는 영어 소문자·숫자·_ 4~20자, 비밀번호는 8자 이상, 닉네임은 2~12자로 써 주세요.',
INVALID_INPUT: '아이디는 영어 소문자·숫자·_ 4~20자, 비밀번호는 8~64자, 닉네임은 2~12자로 써 주세요.',
}
function LoginSheet({ onDone }: { onDone: () => void }) {
@@ -622,7 +635,7 @@ function LoginSheet({ onDone }: { onDone: () => void }) {
))}
</div>
<input value={loginId} onChange={(e) => setLoginId(e.target.value)} autoComplete="username" required minLength={4} maxLength={20} placeholder="아이디" aria-label="아이디" className={field} />
<input value={password} onChange={(e) => setPassword(e.target.value)} type="password" autoComplete={mode === 'login' ? 'current-password' : 'new-password'} required minLength={mode === 'signup' ? 8 : undefined} placeholder={mode === 'signup' ? '비밀번호 (8자 이상)' : '비밀번호'} aria-label="비밀번호" className={field} />
<input value={password} onChange={(e) => setPassword(e.target.value)} type="password" autoComplete={mode === 'login' ? 'current-password' : 'new-password'} required minLength={mode === 'signup' ? 8 : undefined} maxLength={64} placeholder={mode === 'signup' ? '비밀번호 (8자 이상)' : '비밀번호'} aria-label="비밀번호" className={field} />
{mode === 'signup' && <input value={nickname} onChange={(e) => setNickname(e.target.value)} required minLength={2} maxLength={12} placeholder="닉네임 (2~12자)" aria-label="닉네임" className={field} />}
<p className="min-h-5 text-center text-[13px] font-bold text-(--heart)" aria-live="polite">
{error}