Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
23 changes: 23 additions & 0 deletions src/api/auth/exchangeTempToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { apiClient } from '../index';

export type ExchangeTempTokenRequest = Record<string, never>;

export interface ExchangeTempTokenResponse {
isSuccess: boolean;
code: number;
message: string;
data: {
accessToken: string;
// 기타 필요한 응답 데이터
};
}

export const exchangeTempToken = async (
data?: ExchangeTempTokenRequest,
): Promise<ExchangeTempTokenResponse> => {
const response = await apiClient.post<ExchangeTempTokenResponse>(
'/auth/exchange-temp-token',
data,
);
return response.data;
};
2 changes: 2 additions & 0 deletions src/api/auth/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { setCookie } from './setCookie';
export { exchangeTempToken } from './exchangeTempToken';
15 changes: 15 additions & 0 deletions src/api/auth/setCookie.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { apiClient } from '../index';

export type SetCookieRequest = Record<string, never>;

export interface SetCookieResponse {
isSuccess: boolean;
code: number;
message: string;
data: Record<string, unknown>;
}

export const setCookie = async (data?: SetCookieRequest): Promise<SetCookieResponse> => {
const response = await apiClient.post<SetCookieResponse>('/auth/set-cookie', data);
return response.data;
};
44 changes: 0 additions & 44 deletions src/hooks/useOAuthToken.ts

This file was deleted.

78 changes: 78 additions & 0 deletions src/hooks/useSocialLoginToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { apiClient } from '@/api/index';

export const useSocialLoginToken = () => {
const navigate = useNavigate();
const location = useLocation();

useEffect(() => {
const handleSocialLoginToken = async () => {
// URL에서 loginTokenKey 가져오기
const params = new URLSearchParams(window.location.search);
const loginTokenKey = params.get('loginTokenKey');

if (!loginTokenKey) {
console.log('🔑 loginTokenKey가 없습니다.');
return;
}

// 현재 경로가 /signup인지 확인
const isSignupPage = location.pathname === '/signup';

try {
if (isSignupPage) {
// 회원가입 페이지인 경우: 임시토큰 발급 요청
console.log('🔑 회원가입 페이지: 임시토큰 발급 요청');
console.log('📋 loginTokenKey:', loginTokenKey);

const response = await apiClient.post(
'/auth/set-cookie',
{ loginTokenKey },
{ withCredentials: true },
);

if (response.data.isSuccess) {
console.log('✅ 임시토큰 발급 성공');
// URL에서 loginTokenKey 파라미터 제거
const newUrl = window.location.pathname;
window.history.replaceState({}, document.title, newUrl);
} else {
console.error('❌ 임시토큰 발급 실패:', response.data.message);
}
} else {
// 피드 페이지 등 다른 페이지인 경우: 엑세스토큰 발급 요청
console.log('🔑 피드 페이지: 엑세스토큰 발급 요청');
console.log('📋 loginTokenKey:', loginTokenKey);

const response = await apiClient.post(
'/auth/exchange-temp-token',
{ loginTokenKey },
{ withCredentials: true },
);

if (response.data.isSuccess) {
console.log('✅ 엑세스토큰 발급 성공');
// URL에서 loginTokenKey 파라미터 제거
const newUrl = window.location.pathname;
window.history.replaceState({}, document.title, newUrl);
} else {
console.error('❌ 엑세스토큰 발급 실패:', response.data.message);
navigate('/');
}
}
} catch (error) {
console.error('💥 토큰 발급 중 오류 발생:', error);
navigate('/');
}
};

// 소셜 로그인 후 리다이렉트된 경우에만 실행
const urlParams = new URLSearchParams(location.search);
const isSocialLoginComplete = urlParams.get('loginTokenKey');

if (isSocialLoginComplete) {
handleSocialLoginToken();
}
}, [location.pathname, navigate]); // location.pathname과 navigate만 의존성으로 설정
};
4 changes: 2 additions & 2 deletions src/pages/feed/Feed.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import writefab from '../../assets/common/writefab.svg';
import { useNavigate, useLocation } from 'react-router-dom';
import { getTotalFeeds } from '@/api/feeds/getTotalFeed';
import { getMyFeeds } from '@/api/feeds/getMyFeed';
import { useOAuthToken } from '@/hooks/useOAuthToken';
import { useSocialLoginToken } from '@/hooks/useSocialLoginToken';
import type { PostData } from '@/types/post';

const tabs = ['피드', '내 피드'];
Expand All @@ -21,7 +21,7 @@ const Feed = () => {
const [activeTab, setActiveTab] = useState<string>(initialTabFromState ?? tabs[0]);

// 소셜 로그인 토큰 발급 처리
useOAuthToken();
useSocialLoginToken();

// 최초 마운트 시에만 history state 제거하여 이후 재방문 시 영향 없도록 처리
useEffect(() => {
Expand Down
4 changes: 4 additions & 0 deletions src/pages/signup/SignupGenre.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Container } from './Signup.styled';
import leftarrow from '../../assets/common/leftArrow.svg';
import TitleHeader from '../../components/common/TitleHeader';
import { postSignup } from '@/api/users/postSignup';
import { useSocialLoginToken } from '@/hooks/useSocialLoginToken';

const SignupGenre = () => {
const [genres, setGenres] = useState<
Expand All @@ -22,6 +23,9 @@ const SignupGenre = () => {
const navigate = useNavigate();
const location = useLocation();

// 소셜 로그인 토큰 발급 처리
useSocialLoginToken();

// SignupNickname에서 넘어온 nickname 받기
const nickname = location.state?.nickname;

Expand Down
4 changes: 2 additions & 2 deletions src/pages/signup/SignupNickname.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useNavigate } from 'react-router-dom';
import { Container, InputBox, StyledInput, CharCount } from './Signup.styled';
import Header from '../../components/common/TitleHeader';
import { postNickname } from '@/api/users/postNickname';
import { useOAuthToken } from '@/hooks/useOAuthToken';
import { useSocialLoginToken } from '@/hooks/useSocialLoginToken';

const SignupNickname = () => {
const [nickname, setNickname] = useState('');
Expand All @@ -12,7 +12,7 @@ const SignupNickname = () => {
const navigate = useNavigate();

// 소셜 로그인 토큰 발급 처리
useOAuthToken();
useSocialLoginToken();

const isNextActive = nickname.length >= 2 && nickname.length <= maxLength;

Expand Down