Skip to content

Commit

Permalink
Merge pull request #123 from TripInfoWeb/dev_auth
Browse files Browse the repository at this point in the history
Dev auth
  • Loading branch information
ssssksss authored Jul 16, 2024
2 parents 2f5b710 + 243f528 commit de90e0e
Show file tree
Hide file tree
Showing 5 changed files with 91 additions and 23 deletions.
35 changes: 35 additions & 0 deletions src/app/api/auth/refresh-access-token/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
try {
const cookie = request.cookies.get("refresh_token");
if (!cookie) {
return new NextResponse("Access token not found", { status: 401 });
}
// 액세스 토큰 재요청
const backendResponse = await fetch(
`${process.env.BACKEND_URL}/api/auth/oauth2/token/refresh`,
{
method: "POST",
headers: {
Cookie: `${cookie?.name}=${cookie?.value}`,
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
credentials: "include",
},
)
const result = new NextResponse(backendResponse.status == 200 ? "성공" : "실패", {
status: backendResponse.status,
headers: { "Content-Type": "application/json" },
});
if (backendResponse.status == 200) {
const accessToken = backendResponse.headers.get("set-cookie");
result.headers.set("set-cookie", accessToken as string);
}
return result;
} catch (error) {
console.error(error);
return new NextResponse("살려줘" , { status: 500 });
}
}
15 changes: 9 additions & 6 deletions src/app/api/auth/user/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,19 @@ import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
try {
const cookie = request.cookies.get("access_token");
if (!cookie) {
const access_cookie = request.cookies.get("access_token");
if (!access_cookie) {
const refresh_cookie = request.cookies.get("refresh_token");
if (!refresh_cookie) {
return new NextResponse("불필요한 요청", { status: 400 });
}
return new NextResponse("Access token not found", { status: 401 });
}

const response = await fetch(`${process.env.BACKEND_URL}/api/user/info`, {
// 사용자 정보 조회 API
const response = await fetch(`${process.env.BACKEND_URL}/api/users/info`, {
method: "GET",
headers: {
Cookie: `${cookie?.name}=${cookie?.value}`,
Cookie: `${access_cookie?.name}=${access_cookie?.value}`,
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
Expand All @@ -22,7 +26,6 @@ export async function GET(request: NextRequest) {
headers: { "Content-Type": "application/json" },
});
} catch (error) {
console.error(error);
return new NextResponse("Internal Server Error", { status: 500 });
}
}
20 changes: 12 additions & 8 deletions src/containers/auth/AuthKaKaoContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,22 +23,26 @@ const AuthKaKaoContainer = () => {
{
method: "GET",
headers: {
"Content-Type": "application/json;charset=utf-8",
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
credentials: "include",
},
);
// 액세스 토큰을 이용해서 사용자 정보 조회
const user = await fetch("/api/auth/user", {
credentials: "include",
});
user.json().then((res: userResponseDto) => {
authStore.setUser(res);
})
router.push("/");
const data = await fetch("/api/auth/user");
if (data.status == 200) {
data.json().then((res: userResponseDto) => {
authStore.setUser(res);
});
router.push("/");
}
else {
throw "";
}
} catch (error) {
console.error("로그인 실패", error);
alert("로그인에 실패했습니다.")
router.push("/auth/signin");
}
};
Expand Down
20 changes: 11 additions & 9 deletions src/containers/common/HeaderContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
import Header from "@/components/common/Header";
import useAuthStore from "@/store/authStore";
import { userResponseDto } from "@/types/UserDto";
import { fetchWithAuth } from "@/utils/fetchWithAuth";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import { useEffect, useLayoutEffect, useState } from "react";

const HeaderContainer = () => {
const pathname = usePathname();
Expand Down Expand Up @@ -40,16 +41,17 @@ const HeaderContainer = () => {
};
}, []);

useEffect(() => {
useLayoutEffect(() => {
// 자동 로그인
const login = async () => {
const user = await fetch("/api/auth/user", {
credentials: "include",
});
user.json().then((res: userResponseDto) => {
authStore.setUser(res);
});
const data = await fetchWithAuth("/api/auth/user");
if (data.status == 200) {
data.json().then((res: userResponseDto) => {
authStore.setUser(res);
});
}
};
login();
login();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

Expand Down
24 changes: 24 additions & 0 deletions src/utils/fetchWithAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@

export async function fetchWithAuth(url: string, options = {}, retries = 1) {

try {
const response = await fetch(url, options);
if (response.status === 401 && retries > 0) {
// 토큰 갱신
const data = await fetch(
`/api/auth/refresh-access-token`,
);
if (data.status == 401) {
return Promise.reject({
status: 401,
message: "실패",
});
}
// TODO: 추가적인 에러처리 필요
return await fetchWithAuth(url, options, 0); // 요청 재시도
}
return response;
} catch (error) {
throw error;
}
}

0 comments on commit de90e0e

Please sign in to comment.