fix: 코드 재검토 반영 — 댓글 더 보기, 긴 비밀번호 500 방지, 토큰 갱신 실패 처리, 연타 막기
This commit is contained in:
1 parent
ae6b06ac1f
commit
be8f827556
7 files changed
+88
-30
No files matched your search
@@ -21,7 +21,12 @@ async def hash_password(password: str) -> str:
|
|||||||
return (await asyncio.to_thread(bcrypt.hashpw, password.encode(), bcrypt.gensalt())).decode()
|
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:
|
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())
|
return await asyncio.to_thread(bcrypt.checkpw, password.encode(), hashed.encode())
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ from typing import Optional
|
|||||||
|
|
||||||
from fastapi import Depends
|
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.db_session_manager import DB_SESSION_MNG
|
||||||
from common.database.model.models import User
|
from common.database.model.models import User
|
||||||
from common.enums import ErrorType
|
from common.enums import ErrorType
|
||||||
@@ -24,7 +24,7 @@ class AuthService:
|
|||||||
self.crud = crud
|
self.crud = crud
|
||||||
|
|
||||||
async def signup(self, login_id: str, password: str, nickname: str) -> tuple[ErrorType, Optional[User]]:
|
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
|
return ErrorType.INVALID_INPUT, None
|
||||||
err, exists = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
|
err, exists = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
|
||||||
if err is not ErrorType.SUCCESS:
|
if err is not ErrorType.SUCCESS:
|
||||||
@@ -33,7 +33,11 @@ class AuthService:
|
|||||||
return ErrorType.AUTH_DUPLICATE_ID, None
|
return ErrorType.AUTH_DUPLICATE_ID, None
|
||||||
hashed = await hash_password(password)
|
hashed = await hash_password(password)
|
||||||
err, user = await DB_SESSION_MNG.execute_lambda_write(lambda s: self.crud.create(s, login_id, hashed, nickname))
|
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]]:
|
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))
|
err, user = await DB_SESSION_MNG.execute_lambda(lambda s: self.crud.by_login_id(s, login_id))
|
||||||
|
|||||||
@@ -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"
|
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
|
@pytest.mark.anyio
|
||||||
async def test_signup_rejects_bad_input():
|
async def test_signup_rejects_bad_input():
|
||||||
async with client() as c:
|
async with client() as c:
|
||||||
|
|||||||
@@ -38,11 +38,13 @@ export function getAccessToken() {
|
|||||||
return accessToken
|
return accessToken
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 로그인·로그아웃처럼 로그인 여부가 바뀔 때만 알린다. 토큰 갱신은 알리지 않는다 */
|
||||||
export function setTokens(access: string | null, refreshToken?: string | null) {
|
export function setTokens(access: string | null, refreshToken?: string | null) {
|
||||||
|
const wasLoggedIn = !!accessToken
|
||||||
accessToken = access
|
accessToken = access
|
||||||
writeStored(ACCESS_KEY, access)
|
writeStored(ACCESS_KEY, access)
|
||||||
if (refreshToken !== undefined) writeStored(REFRESH_KEY, refreshToken)
|
if (refreshToken !== undefined) writeStored(REFRESH_KEY, refreshToken)
|
||||||
emit('change')
|
if (wasLoggedIn !== !!access) emit('change')
|
||||||
}
|
}
|
||||||
|
|
||||||
export function clearTokens() {
|
export function clearTokens() {
|
||||||
|
|||||||
+37
-15
@@ -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'
|
export const API_BASE_URL: string = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:9810'
|
||||||
|
|
||||||
// 401이 한꺼번에 와도 갱신은 한 번만
|
type Refresh = 'ok' | 'rejected' | 'unreachable'
|
||||||
let refreshing: Promise<boolean> | null = null
|
|
||||||
|
|
||||||
function refreshTokens(): Promise<boolean> {
|
// 401이 한꺼번에 와도 갱신은 한 번만
|
||||||
refreshing ??= (async () => {
|
let refreshing: Promise<Refresh> | null = null
|
||||||
|
|
||||||
|
/** 서버가 거절하면 'rejected', 네트워크 오류·5xx 면 'unreachable' (이때는 토큰을 지우지 않는다) */
|
||||||
|
function refreshTokens(): Promise<Refresh> {
|
||||||
|
refreshing ??= (async (): Promise<Refresh> => {
|
||||||
const token = getRefreshToken()
|
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 }) })
|
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
|
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)
|
setTokens(body.access_token, body.refresh_token ?? token)
|
||||||
return true
|
return 'ok'
|
||||||
})()
|
})()
|
||||||
.catch(() => false)
|
.catch((): Refresh => 'unreachable')
|
||||||
.finally(() => {
|
.finally(() => {
|
||||||
refreshing = null
|
refreshing = null
|
||||||
})
|
})
|
||||||
return refreshing
|
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> {
|
async function authFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response> {
|
||||||
const request = input instanceof Request && !init ? input : new Request(input, init)
|
const request = input instanceof Request && !init ? input : new Request(input, init)
|
||||||
const retry = request.clone()
|
const retry = request.clone()
|
||||||
const response = await fetch(request)
|
const response = await fetch(request)
|
||||||
if (response.status !== 401 || new URL(request.url).pathname.startsWith('/v1/auth/')) return response
|
if (response.status !== 401 || NO_REFRESH.includes(new URL(request.url).pathname)) return response
|
||||||
if (request.headers.has('Authorization') && (await refreshTokens())) {
|
if (request.headers.has('Authorization')) {
|
||||||
retry.headers.set('Authorization', `Bearer ${getAccessToken()}`)
|
const result = await refreshTokens()
|
||||||
const again = await fetch(retry)
|
if (result === 'unreachable') return response
|
||||||
if (again.status !== 401) return again
|
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()
|
emitAuthRequired()
|
||||||
return response
|
return response
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -229,7 +229,7 @@ function FullCard({ post }: PostProps) {
|
|||||||
// 화면을 먼저 바꾸고, 실패하면 되돌린다 (서버는 실패도 200 + result.success=false 로 준다)
|
// 화면을 먼저 바꾸고, 실패하면 되돌린다 (서버는 실패도 200 + result.success=false 로 준다)
|
||||||
const setLike = (on: boolean) => {
|
const setLike = (on: boolean) => {
|
||||||
if (!loggedIn) return open({ type: 'login' })
|
if (!loggedIn) return open({ type: 'login' })
|
||||||
if (on === liked) return
|
if (on === liked || like.isPending || unlike.isPending) return
|
||||||
if (on) setPop((p) => p + 1)
|
if (on) setPop((p) => p + 1)
|
||||||
patch({ liked: on, like_count: likeCount + (on ? 1 : -1) })
|
patch({ liked: on, like_count: likeCount + (on ? 1 : -1) })
|
||||||
;(on ? like : unlike).mutate(
|
;(on ? like : unlike).mutate(
|
||||||
@@ -246,6 +246,7 @@ function FullCard({ post }: PostProps) {
|
|||||||
|
|
||||||
const toggleSave = () => {
|
const toggleSave = () => {
|
||||||
if (!loggedIn) return open({ type: 'login' })
|
if (!loggedIn) return open({ type: 'login' })
|
||||||
|
if (save.isPending || unsave.isPending) return
|
||||||
const on = !saved
|
const on = !saved
|
||||||
patch({ saved: on })
|
patch({ saved: on })
|
||||||
;(on ? save : unsave).mutate(
|
;(on ? save : unsave).mutate(
|
||||||
|
|||||||
+23
-10
@@ -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 { useCallback, useDeferredValue, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from 'react'
|
||||||
import { setTokens, subscribeAuth } from '../api/auth'
|
import { setTokens, subscribeAuth } from '../api/auth'
|
||||||
import {
|
import {
|
||||||
@@ -9,8 +9,8 @@ import {
|
|||||||
getIndexOptions,
|
getIndexOptions,
|
||||||
getSeasonWeekOptions,
|
getSeasonWeekOptions,
|
||||||
likeCommentMutation,
|
likeCommentMutation,
|
||||||
listCommentsQueryKey,
|
listCommentsInfiniteOptions,
|
||||||
listCommentsOptions,
|
listCommentsInfiniteQueryKey,
|
||||||
listRegionsOptions,
|
listRegionsOptions,
|
||||||
loginMutation,
|
loginMutation,
|
||||||
meQueryKey,
|
meQueryKey,
|
||||||
@@ -426,6 +426,7 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
|
|||||||
|
|
||||||
const toggle = () => {
|
const toggle = () => {
|
||||||
if (!loggedIn) return open({ type: 'login' })
|
if (!loggedIn) return open({ type: 'login' })
|
||||||
|
if (like.isPending || unlike.isPending) return
|
||||||
const next = !liked
|
const next = !liked
|
||||||
setLiked(next)
|
setLiked(next)
|
||||||
setCount((n) => n + (next ? 1 : -1))
|
setCount((n) => n + (next ? 1 : -1))
|
||||||
@@ -456,7 +457,7 @@ function CommentRow({ c, postId }: { c: CommentData; postId: number }) {
|
|||||||
onSuccess: (res) => {
|
onSuccess: (res) => {
|
||||||
setRemoveFailed(!res.result?.success)
|
setRemoveFailed(!res.result?.success)
|
||||||
if (!res.result?.success) return
|
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 } }) })
|
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) })
|
||||||
},
|
},
|
||||||
onError: () => setRemoveFailed(true),
|
onError: () => setRemoveFailed(true),
|
||||||
@@ -496,12 +497,16 @@ function CommentsSheet({ postId }: { postId: number }) {
|
|||||||
const { open } = useSheet()
|
const { open } = useSheet()
|
||||||
const { loggedIn, me } = useAuth()
|
const { loggedIn, me } = useAuth()
|
||||||
const queryClient = useQueryClient()
|
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 add = useMutation(addCommentMutation())
|
||||||
const [addFailed, setAddFailed] = useState(false)
|
const [addFailed, setAddFailed] = useState(false)
|
||||||
const [text, setText] = useState('')
|
const [text, setText] = useState('')
|
||||||
const inputRef = useRef<HTMLInputElement>(null)
|
const inputRef = useRef<HTMLInputElement>(null)
|
||||||
const comments = list.data?.comments ?? []
|
const comments = list.data?.pages.flatMap((p) => p.comments ?? []) ?? []
|
||||||
|
|
||||||
const submit = (e: FormEvent) => {
|
const submit = (e: FormEvent) => {
|
||||||
e.preventDefault()
|
e.preventDefault()
|
||||||
@@ -515,7 +520,7 @@ function CommentsSheet({ postId }: { postId: number }) {
|
|||||||
setAddFailed(!res.result?.success)
|
setAddFailed(!res.result?.success)
|
||||||
if (!res.result?.success) return
|
if (!res.result?.success) return
|
||||||
setText('')
|
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 } }) })
|
queryClient.invalidateQueries({ queryKey: getFeedQueryKey({ query: { region: region.code } }) })
|
||||||
},
|
},
|
||||||
onError: () => setAddFailed(true),
|
onError: () => setAddFailed(true),
|
||||||
@@ -527,7 +532,15 @@ function CommentsSheet({ postId }: { postId: number }) {
|
|||||||
<>
|
<>
|
||||||
<Body>
|
<Body>
|
||||||
{comments.length ? (
|
{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 ? (
|
) : list.isSuccess ? (
|
||||||
<p className="my-6 text-center font-semibold text-(--ink3)">
|
<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> = {
|
const AUTH_ERRORS: Record<string, string> = {
|
||||||
AUTH_FAILED: '아이디나 비밀번호가 맞지 않아요.',
|
AUTH_FAILED: '아이디나 비밀번호가 맞지 않아요.',
|
||||||
AUTH_DUPLICATE_ID: '이미 쓰고 있는 아이디예요.',
|
AUTH_DUPLICATE_ID: '이미 쓰고 있는 아이디예요.',
|
||||||
INVALID_INPUT: '아이디는 영어 소문자·숫자·_ 4~20자, 비밀번호는 8자 이상, 닉네임은 2~12자로 써 주세요.',
|
INVALID_INPUT: '아이디는 영어 소문자·숫자·_ 4~20자, 비밀번호는 8~64자, 닉네임은 2~12자로 써 주세요.',
|
||||||
}
|
}
|
||||||
|
|
||||||
function LoginSheet({ onDone }: { onDone: () => void }) {
|
function LoginSheet({ onDone }: { onDone: () => void }) {
|
||||||
@@ -622,7 +635,7 @@ function LoginSheet({ onDone }: { onDone: () => void }) {
|
|||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
<input value={loginId} onChange={(e) => setLoginId(e.target.value)} autoComplete="username" required minLength={4} maxLength={20} placeholder="아이디" aria-label="아이디" className={field} />
|
<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} />}
|
{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">
|
<p className="min-h-5 text-center text-[13px] font-bold text-(--heart)" aria-live="polite">
|
||||||
{error}
|
{error}
|
||||||
|
|||||||
Reference in new issue
Block a user