Skip to content

Commit

Permalink
Merge pull request #26 from mic050r/main
Browse files Browse the repository at this point in the history
refactor : 카카오 로그인 api 라우터 분리
  • Loading branch information
mic050r authored Dec 12, 2023
2 parents d2b74de + 75ca762 commit 8d43aaf
Show file tree
Hide file tree
Showing 10 changed files with 134 additions and 129 deletions.
122 changes: 2 additions & 120 deletions api.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,16 @@
// 모듈 선언
const express = require("express");
const session = require("express-session");
const cors = require("cors");
const app = express();
const port = 3000;
const path = require("path");
const nunjucks = require("nunjucks");
const axios = require("axios");
const pool = require("./db/conn"); // 데이터베이스 연결 모듈 가져오기
const qs = require("qs");
const passport = require("passport");

const bodyParser = require("body-parser");
const inquiriesRouter = require("./routes/inquiries"); // 문의 사항
const conceptRouter = require("./routes/concept"); // 개념 포스트잇
const quizRouter = require("./routes/quiz"); // 퀴즈 포스트잇
const worngRouter = require("./routes/wrong"); // 퀴즈 포스트잇
const authRouter = require("./routes/auth"); // 퀴즈 포스트잇

// 기본 설정
app.use(cors());
Expand All @@ -29,6 +24,7 @@ app.use("/inquiries", inquiriesRouter); // 문의사항 라우터
app.use("/concept", conceptRouter); // 개념 포스트잇 라우터
app.use("/quiz", quizRouter); // 개념 포스트잇 라우터
app.use("/wrong", worngRouter); // 개념 포스트잇 라우터
app.use("/auth", authRouter); // 개념 포스트잇 라우터

