Skip to content
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

Fix/auth provider #91

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
"next": "14.2.12",
"next-intl": "^3.7.0",
"openapi-fetch": "^0.12.2",
"openapi-react-query": "^0.2.0",
"react": "^18",
"react-cookie": "^7.1.4",
"react-dom": "^18",
Expand Down
14 changes: 14 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 4 additions & 5 deletions src/api/api.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import type { paths } from '@src/__generated__/api';
import createClient from 'openapi-fetch';
import createFetchClient from 'openapi-fetch';
import createClient from 'openapi-react-query';

const client = createClient<paths>({
export const client = createFetchClient<paths>({
baseUrl: `${process.env.NEXT_PUBLIC_META_TEST_SERVER_HOST_URL}`,
});

const { data, response } = await client.GET('/users');

console.log(data, 'data');
export const $api = createClient(client);
2 changes: 1 addition & 1 deletion src/app/auth/components/AuthPageClient.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const toastService = ToastService.getInstance();
const processSocialLogin = async ({ code, socialType, loginPath }: SocialLoginRequestParameter) => {
try {
const { data } = await axios.post(
`${process.env.NEXT_PUBLIC_MATE_TEST_WEB_HOST_URL}/api/social-login`,
`${process.env.NEXT_PUBLIC_META_TEST_WEB_HOST_URL}/api/social-login`,
{
code,
socialType,
Expand Down
3 changes: 2 additions & 1 deletion src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export const metadata: Metadata = {

const LocaleLayout: FC<LocaleLayoutProps> = async ({ children }) => {
const accessToken = cookies().get('atk')?.value;
const refreshToken = cookies().get('rtk')?.value;
const { token } = await checkToken(accessToken);

return (
Expand All @@ -61,7 +62,7 @@ const LocaleLayout: FC<LocaleLayoutProps> = async ({ children }) => {
<body>
<AuthProvider
accessToken={accessToken ?? token?.access_token}
refreshToken={token?.refresh_token}
refreshToken={refreshToken ?? token?.refresh_token}
/>
<TanstackQueryProvider>
{children}
Expand Down
10 changes: 6 additions & 4 deletions src/components/common/quiz-result/QuizResultHistoryGraphCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { QuizTestLevel } from '@src/types/api/test';
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
import { FC, useState } from 'react';
import { QuizResultBarChart } from './QuizResultBarChart';
import { $api } from '@src/api/api';

interface QuizResultHistoryGraphCardProps {
isLogin: boolean;
Expand Down Expand Up @@ -37,10 +38,11 @@ function isValidTestLevelType(value: unknown): value is QuizTestLevel {

const QuizResultHistoryGraphCard: FC<QuizResultHistoryGraphCardProps> = ({ isLogin }) => {
const [selectedLevel, setSelectedLevel] = useState<QuizTestLevel>('all');
const { data: userData } = useQuery({
queryKey: [API_GET_USER_PROFILE],
queryFn: () => getUserProfile(),
});
// const { data: userData } = useQuery({
// queryKey: [API_GET_USER_PROFILE],
// queryFn: () => getUserProfile(),
// });
const { data: userData } = $api.useQuery('get', '/users');
const {
data: chartData,
hasNextPage,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { isAxiosError } from 'axios';
import { FormProvider, useForm } from 'react-hook-form';
import MyPageInformationEditEmailInput from './MyPageInformationEditEmailInput';
import MyPageInformationEditSubmitButton from './MyPageInformationEditSubmitButton';
import { $api } from '@src/api/api';

interface MyPageInformationEditModalScreenProps {}

Expand All @@ -34,10 +35,11 @@ const MyPageInformationEditModalScreen: FC<MyPageInformationEditModalScreenProps
isSuccessAuthorization: false,
request_id: undefined,
});
const userInformationQuery = useQuery({
queryKey: [API_GET_USER_PROFILE],
queryFn: getUserProfile,
});
const { data: userData } = $api.useQuery('get', '/users');
// const userInformationQuery = useQuery({
// queryKey: [API_GET_USER_PROFILE],
// queryFn: getUserProfile,
// });

const toastService = ToastService.getInstance();
const modalService = ModalService.getInstance();
Expand Down Expand Up @@ -153,7 +155,7 @@ const MyPageInformationEditModalScreen: FC<MyPageInformationEditModalScreenProps
>
<p className="text-2xl font-bold">정보수정</p>
<section className="mt-5 flex flex-col gap-6">
{userInformationQuery.data?.userType === 'NORMAL' && (
{userData?.userType === 'NORMAL' && (
<section className="flex w-full flex-col gap-3">
<section>
<p className="text-base font-bold text-gray-400">아이디(이메일)</p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { FormProvider, useForm } from 'react-hook-form';
import MyPagePasswordEditNewPasswordConfirmInput from './MyPagePasswordEditNewPasswordConfirmInput';
import MyPagePasswordEditNewPasswordInput from './MyPagePasswordEditNewPasswordInput';
import MyPagePasswordEditSubmitButton from './MyPagePasswordEditSubmitButton';
import { $api } from '@src/api/api';

interface MyPagePasswordEditModalScreenProps {}

Expand All @@ -27,10 +28,12 @@ const MyPagePasswordEditModalScreen: FC<MyPagePasswordEditModalScreenProps> = ()
const updatePassword = useMutation({
mutationFn: patchUsers,
});
const userInformation = useQuery({
queryKey: [API_GET_USER_PROFILE],
queryFn: getUserProfile,
});
// const userData?Query({
// queryKey: [API_GET_USER_PROFILE],
// queryFn: getUserProfile,
// });

const { data: userData } = $api.useQuery('get', '/users');

const form = useForm<MyPagePasswordEditForm>({
defaultValues: {
Expand Down Expand Up @@ -68,11 +71,11 @@ const MyPagePasswordEditModalScreen: FC<MyPagePasswordEditModalScreenProps> = ()
<section className="flex w-full flex-col gap-3">
<section className="flex w-full gap-3">
<p className="text-base font-bold text-gray-400">아이디</p>
<span>{userInformation.data?.email}</span>
<span>{userData?.email}</span>
</section>
<section className="flex gap-3">
<p className="text-base font-bold text-gray-400">닉네임</p>
<span>{userInformation.data?.nickname}</span>
<span>{userData?.nickname}</span>
</section>
</section>
<section className="flex w-full flex-col gap-3">
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
'use client';

import { FC } from 'react';
import { API_GET_USER_PROFILE } from '@src/api/getUserProfile';
import Button from '@src/components/common/Button';
import HomeIcon from '@src/components/common/Icons/HomeIcon';
import { ToastService } from '@src/service/ToastService';
Expand All @@ -10,6 +9,7 @@ import { useRouter } from 'next/navigation';
import { useCookies } from 'react-cookie';
import axios from 'axios';
import { renewAllCache } from '@src/app/actions/renewAllCache';
import { $api } from '@src/api/api';

interface MyPageHeaderSectionProps {
isLogin: boolean;
Expand All @@ -26,7 +26,7 @@ const MyPageHeaderSection: FC<MyPageHeaderSectionProps> = ({ isLogin }) => {
await axios.delete(`${process.env.NEXT_PUBLIC_META_TEST_WEB_HOST_URL}/api/auth`);
await renewAllCache();
await queryClient.removeQueries({
queryKey: [API_GET_USER_PROFILE],
queryKey: $api.queryOptions('get', '/users').queryKey,
});
await toastService.addToast('로그아웃 되었습니다.');
replace('/');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { useRouter } from 'next/navigation';
import { FormProvider, useForm } from 'react-hook-form';
import QuizAnswerExpectationInput from './QuizAnswerExpectationInput';
import QuizAnswerExpectationSubmitButton from './QuizAnswerExpectationSubmitButton';
import { $api } from '@src/api/api';

interface QuizAnswerExpectationFormProps {
answers: string[];
Expand All @@ -32,10 +33,8 @@ const getQuizLevel = (array: string[]) => {

const QuizAnswerExpectationForm: FC<QuizAnswerExpectationFormProps> = ({ answers }) => {
const { replace } = useRouter();
const { data: userProfile } = useQuery({
queryKey: [API_GET_USER_PROFILE],
queryFn: () => getUserProfile(),
});
const { data: userData } = $api.useQuery('get', '/users');

const modalService = ModalService.getInstance();
const quizService = QuizListService.getInstance();
const testSubmit = useMutation({
Expand All @@ -56,7 +55,7 @@ const QuizAnswerExpectationForm: FC<QuizAnswerExpectationFormProps> = ({ answers
const onValid = ({ expectationNumber }: QuizAnswerExpectationPopupFormValue) => {
testSubmit.mutate(
{
id: userProfile?.id,
id: userData?.id,
level: getQuizLevel(quizService.getQuizList().flatMap((quiz) => quiz.word)),
total_count: quizService.getQuizList().length,
expected_count: Number(expectationNumber),
Expand Down
8 changes: 3 additions & 5 deletions src/components/screens/quiz-result/QuizResultHeaderText.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,17 @@
import { FC } from 'react';
import { API_GET_USER_PROFILE, getUserProfile } from '@src/api/getUserProfile';
import { useQuery } from '@tanstack/react-query';
import { $api } from '@src/api/api';

interface QuizResultHeaderTitleProps {}

const QuizResultHeaderTitle: FC<QuizResultHeaderTitleProps> = () => {
const { data } = useQuery({
queryKey: [API_GET_USER_PROFILE],
queryFn: () => getUserProfile(),
});
const { data: userData } = $api.useQuery('get', '/users');

return (
<section>
<h1 className="font-sans text-4xl font-bold">
{data?.nickname ?? 'ooo'}님의 테스트 결과
{userData?.nickname ?? 'ooo'}님의 테스트 결과
</h1>
<hr className="mt-4 border-2 border-violet-400" />
</section>
Expand Down
8 changes: 1 addition & 7 deletions src/components/screens/quiz-result/QuizResultScoreCard.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
'use client';

import { randomUUID } from 'crypto';
import { FC } from 'react';
import { API_GET_USER_PROFILE, getUserProfile } from '@src/api/getUserProfile';
import { API_GET_USER_TEST_DETAIL, getUserTestDetail } from '@src/api/getUserTestDetail';
import StarIcon from '@src/components/common/Icons/StarIcon';
import { useQuery } from '@tanstack/react-query';
import { useSearchParams } from 'next/navigation';
import { FC } from 'react';

interface QuizResultScoreCardProps {}

Expand Down Expand Up @@ -51,10 +49,6 @@ const calculateFillRatio = ({ totalScore, maxScore, index }: StarIconFillRatioPr

const QuizResultScoreCard: FC<QuizResultScoreCardProps> = () => {
const queryParams = useSearchParams();
const userProfileQuery = useQuery({
queryKey: [API_GET_USER_PROFILE],
queryFn: () => getUserProfile(),
});

const userTestQuery = useQuery({
queryKey: [API_GET_USER_TEST_DETAIL],
Expand Down
47 changes: 47 additions & 0 deletions src/provider/AuthProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,65 @@
'use client';

import { client } from '@src/api/api';
import { setAuthCookie } from '@src/app/actions/setAuthCookie';
import defaultRequest from '@src/lib/axios/defaultRequest';
import { Middleware } from 'openapi-fetch';
import { FC, useEffect } from 'react';

interface IAuthProviderProps {
accessToken?: string;
refreshToken?: string;
}

let retryCount = 0;
const maxRetries = 1;

export const AuthProvider: FC<IAuthProviderProps> = ({ accessToken, refreshToken }) => {
useEffect(() => {
if (accessToken && refreshToken) {
setAuthCookie({ rtk: refreshToken, atk: accessToken });
const authMiddleware: Middleware = {
async onRequest({ request }) {
// 토큰이 있을 때 Authorization 헤더 추가
if (accessToken) {
request.headers.set('Authorization', `Bearer ${accessToken}`);
}
return request;
},
async onResponse({ response, request }) {
// 401 에러 처리
if (response.status === 401 && retryCount < maxRetries) {
retryCount += 1;

try {
// 리프레시 토큰을 사용해 새로운 액세스 토큰 요청
const tokenResponse = await client.POST('/auth/token/refresh', {
body: { refresh_token: refreshToken },
});
const newAccessToken = tokenResponse.data?.access_token;

if (newAccessToken) {
// Authorization 헤더에 새 토큰 추가
request.headers.set('Authorization', `Bearer ${newAccessToken}`);

// 토큰 쿠키에 저장
setAuthCookie({ rtk: refreshToken, atk: newAccessToken });

// 원래 요청을 다시 시도
return response;
}
} catch (error) {
console.error('토큰 갱신 실패:', error);
return Promise.reject(error);
}
}

return response;
},
};

// client에 미들웨어 추가
client.use(authMiddleware);
}
}, [accessToken, refreshToken]);

Expand Down