Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
4 changes: 3 additions & 1 deletion components/Auth/SnsLogin.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ const SnsLogin = () => {
<div className="flex items-center justify-between bg-gray300 rounded-lg px-6 py-3 mt-8">
<span>소셜 로그인</span>
<div className="flex gap-4">
<Link href="https://accounts.google.com/o/oauth2/v2/auth?scope=openid%20profile%20email&response_type=token&redirect_uri=http://localhost:3000/google&client_id=1079911783112-7rg5ecp9ia9lorm7pit0m2nb2ti1rpt0.apps.googleusercontent.com">
<Link
href={`https://accounts.google.com/o/oauth2/v2/auth?scope=https%3A//www.googleapis.com/auth/drive.metadata.readonly&response_type=code&redirect_uri=http://localhost:3000/api/auth/sign-up/google&client_id=${process.env.GOOGLE_CLIENT_ID}`}
>
<Image src="/icons/google.svg" width="42" height="42" alt="구글" />
</Link>
<Image
Expand Down
22 changes: 22 additions & 0 deletions pages/api/auth/sign-in/google.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import axiosInstance from "@/lib/api/axiosInstanceApi";
import { NextApiRequest, NextApiResponse } from "next";

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === "POST") {
try {
const { token, redirectUri } = req.body;

await axiosInstance.post("/auth/sign-in/google", {
token,
redirectUri,
});
return res.status(200).json({ message: "회원가입 성공" });
} catch (error) {
return res.status(400).json({ message: "서버 오류" });
}
} else {
res.status(405).json({ message: "허용되지 않은 접근 방법" });
}
};

export default handler;
File renamed without changes.
68 changes: 68 additions & 0 deletions pages/api/auth/sign-up/google.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import axios from "axios";
import axiosInstance from "@/lib/api/axiosInstanceApi";
import { NextApiRequest, NextApiResponse } from "next";

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
try {
const { code } = req.query;
if (!code) {
return res.status(400).json({ message: "인증 코드가 없습니다." });
}

const clientId = process.env.GOOGLE_CLIENT_ID;
const clientSecret = process.env.GOOGLE_CLIENT_SECRET;
const redirectUri =
process.env.GOOGLE_REDIRECT_URI || "http://localhost:3000/";

if (!clientId || !clientSecret) {
return res
.status(500)
.json({ message: "Google API 클라이언트 정보가 설정되지 않았습니다." });
}

const tokenUrl = "https://oauth2.googleapis.com/token";
const params = new URLSearchParams({
code: code as string,
client_id: clientId,
client_secret: clientSecret,
redirect_uri: redirectUri,
grant_type: "authorization_code",
});

// 토큰 요청
const tokenResponse = await axios.post(tokenUrl, params.toString(), {
headers: { "Content-Type": "application/x-www-form-urlencoded" },
});

const { access_token } = tokenResponse.data;
if (!access_token) {
return res
.status(401)
.json({ message: "액세스 토큰을 가져오지 못했습니다." });
}

// 사용자 정보 요청
const userInfoResponse = await axios.get(
`https://www.googleapis.com/oauth2/v3/userinfo?access_token=${access_token}`
);
const userInfo = userInfoResponse.data;

// 서버로 사용자 정보 전송
await axiosInstance.post("/auth/sign-up/google", {
name: userInfo.name,
token: access_token,
redirectUri: "http://localhost:3000", // 실제 배포 환경에서는 환경 변수 사용
});

// 성공적인 응답
return res.status(200).json({ message: "회원가입 성공", user: userInfo });
} catch (error: any) {
console.error("Error:", error.response?.data || error.message);
return res.status(500).json({
message: "서버 오류",
error: error.response?.data || error.message,
});
}
};

export default handler;
File renamed without changes.
50 changes: 42 additions & 8 deletions pages/google.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,55 @@
import { proxy } from "@/lib/api/axiosInstanceApi";
import axios from "axios";
import { useEffect } from "react";

const Google = () => {
useEffect(() => {
const hash = window.location.hash;
const params = new URLSearchParams(hash.substring(1));
const token = params.get("access_token");
console.log(token);
const idToken = params.get("id_token"); // Google에서 전달받은 id_token
const accessToken = params.get("access_token"); // Google에서 전달받은 id_token

axios
.get(`https://www.googleapis.com/oauth2/v2/userinfo`, {
headers: { Authorization: `Bearer ${token}` },
})
.then((res) => console.log(res));
if (accessToken) {
console.log(" Access Token:", accessToken);
proxy
.post("/api/auth/sign-up/google", {
name: "박문균",
token: accessToken,
redirectUri: "http://localhost:3000/google",
})
Comment on lines +15 to +19
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

테스트 하기 위해 name 을 고정으로 넣어보신 건가욧!?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아 이 페이지는 없애야하는 데 깜빡했네여 merge하기 전에 수정해서 push할게욥

.then((response) => {
console.log("Authentication Success:", response.data);
// 성공적인 로그인 처리 후, 리다이렉션 등의 작업을 할 수 있습니다.
})
.catch((error) => {
console.error("Authentication Error:", error);
});
} else {
console.error("Access Token이 없습니다.");
}

if (idToken) {
console.log("Id Token:", idToken);

// 서버로 id_token을 전달하여 인증을 요청합니다.
proxy
.post("/api/auth/sign-in/google", {
token: idToken,
redirectUri: "http://localhost:3000/google",
})
.then((response) => {
console.log("Authentication Success:", response.data);
// 성공적인 로그인 처리 후, 리다이렉션 등의 작업을 할 수 있습니다.
})
.catch((error) => {
console.error("Authentication Error:", error);
});
} else {
console.error("Id Token이 없습니다.");
}
}, []);

return <div>안녕</div>;
return <div>Google OAuth 로그인 완료</div>;
};

export default Google;