app.use(
express.static("public", {
Expand All @@ -44,127 +40,13 @@ nunjucks.configure("views", {
express: app,
});

app.use(
require("express-session")({
secret: "ras",
resave: true,
saveUninitialized: true,
})
);

// Express 세션 설정
app.use(
session({
secret: "ras",
resave: true,
saveUninitialized: false,
})
);

passport.serializeUser((user, done) => {
done(null, user.id);
});

// Serialize 및 Deserialize 설정
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});

// html 파일들 라우트 정의
app.get("/", (req, res) => {
res.render("index");
});

app.use(bodyParser.json());
app.use(express.urlencoded({ extended: true }));
// 카카오 API 정보
const kakao = {
clientID: "2c536552403975785e3fdc6053dfb673",
clientSecret: "BHcC3tbvBXLAMDPfOav74BDmhIZFTe1s",
redirectUri: "http://localhost:3000/auth/kakao/callback",
logout_url: "http://localhost:3000/kakao/logout",
};

// http://localhost:3000/auth/kakao
app.get("/auth/kakao", (req, res) => {
const kakaoAuthURL = `https://kauth.kakao.com/oauth/authorize?client_id=${kakao.clientID}&redirect_uri=${kakao.redirectUri}&response_type=code`;
res.redirect(kakaoAuthURL);
});
app.get("/auth/kakao/callback", async (req, res) => {
try {
const tokenResponse = await axios({
method: "POST",
url: "https://kauth.kakao.com/oauth/token",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
data: qs.stringify({
grant_type: "authorization_code",
client_id: kakao.clientID,
client_secret: kakao.clientSecret,
redirectUri: kakao.redirectUri,
code: req.query.code,
}),
});

const { access_token } = tokenResponse.data;

const userResponse = await axios({
method: "get",
url: "https://kapi.kakao.com/v2/user/me",
headers: {
Authorization: `Bearer ${access_token}`,
},
});

// 사용자 정보를 세션에 저장
req.session.kakao = userResponse.data;

// 여기에서 세션에 토큰 및 사용자 정보 저장
req.session.accessToken = access_token;
req.session.nickname = userResponse.data.properties.nickname; // 닉네임
req.session.profileImage = userResponse.data.properties.profile_image; // 프로필 이미지

res.redirect("http://localhost:3000/home.html");
} catch (error) {
console.error("Error:", error);
res.json(error.data);
}
});

app.get("/token", (req, res) => {
const tokenInfo = {
token: req.session.nickname,
};
res.json(tokenInfo);
});

// 사용자 프로필, 닉네임 가져오는 API
app.get("/get-user-info", (req, res) => {
const userInfo = {
profileImage: req.session.profileImage,
nickname: req.session.nickname,
};

res.json(userInfo);
});

// Express 라우트에서 템플릿 렌더링
app.get("/auth/info", (req, res) => {
const { nickname, profileImage } = req.session.kakao;
res.render("info", {
nickname,
profileImage,
});
});

// 카카오 로그아웃 -> 카카오 로그아웃에 url 추가해야함
app.get("/kakao/logout", async (req, res) => {
const kakaoAuthURL = `https://kauth.kakao.com/oauth/logout?client_id=${kakao.clientID}&logout_redirect_uri=${kakao.logout_url}`;
res.redirect(kakaoAuthURL);
});

app.listen(port, () => {
console.log(`서버가 포트 ${port}에서 실행 중입니다.`);
Expand Down
2 changes: 1 addition & 1 deletion public/addposit-it(wronganswer).html
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@
// 서버로부터 토큰을 가져오는 비동기 함수
async function getToken() {
try {
const response = await fetch("http://localhost:3000/token");
const response = await fetch("http://localhost:3000/auth/token");
if (!response.ok) {
throw new Error("Network response was not ok");
}
Expand Down
2 changes: 1 addition & 1 deletion public/addpost-it(concept).html
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@
// 서버로부터 토큰을 가져오는 비동기 함수
async function getToken() {
try {
const response = await fetch("http://localhost:3000/token");
const response = await fetch("http://localhost:3000/auth/token");
if (!response.ok) {
throw new Error("네트워크 응답이 올바르지 않습니다");
}
Expand Down
2 changes: 1 addition & 1 deletion public/addpost-it(quiz).html
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@
// 서버로부터 토큰을 가져오는 비동기 함수
async function getToken() {
try {
const response = await fetch("http://localhost:3000/token");
const response = await fetch("http://localhost:3000/auth/token");
if (!response.ok) {
throw new Error("네트워크 응답이 올바르지 않습니다");
}
Expand Down
2 changes: 1 addition & 1 deletion public/category(concept).html
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@
// 서버로부터 토큰을 가져오는 비동기 함수
async function getToken() {
try {
const response = await fetch("http://localhost:3000/token");
const response = await fetch("http://localhost:3000/auth/token");
if (!response.ok) {
throw new Error("네트워크 응답이 올바르지 않습니다");
}
Expand Down
2 changes: 1 addition & 1 deletion public/category(quiz).html
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@
// 서버로부터 토큰을 가져오는 비동기 함수
async function getToken() {
try {
const response = await fetch("http://localhost:3000/token");
const response = await fetch("http://localhost:3000/auth/token");
if (!response.ok) {
throw new Error("네트워크 응답이 올바르지 않습니다");
}
Expand Down
2 changes: 1 addition & 1 deletion public/category(wronganswer).html
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@
// 서버로부터 토큰을 가져오는 비동기 함수
async function getToken() {
try {
const response = await fetch("http://localhost:3000/token");
const response = await fetch("http://localhost:3000/auth/token");
if (!response.ok) {
throw new Error("네트워크 응답이 올바르지 않습니다");
}
Expand Down
4 changes: 2 additions & 2 deletions public/home.html
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ <h2 style="font-size: 20px">포스트잇 추가</h2>
</li>
<!-- <li><a href="javascript:void(0)">버전정보</a></li> -->
<li><a href="./noticeboard.html">문의사항</a></li>
<li><a href="http://localhost:3000/kakao/logout">로그아웃</a></li>
<li><a href="http://localhost:3000/auth/kakao/logout">로그아웃</a></li>
</ul>
</div>

Expand All @@ -108,7 +108,7 @@ <h2 style="font-size: 20px">포스트잇 추가</h2>
// 예시로 fetch를 사용한 클라이언트 측 코드
async function getUserInfo() {
try {
const response = await fetch("http://localhost:3000/get-user-info", {
const response = await fetch("http://localhost:3000/auth/user/info", {
method: "GET",
credentials: "include",
});
Expand Down
2 changes: 1 addition & 1 deletion public/notibeboardtyping.html
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ <h3>게시글 작성</h3>
// 비동기 함수 내에서 await 사용
async function getToken() {
try {
const response = await fetch("http://localhost:3000/token");
const response = await fetch("http://localhost:3000/auth/token");
if (!response.ok) {
throw new Error("Network response was not ok");
}
Expand Down
123 changes: 123 additions & 0 deletions routes/auth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// 모듈 선언
const qs = require("qs");
const express = require("express");
const session = require("express-session");
const axios = require("axios");
const passport = require("passport");
const router = express.Router();

router.use(
require("express-session")({
secret: "ras",
resave: true,
saveUninitialized: true,
})
);

// Express 세션 설정
router.use(
session({
secret: "ras",
resave: true,
saveUninitialized: false,
})
);

passport.serializeUser((user, done) => {
done(null, user.id);
});

// Serialize 및 Deserialize 설정
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});

// 카카오 API 정보
const kakao = {
clientID: "2c536552403975785e3fdc6053dfb673",
clientSecret: "BHcC3tbvBXLAMDPfOav74BDmhIZFTe1s",
redirectUri: "http://localhost:3000/auth/kakao/callback",
logout_url: "http://localhost:3000/auth/kakao/logout",
};

// http://localhost:3000/auth/kakao
router.get("/kakao", (req, res) => {
const kakaoAuthURL = `https://kauth.kakao.com/oauth/authorize?client_id=${kakao.clientID}&redirect_uri=${kakao.redirectUri}&response_type=code`;
res.redirect(kakaoAuthURL);
});

router.get("/kakao/callback", async (req, res) => {
try {
const tokenResponse = await axios({
method: "POST",
url: "https://kauth.kakao.com/oauth/token",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
data: qs.stringify({
grant_type: "authorization_code",
client_id: kakao.clientID,
client_secret: kakao.clientSecret,
redirectUri: kakao.redirectUri,
code: req.query.code,
}),
});

const { access_token } = tokenResponse.data;

const userResponse = await axios({
method: "get",
url: "https://kapi.kakao.com/v2/user/me",
headers: {
Authorization: `Bearer ${access_token}`,
},
});

// 사용자 정보를 세션에 저장
req.session.kakao = userResponse.data;

// 여기에서 세션에 토큰 및 사용자 정보 저장
req.session.accessToken = access_token;
req.session.nickname = userResponse.data.properties.nickname; // 닉네임
req.session.profileImage = userResponse.data.properties.profile_image; // 프로필 이미지

res.redirect("http://localhost:3000/home.html");
} catch (error) {
console.error("Error:", error);
res.json(error.data);
}
});

router.get("/token", (req, res) => {
const tokenInfo = {
token: req.session.nickname,
};
res.json(tokenInfo);
});

// 사용자 프로필, 닉네임 가져오는 API
router.get("/user/info", (req, res) => {
const userInfo = {
profileImage: req.session.profileImage,
nickname: req.session.nickname,
};

res.json(userInfo);
});

router.get("/kakao/logout", async (req, res) => {
// 세션 초기화
req.session.destroy((err) => {
if (err) {
console.error("세션 초기화 오류:", err);
}

// 카카오 로그아웃 URL로 리다이렉트
const kakaoAuthURL = `https://kauth.kakao.com/oauth/logout?client_id=${kakao.clientID}&logout_redirect_uri=${kakao.logout_url}`;
res.redirect(kakaoAuthURL);
});
});

module.exports = router;

0 comments on commit 8d43aaf

Please sign in to comment.