-
Notifications
You must be signed in to change notification settings - Fork 0
[FEAT] 로그인 api 연동 #50
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 11 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
27108fd
DEL: 미사용 중복 ProfileForm 제거
wlsldm afff839
CHORE: api 폴더 도메인별 디렉터리로 이동
wlsldm 27faa75
FEAT: axios 인스턴스 및 인터셉터 추가
wlsldm 94104d4
FEAT: react-query 클라이언트 기본 설정 추가
wlsldm c6dee87
FEAT: 로그인 여부에 따른 라우트 접근 제어 추가
wlsldm 8d284a4
FEAT: 로그인, 로그아웃 api 연동
wlsldm e609e2e
DEL: 미사용 중복 ProfileForm 제거
wlsldm c5facd1
FIX: 쿼리 재시도 네트워크 오류와 5xx로 제한
wlsldm 55958ed
FIX: 로그인 실패 시 서버 메세지 없을 경우 기본 문구 노출
wlsldm 85f805d
FEAT: api 에러 응답 공통 처리 유틸 추가
wlsldm 95436de
FEAT: 로그인 실패 시 서버 필드 에러 폼에 노출
wlsldm a0e27ac
FIX: 취소된 요청 재시도에서 제외
wlsldm eeca918
FIX: 빈 서버 에러 메세지 기본 문구로 대체
wlsldm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| import { authInstance, publicInstance } from "@/api/instance"; | ||
| import type { ApiResponse } from "@/types/api"; | ||
| import type { AuthTokenResponse, LoginRequest } from "@/types/auth/auth"; | ||
|
|
||
| export const login = async (body: LoginRequest) => { | ||
| const { data } = await publicInstance.post<ApiResponse<AuthTokenResponse>>( | ||
| "/auth/login", | ||
| body | ||
| ); | ||
|
|
||
| return data.data; | ||
| }; | ||
|
|
||
| export const logout = async () => { | ||
| await authInstance.post<ApiResponse<string>>("/auth/logout"); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| import { useMutation, useQueryClient } from "@tanstack/react-query"; | ||
| import { useNavigate } from "react-router"; | ||
|
|
||
| import { login, logout } from "@/api/auth/api"; | ||
| import { PATH } from "@/routes/paths"; | ||
| import { useAuthStore } from "@/stores/useAuthStore"; | ||
|
|
||
| export const useLogin = () => { | ||
| const navigate = useNavigate(); | ||
| const setTokens = useAuthStore((state) => state.setTokens); | ||
|
|
||
| return useMutation({ | ||
| mutationFn: login, | ||
| onSuccess: (tokens) => { | ||
| setTokens(tokens); | ||
| navigate(PATH.HOME, { replace: true }); | ||
| }, | ||
| }); | ||
| }; | ||
|
|
||
| export const useLogout = () => { | ||
| const clearAuth = useAuthStore((state) => state.clearAuth); | ||
| const queryClient = useQueryClient(); | ||
|
|
||
| return useMutation({ | ||
| mutationFn: logout, | ||
| onSettled: () => { | ||
| clearAuth(); | ||
| queryClient.removeQueries(); | ||
| }, | ||
| }); | ||
| }; |
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| import { isAxiosError } from "axios"; | ||
|
|
||
| import { API_ERROR_MESSAGE } from "@/constants/errorMessage"; | ||
| import type { ApiErrorResponse, ApiFieldErrors } from "@/types/api"; | ||
|
|
||
| // 서버가 내려준 에러 메시지, 없으면 화면별 기본 문구 | ||
| export const getApiErrorMessage = ( | ||
| error: unknown, | ||
| fallback: string = API_ERROR_MESSAGE.DEFAULT | ||
| ) => { | ||
| if (isAxiosError<ApiErrorResponse>(error)) { | ||
| return error.response?.data?.message ?? fallback; | ||
| } | ||
|
|
||
| return fallback; | ||
| }; | ||
|
|
||
| // 필드 단위 검증 에러 — 폼 입력에 매핑 | ||
| export const getApiFieldErrors = (error: unknown): ApiFieldErrors => { | ||
| if (isAxiosError<ApiErrorResponse>(error)) { | ||
| return error.response?.data?.data?.fieldErrors ?? {}; | ||
| } | ||
|
|
||
| return {}; | ||
| }; | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| import axios from "axios"; | ||
|
|
||
| import { PATH } from "@/routes/paths"; | ||
| import { useAuthStore } from "@/stores/useAuthStore"; | ||
| import type { ApiResponse } from "@/types/api"; | ||
| import type { AuthTokenResponse } from "@/types/auth/auth"; | ||
|
|
||
| const BASE_CONFIG = { | ||
| baseURL: `${import.meta.env.VITE_API_BASE_URL}/api/v1`, | ||
| headers: { "Content-Type": "application/json" }, | ||
| timeout: 10000, | ||
| }; | ||
|
|
||
| // 토큰이 필요 없는 요청 — 로그인, 회원가입, 토큰 재발급 | ||
| export const publicInstance = axios.create(BASE_CONFIG); | ||
|
|
||
| // 토큰이 필요한 요청 — 헤더 자동 첨부, 401이면 재발급 후 재시도 | ||
| export const authInstance = axios.create(BASE_CONFIG); | ||
|
|
||
| authInstance.interceptors.request.use((config) => { | ||
| const { accessToken } = useAuthStore.getState(); | ||
| if (accessToken) { | ||
| config.headers.Authorization = `Bearer ${accessToken}`; | ||
| } | ||
|
|
||
| return config; | ||
| }); | ||
|
|
||
| let reissuePromise: Promise<string> | null = null; | ||
|
|
||
| const reissueAccessToken = async () => { | ||
| const { refreshToken } = useAuthStore.getState(); | ||
| if (!refreshToken) return null; | ||
|
|
||
| reissuePromise ??= publicInstance | ||
| .post<ApiResponse<AuthTokenResponse>>("/auth/reissue", { refreshToken }) | ||
| .then((response) => { | ||
| const tokens = response.data.data; | ||
| useAuthStore.getState().setTokens(tokens); | ||
|
|
||
| return tokens.accessToken; | ||
| }) | ||
| .finally(() => { | ||
| reissuePromise = null; | ||
| }); | ||
|
|
||
| return reissuePromise.catch(() => null); | ||
| }; | ||
|
|
||
| authInstance.interceptors.response.use( | ||
| (response) => response, | ||
| async (error) => { | ||
| const status = error.response?.status; | ||
| const originRequest = error.config; | ||
|
|
||
| if (status === 401 && originRequest) { | ||
| if (!originRequest.isRetried) { | ||
| originRequest.isRetried = true; | ||
|
|
||
| const accessToken = await reissueAccessToken(); | ||
| if (accessToken) { | ||
| originRequest.headers.Authorization = `Bearer ${accessToken}`; | ||
| return authInstance(originRequest); | ||
| } | ||
| } | ||
|
|
||
| useAuthStore.getState().clearAuth(); | ||
|
|
||
| if (window.location.pathname !== PATH.LOGIN) { | ||
| window.location.replace(PATH.LOGIN); | ||
| } | ||
| } | ||
|
|
||
| return Promise.reject(error); | ||
| } | ||
| ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| import { QueryClient } from "@tanstack/react-query"; | ||
| import { isAxiosError } from "axios"; | ||
|
|
||
| // 응답이 없는 네트워크 오류와 5xx만 재시도 | ||
| const shouldRetry = (failureCount: number, error: Error) => { | ||
| if (!isAxiosError(error)) return false; | ||
|
|
||
| const status = error.response?.status; | ||
| const isRetryable = status === undefined || status >= 500; | ||
|
|
||
| return isRetryable && failureCount < 1; | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| }; | ||
|
|
||
| export const queryClient = new QueryClient({ | ||
| defaultOptions: { | ||
| queries: { | ||
| staleTime: 1000 * 20, | ||
| gcTime: 1000 * 60 * 5, | ||
| retry: shouldRetry, | ||
| refetchOnWindowFocus: false, | ||
| }, | ||
| }, | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| // 서버가 에러 메시지를 안 내려줄 때 노출할 기본 문구 | ||
| export const API_ERROR_MESSAGE = { | ||
| DEFAULT: "요청에 실패했어요. 잠시 후 다시 시도해주세요", | ||
| LOGIN: "로그인에 실패했어요. 잠시 후 다시 시도해주세요", | ||
| } as const; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.