Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
8007e83
feat: 카카오 로그인 후 원래 페이지 복귀 기능 구현
yoouyeon Apr 11, 2026
a0fb892
fix: 인증 체크 API 경로 수정 및 mock 옵션 제거
yoouyeon Apr 11, 2026
903e2ea
refactor: auth loader를 features 레이어로 이동
yoouyeon Apr 11, 2026
d55c595
feat: 로그인 페이지 진입 시 인증 상태 확인 loader 추가
yoouyeon Apr 11, 2026
22750dd
fix: axios 인터셉터에서 401 시 redirectTo 파라미터 포함
yoouyeon Apr 11, 2026
d991b76
refactor: Supabase 관련 코드 제거 및 baseURL 정리
yoouyeon Apr 11, 2026
908d7cc
feat: 게스트 토큰을 cookie에 저장하는 방식으로 변경
yoouyeon Apr 11, 2026
0332532
feat: 401 응답 시 토큰 재발급 후 원래 요청 재시도
yoouyeon Apr 11, 2026
c4a67f2
fix: 로그아웃 API 경로 수정 및 mock 옵션 제거
yoouyeon Apr 11, 2026
0fe504c
fix: 서비스 탈퇴 API 경로 수정 및 mock 옵션 제거
yoouyeon Apr 11, 2026
62301fe
fix: 사용자 정보 조회 API 경로 수정 및 User 타입 API 응답에 맞게 수정
yoouyeon Apr 11, 2026
d4eb76c
refactor: 게스트 토큰 발급에서 TanStack Query 제거
yoouyeon Apr 11, 2026
33a7fca
fix: redirectTo 파라미터 Open Redirect 취약점 방어
yoouyeon Apr 11, 2026
8309bd3
fix: checkAuth 에러 처리 개선 및 redirectTo에 search, hash 포함
yoouyeon Apr 11, 2026
f262287
fix: 초기 랜더 상황을 위한 null guard
yoouyeon Apr 11, 2026
384fdc3
fix: 토큰 재발급 시 무한 루프 방지를 위해 refreshClient 분리
yoouyeon Apr 11, 2026
7848c84
Merge branch 'develop' into feat/MD-25
yoouyeon Apr 14, 2026
4daba49
fix: 게스트 로그인 후 auth 캐시 제거로 checkAuth 재검증
yoouyeon Apr 14, 2026
792bf3b
fix: 개발 환경 cross-origin 쿠키 차단 문제 해결
yoouyeon Apr 14, 2026
3868a42
fix: 토큰 재발급 실패 시 401만 로그인으로 redirect, 나머지는 상위로 전파
yoouyeon Apr 14, 2026
68cdded
fix: VITE_SERVER_URL 미설정 시 Storybook 빌드 오류 수정
yoouyeon Apr 14, 2026
61fa24a
fix: 게스트 로그인 실패 시 에러 토스트 표시
yoouyeon Apr 15, 2026
767f196
fix: proxy cookieDomainRewrite 와일드카드 적용과 URL 파싱 안전성 보강
yoouyeon Apr 15, 2026
6169b94
fix: 로그인 버튼 연타 방지 로직 추가
yoouyeon Apr 19, 2026
551da15
refactor: 안전한 경로를 반환하는 로직을 getSafeRedirectPath 유틸로 모듈화
yoouyeon Apr 19, 2026
eb9f106
refactor: URL.canParse를 이용해서 URL 검증 단계를 직관적으로 표시함
yoouyeon Apr 19, 2026
a108e92
Merge remote-tracking branch 'origin/develop' into feat/MD-25
yoouyeon Apr 19, 2026
f0b0d4e
fix: redirect 경로 검증 고도화
yoouyeon Apr 19, 2026
5f343ce
fix: loader 인증 체크를 getUserInfo 대신 getAuth로 교체
yoouyeon Apr 19, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/app/Router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import { createBrowserRouter, Outlet, RouterProvider } from 'react-router';
import { ROUTE } from '@/shared/config/route';
import RouteErrorBoundary from '@/app/RouteErrorBoundary';
import RouteErrorElement from '@/app/RouteErrorElement';
import checkAuth from '@/entities/auth/lib/checkAuth';
import checkAuth from '@/features/auth/lib/checkAuth';
import checkAlreadyAuthLoader from '@/features/auth/lib/checkAlreadyAuthLoader';
import groupTokenUrlLoader from '@/entities/auth/lib/groupTokenUrlLoader';
import createExpensePageGuardLoader from '@/pages/CreateExpensePage/lib/createExpensePageGuardLoader';
import joinLoader from '@/pages/join/loader';
Expand Down Expand Up @@ -87,6 +88,7 @@ function AppRouter() {
{
path: ROUTE.login,
element: <LazyLogin />,
loader: checkAlreadyAuthLoader,
},
{
id: 'protected',
Expand Down
13 changes: 4 additions & 9 deletions src/entities/auth/api/auth.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import axiosInstance from '@/shared/api/axios';
import { User } from '../model/user.type';
import { AuthCheckResponse, User } from '../model/user.type';

// CHECK - 게스트 토큰 정책 제거 가능성 있음
export interface GuestTokenData {
Expand All @@ -16,17 +16,12 @@ export const getGuestToken = async (): Promise<GuestTokenData> => {

// ==========

export const getAuth = async () => {
const response = await axiosInstance.get('/user/auth/check', {
useMock: true,
});
export const getAuth = async (): Promise<AuthCheckResponse> => {
const response = await axiosInstance.get<AuthCheckResponse>('/auth/check');
return response.data;
};

export const getUserInfo = async () => {
const response = await axiosInstance.get<User>('/user', {
useMock: true,
});

const response = await axiosInstance.get<User>('/user');
return response.data;
};
Comment thread
coderabbitai[bot] marked this conversation as resolved.
21 changes: 0 additions & 21 deletions src/entities/auth/api/useGetGuestToken.ts

This file was deleted.

31 changes: 0 additions & 31 deletions src/entities/auth/lib/checkAuth.ts

This file was deleted.

15 changes: 11 additions & 4 deletions src/entities/auth/lib/kakaoLogin.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
import getSafeRedirectPath from '@/shared/lib/getSafeRedirectPath';

const KAKAO_CLIENT_ID = import.meta.env.VITE_KAKAO_CLIENT_ID;
const KAKAO_REDIRECT_URI = import.meta.env.VITE_KAKAO_REDIRECT_URI;

function kakaoLogin(url?: string) {
/**
* 카카오 소셜 로그인 페이지로 이동한다.
* @param redirectPathAfterLogin - 로그인 완료 후 돌아올 경로 (pathname). 미전달 시 origin(루트)으로 이동.
* state 파라미터에 완전한 URL을 담아 전달하며, 백엔드가 로그인 완료 후 해당 URL로 redirect한다.
*/
function kakaoLogin(redirectPathAfterLogin?: string) {
if (!KAKAO_CLIENT_ID || !KAKAO_REDIRECT_URI) {
throw new Error('카카오 OAuth에 필요한 환경 변수가 설정되지 않았습니다.');
}

const defaultRedirectUrl = window.location.origin;
const redirectUrl = url || defaultRedirectUrl;
const safePath = getSafeRedirectPath(redirectPathAfterLogin);
const stateUrl = `${window.location.origin}${safePath}`;

window.location.href = `https://kauth.kakao.com/oauth/authorize?client_id=${KAKAO_CLIENT_ID}&redirect_uri=${KAKAO_REDIRECT_URI}&response_type=code&state=${encodeURIComponent(
redirectUrl
stateUrl
)}`;
}

Expand Down
12 changes: 10 additions & 2 deletions src/entities/auth/model/user.type.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
export interface User {
id: number;
email: string;
name: string;
profileImageUrl?: string;
profile?: string;
}

export interface AuthCheckResponse {
authenticated: boolean;
user?: {
id: number;
role: string;
};
reason?: string;
}
8 changes: 2 additions & 6 deletions src/features/auth/api/authApi.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import axiosInstance from '@/shared/api/axios';

export const logout = () =>
axiosInstance.post('/user/logout', null, { useMock: true });
export const logout = () => axiosInstance.post('/logout');

export const unregister = () =>
axiosInstance.delete('/users/me', {
useMock: true,
});
export const unregister = () => axiosInstance.delete('/unlink');
31 changes: 31 additions & 0 deletions src/features/auth/lib/checkAlreadyAuthLoader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { redirect } from 'react-router';
import type { LoaderFunctionArgs } from 'react-router';
import { queryClient } from '@/shared/api/queryClient';
import { getAuth } from '@/entities/auth/api/auth';
import getSafeRedirectPath from '@/shared/lib/getSafeRedirectPath';

/**
* 로그인 페이지 진입 전에 실행되는 loader
* 이미 인증된 상태라면 redirectTo 또는 홈으로 redirect한다.
*/
const checkAlreadyAuthLoader = async ({ request }: LoaderFunctionArgs) => {
try {
const user = await queryClient.ensureQueryData({
queryKey: ['auth', 'user'],
queryFn: getAuth,
staleTime: 5 * 60 * 1000,
gcTime: 10 * 60 * 1000,
});

if (user?.authenticated) {
const redirectTo = new URL(request.url).searchParams.get('redirectTo');
return redirect(getSafeRedirectPath(redirectTo));
}
} catch {
// 인증 실패 시 로그인 페이지 렌더링
}

return null;
};

export default checkAlreadyAuthLoader;
30 changes: 30 additions & 0 deletions src/features/auth/lib/checkAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { redirect } from 'react-router';
import type { LoaderFunctionArgs } from 'react-router';
import { ROUTE } from '@/shared/config/route';
import { queryClient } from '@/shared/api/queryClient';
import { getAuth } from '@/entities/auth/api/auth';

/**
* 페이지에 접근하기 전에 실행되는 함수
* */
const checkAuth = async ({ request }: LoaderFunctionArgs) => {
const user = await queryClient.ensureQueryData({
queryKey: ['auth', 'user'],
queryFn: getAuth,
staleTime: 5 * 60 * 1000, // 5 minutes
gcTime: 10 * 60 * 1000, // 10 minutes
});

if (!user || !user.authenticated) {
const { pathname, search, hash } = new URL(request.url);
const redirectTo = `${pathname}${search}${hash}`;
return redirect(
`${ROUTE.login}?redirectTo=${encodeURIComponent(redirectTo)}`
);
}

// 5xx, 네트워크 오류 등 인증과 무관한 에러는 상위로 throw → RouteErrorElement에서 처리 (error를 여기서 캐치하지 않습니다.)
return user;
};

export default checkAuth;
14 changes: 10 additions & 4 deletions src/features/user-profile/ui/MyProfile/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,28 @@ import Button from '@/shared/ui/Button';
import * as S from './index.styles';

function MyProfile() {
const { data: profile } = useGetUserInfo();
const { data: user } = useGetUserInfo();
const navigate = useNavigate();
const theme = useTheme();

// suspense로 감싸져 있긴 초기에 없는 경우의 에러를 방지하기 위해 null guard를 추가했습니다.
// ref: https://github.com/moddo-kr/moddo-frontend/pull/30#discussion_r3068041167
if (!user) {
return null;
}

return (
<S.ProfileContainer>
<ProfileImage size="36" src={profile?.profileImageUrl} />
<ProfileImage size="36" src={user?.profile} />
<Flex direction="column" flex={1} gap={4}>
<Text variant="body1Sb">{profile.name}</Text>
<Text variant="body1Sb">{user.name}</Text>
{/* TODO: 디자인 시스템 정비 후 다시 디자인 확인이 필요합니다 (Opacity를 계속 쓰는지?) */}
<Text
variant="body2R"
color="semantic.text.default"
style={{ opacity: 0.5 }}
>
{profile.email}
{user.email}
</Text>
</Flex>
{/* TODO: 현 피그마 디자인은 Chip이 Button으로 쓰이고 있는 상황이라 우선 button 컴포넌트 기준으로 구현했습니다. 디자인시스템 정리 후 다시 확인이 필요합니다! */}
Expand Down
1 change: 0 additions & 1 deletion src/mocks/handlers/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
const isMocked = request.headers.get('X-Mock-Request');
if (!isMocked || isMocked !== 'true') return passthrough();

console.log('유저 인증 체크 API 호출 - Mocked Response');

Check warning on line 19 in src/mocks/handlers/auth.ts

View workflow job for this annotation

GitHub Actions / test-and-build

Unexpected console statement

return HttpResponse.json({
authenticated: true,
Expand All @@ -29,7 +29,6 @@
if (!isMocked || isMocked !== 'true') return passthrough();

const mockUserInfo: User = {
id: 1,
name: '김모또',
email: 'moddo@kakao.com',
};
Expand Down
14 changes: 7 additions & 7 deletions src/pages/expenseDetail/loader.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// 정산 상세 페이지 전 거치는 로더
// TODO : 기존 groupToken들을 사용하는 방식을 settlementCode를 사용하는 방식으로 변경했음. 동작 확인 필요함.

import { getUserInfo } from '@/entities/auth/api/auth';
import { getAuth } from '@/entities/auth/api/auth';
import { getGroupHeader } from '@/entities/group/api/group';
import { getProfiles } from '@/entities/member/api/getProfiles';
import { queryClient } from '@/shared/api/queryClient';
Expand All @@ -18,13 +18,13 @@ async function expenseDetailLoader({ params }: LoaderFunctionArgs) {

try {
// 1. 로그인 여부 확인
// TODO: getUserInfo 401 발생 시 axiosInstance 인터셉터가 window.location.href로 처리해 returnUrl이 무시됨. 인터셉터를 React Router redirect 방식으로 교체 필요. (https://moddo2.atlassian.net/browse/MD-25)
const user = await queryClient.ensureQueryData({
queryKey: ['userInfo'],
queryFn: getUserInfo,
// TODO: getAuth 401 발생 시 axiosInstance 인터셉터가 window.location.href로 처리해 returnUrl이 무시됨. 인터셉터를 React Router redirect 방식으로 교체 필요. (https://moddo2.atlassian.net/browse/MD-27)
const auth = await queryClient.ensureQueryData({
queryKey: ['auth', 'user'],
queryFn: getAuth,
});
// TODO: 로그인 페이지에서 성공 후 returnUrl 처리 필요함
if (!user) {
if (!auth?.authenticated) {
const returnUrl = encodeURIComponent(`/expense-detail/${groupToken}`);
return redirect(`/login?returnUrl=${returnUrl}`);
}
Expand All @@ -35,7 +35,7 @@ async function expenseDetailLoader({ params }: LoaderFunctionArgs) {
queryFn: () => getProfiles(groupToken),
});
const myProfile =
profiles.find((profile) => profile.userId === user.id) ?? null;
profiles.find((profile) => profile.userId === auth.user?.id) ?? null;
if (!myProfile) return redirect(`/join/${groupToken}`);

const groupData = await queryClient.ensureQueryData({
Expand Down
14 changes: 7 additions & 7 deletions src/pages/join/loader.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// 정산 참여 페이지 전 거치는 로더
// TODO : 기존 groupToken들을 사용하는 방식을 settlementCode를 사용하는 방식으로 변경해야 함.

import { getUserInfo } from '@/entities/auth/api/auth';
import { getAuth } from '@/entities/auth/api/auth';
import { getProfiles } from '@/entities/member/api/getProfiles';
import { queryClient } from '@/shared/api/queryClient';
import { ROUTE } from '@/shared/config/route';
Expand All @@ -14,13 +14,13 @@ async function joinLoader({ params }: LoaderFunctionArgs) {
if (!groupToken) return redirect(ROUTE.home);

// 1. 로그인 여부 확인
// TODO: getUserInfo 401 발생 시 axiosInstance 인터셉터가 window.location.href로 처리해 returnUrl이 무시됨. 인터셉터를 React Router redirect 방식으로 교체 필요. (https://moddo2.atlassian.net/browse/MD-25)
const user = await queryClient.ensureQueryData({
queryKey: ['userInfo'],
queryFn: getUserInfo,
// TODO: getAuth 401 발생 시 axiosInstance 인터셉터가 window.location.href로 처리해 returnUrl이 무시됨. 인터셉터를 React Router redirect 방식으로 교체 필요. (https://moddo2.atlassian.net/browse/MD-27)
const auth = await queryClient.ensureQueryData({
queryKey: ['auth', 'user'],
queryFn: getAuth,
});

if (!user) {
if (!auth?.authenticated) {
const returnUrl = encodeURIComponent(`/join/${groupToken}`);
return redirect(`/login?returnUrl=${returnUrl}`);
}
Expand All @@ -33,7 +33,7 @@ async function joinLoader({ params }: LoaderFunctionArgs) {

// 3. 본인 프로필을 선택했는지 확인
const myProfile =
profiles.find((profile) => profile.userId === user.id) ?? null;
profiles.find((profile) => profile.userId === auth.user?.id) ?? null;
if (myProfile) return redirect(`/expense-detail/${groupToken}`);

return { profiles };
Expand Down
36 changes: 26 additions & 10 deletions src/pages/login/LoginPage.tsx
Original file line number Diff line number Diff line change
@@ -1,30 +1,45 @@
import LogoImg from '@/shared/assets/pngs/LogoImg.png';
import Text from '@/shared/ui/Text';
import { useNavigate } from 'react-router';
import { ROUTE } from '@/shared/config/route';
import { useNavigate, useSearchParams } from 'react-router';
import { useEffect, useState } from 'react';
import theme from '@/shared/styles/theme';
import Button from '@/shared/ui/Button';
import { Kakao } from '@/shared/assets/svgs/icon';
import Flex from '@/shared/ui/Flex';
import { useGetGuestToken } from '@/entities/auth/api/useGetGuestToken';
import { getGuestToken } from '@/entities/auth/api/auth';
import { ROUTE } from '@/shared/config/route';
import kakaoLogin from '@/entities/auth/lib/kakaoLogin';
import { queryClient } from '@/shared/api/queryClient';
import { showToast } from '@/shared/ui/Toast';
import LoginEntranceView from './LoginEntranceView';
import * as S from './LoginPage.styles';

function LoginPage() {
const { refetch: getGuestToken } = useGetGuestToken();
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const [isEntrance, setIsEntrance] = useState(true);
const [isGuestLoginPending, setIsGuestLoginPending] = useState(false);

const handleLoginButtonClick = (loginType: 'KAKAO' | 'GUEST') => {
const token = localStorage.getItem('accessToken');
const handleLoginButtonClick = async (loginType: 'KAKAO' | 'GUEST') => {
if (loginType === 'KAKAO') {
kakaoLogin();
} else if (!token) {
getGuestToken();
const redirectPathAfterLogin =
searchParams.get('redirectTo') ?? undefined;
kakaoLogin(redirectPathAfterLogin);
} else {
navigate(ROUTE.home);
if (isGuestLoginPending) return;
setIsGuestLoginPending(true);
try {
await getGuestToken();
queryClient.removeQueries({ queryKey: ['auth', 'user'] });
navigate(ROUTE.selectGroup);
} catch {
showToast({
type: 'error',
content: '비회원 로그인에 실패했습니다. 다시 시도해주세요.',
});
} finally {
setIsGuestLoginPending(false);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
};

Expand Down Expand Up @@ -69,6 +84,7 @@ function LoginPage() {
</Button>
<Button
variant="secondary"
disabled={isGuestLoginPending}
onClick={() => handleLoginButtonClick('GUEST')}
>
<Text variant="body1R" color="semantic.text.strong">
Expand Down
Loading
Loading