Skip to content

Commit

Permalink
Merge pull request #147 from TripInfoWeb/dev_auth
Browse files Browse the repository at this point in the history
쿠키가 저장이 되지 않는 문제 SSR로 변경해서 되는지 테스트
  • Loading branch information
ssssksss authored Jul 29, 2024
2 parents 0fa2dc4 + fafaea6 commit 388133b
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 11 deletions.
43 changes: 43 additions & 0 deletions src/app/api/auth/kakao/getToken/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
try {
// Query string 파싱
const url = new URL(request.url);
const code = url.searchParams.get("code");

// 백엔드에 액세스 토큰 재요청
const backendResponse = await fetch(
`${process.env.NEXT_PUBLIC_BACKEND_URL}/api/auth/oauth2/login?type=kakao&redirectUrl=${process.env.NEXT_PUBLIC_KAKAO_REDIRECT_URL}&code=${code}`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
},
credentials: "include",
},
);

const result = new NextResponse(
backendResponse.status == 200 ? "성공" : "실패",
{
status: backendResponse.status,
headers: { "Content-Type": "application/json" },
},
);

if (backendResponse.status == 200) {
const cookies = backendResponse.headers.get("set-cookie");
if (cookies) {
// 받은 쿠키를 파싱하여 설정
cookies.split(",").forEach((cookie) => {
result.headers.append("Set-Cookie", cookie.trim());
});
}
}

return result;
} catch (error) {
return new NextResponse("서버 에러", { status: 500 });
}
}
23 changes: 12 additions & 11 deletions src/containers/auth/AuthKaKaoContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,28 +17,29 @@ const AuthKaKaoContainer = () => {
}>(window.location.href);
const kakaoLogin = async () => {
try {
// 액세스와 리프레시 토큰 발급
await fetch(
`${process.env.NEXT_PUBLIC_BACKEND_URL}/api/auth/oauth2/login?type=kakao&redirectUrl=${process.env.NEXT_PUBLIC_KAKAO_REDIRECT_URL}&code=${_queryStringObject?.code}`,
const response = await fetch(
`/api/auth/kakao/getToken?code=${_queryStringObject?.code}`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
cache: "no-store",
credentials: "include",
},
);

if (response.status !== 200) {
throw new Error("Failed to login");
}

// 액세스 토큰을 이용해서 사용자 정보 조회
const data = await fetch("/api/auth/user");
if (data.status == 200) {
data.json().then((res: userResponseDto) => {
authStore.setUser(res);
});
const userDataResponse = await fetch("/api/auth/user");
if (userDataResponse.status == 200) {
const userData = await userDataResponse.json();
authStore.setUser(userData as userResponseDto);
router.push("/");
} else {
throw "";
throw new Error("Failed to fetch user data");
}
} catch (error) {
console.error("로그인 실패", error);
Expand Down

0 comments on commit 388133b

Please sign in to comment.