Skip to content

Commit

Permalink
[feat] #8 토큰 받아오기 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
choihooo committed Oct 8, 2024
1 parent e732850 commit f4bba9b
Show file tree
Hide file tree
Showing 5 changed files with 102 additions and 0 deletions.
3 changes: 3 additions & 0 deletions fe/src/types/kakao.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
interface Window {
Kakao: any;
}
55 changes: 55 additions & 0 deletions fe/src/app/api/auth/callback/kakao/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { NextRequest, NextResponse } from "next/server";

export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
const code = searchParams.get("code");
const clientId = process.env.NEXT_PUBLIC_KAKAO_CLIENT_ID;
const clientSecret = process.env.NEXT_PUBLIC_KAKAO_CLIENT_SECRET;
const redirectUri = process.env.NEXT_PUBLIC_REDIRECT_KAKAO_URI;

// 필수 매개변수가 없을 경우 처리
if (!code || !clientId || !clientSecret || !redirectUri) {
return NextResponse.json(
{ error: "Missing required parameters" },
{ status: 400 }
);
}

try {
// 카카오에 액세스 토큰 요청
const tokenResponse = await fetch(`https://kauth.kakao.com/oauth/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
client_id: clientId,
client_secret: clientSecret,
redirect_uri: redirectUri,
code: code,
}).toString(),
});

// 액세스 토큰 데이터를 받아 처리
const tokenData = await tokenResponse.json();
if (tokenData.error) {
return NextResponse.json(
{ error: tokenData.error_description },
{ status: 400 }
);
}

const accessToken = tokenData.access_token;

// 액세스 토큰 출력 (테스트 용도)
console.log("Access Token:", accessToken); // eslint-disable-line no-console

// 클라이언트에 액세스 토큰 전달
return NextResponse.json({ accessToken });
} catch (error) {
console.error("Error during OAuth process:", error);
return NextResponse.json(
{ error: "Internal server error" },
{ status: 500 }
);
}
}
34 changes: 34 additions & 0 deletions fe/src/app/component/KakaoLoginButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"use client";

import { useEffect } from "react";

export default function KakaoLoginButton() {
useEffect(() => {
// 카카오 SDK 초기화 (JavaScript Key는 환경 변수로 관리)
if (!window.Kakao.isInitialized()) {
window.Kakao.init(process.env.NEXT_PUBLIC_KAKAO_CLIENT_ID);
}
}, []);
const handleLogin = () => {
const clientId = process.env.NEXT_PUBLIC_KAKAO_CLIENT_ID;
const redirectUri = process.env.NEXT_PUBLIC_REDIRECT_KAKAO_URI;
const state = Math.random().toString(36).substring(2, 15);

if (!clientId || !redirectUri) {
alert("환경 변수가 제대로 설정되지 않았습니다.");
return;
}

const kakaoAuthUrl = `https://kauth.kakao.com/oauth/authorize?response_type=code&client_id=${clientId}&redirect_uri=${encodeURIComponent(
redirectUri
)}&state=${state}`;

window.location.href = kakaoAuthUrl;
};

return (
<button type="button" onClick={handleLogin}>
Sign in with Kakao
</button>
);
}
8 changes: 8 additions & 0 deletions fe/src/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
import Script from "next/script";

export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<head>
<Script
src="https://developers.kakao.com/sdk/js/kakao.min.js"
strategy="beforeInteractive" // 페이지 로드 전에 실행
/>
</head>
<body>
<header>
<nav>
Expand Down
2 changes: 2 additions & 0 deletions fe/src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import NaverLoginButton from "@/app/component/NaverLoginButton";
import KakaoLoginButton from "@/app/component/KakaoLoginButton";

export default function Home() {
return (
<div>
<h1>Welcome to My App</h1>
<p>Please login using Naver:</p>
<NaverLoginButton />
<KakaoLoginButton />
</div>
);
}

0 comments on commit f4bba9b

Please sign in to comment.