Commit b4873b7c authored by Jiwon Yoon's avatar Jiwon Yoon
Browse files

kakaologin-사용자 정보를 얻어오기까지

parent 5bb62e29
...@@ -2,4 +2,5 @@ node_modules/ ...@@ -2,4 +2,5 @@ node_modules/
.vscode/ .vscode/
package-lock.json package-lock.json
dist/ dist/
uploads/ uploads/
\ No newline at end of file .env
\ No newline at end of file
node_modules/ node_modules/
.vscode/ .vscode/
package-lock.json package-lock.json
dist/ dist/
\ No newline at end of file src/auth/OauthKey.tsx
\ No newline at end of file
...@@ -18,6 +18,8 @@ import { ...@@ -18,6 +18,8 @@ import {
ResultLayout, ResultLayout,
} from "./layouts"; } from "./layouts";
import { Home } from "./home"; import { Home } from "./home";
import { OAuthRedirectHandler } from "./auth/OAuthRedirectHandler";
import { LoginSuccess } from "./commons/LoginSuccess";
export const MainRouter = () => { export const MainRouter = () => {
return ( return (
...@@ -26,6 +28,8 @@ export const MainRouter = () => { ...@@ -26,6 +28,8 @@ export const MainRouter = () => {
<Route element={<BaseLayout />}> <Route element={<BaseLayout />}>
<Route path="/" element={<Home />}></Route> <Route path="/" element={<Home />}></Route>
<Route path="/login" element={<Login />} /> <Route path="/login" element={<Login />} />
<Route path="/login/success" element={<LoginSuccess />} />
<Route path="/oauth/kakao" element={<OAuthRedirectHandler />} />
<Route path="/signup" element={<SignUp />} /> <Route path="/signup" element={<SignUp />} />
<Route element={<ResultLayout />}> <Route element={<ResultLayout />}>
<Route path="/results/:surveyId" element={<ResultSurvey />} /> <Route path="/results/:surveyId" element={<ResultSurvey />} />
......
...@@ -19,3 +19,11 @@ export const signup = async (user: SignupUser) => { ...@@ -19,3 +19,11 @@ export const signup = async (user: SignupUser) => {
const { data } = await axios.post(`${baseUrl}/auth/signup`, user); const { data } = await axios.post(`${baseUrl}/auth/signup`, user);
return data; return data;
}; };
export const getKakaoUserData = async (code: string) => {
const { data } = await axios.post(`${baseUrl}/auth/oauth/kakao`, {
code: code,
});
console.log("data=", data);
return data.kakaoUserData;
};
...@@ -3,6 +3,9 @@ import { Link, useLocation, useNavigate } from "react-router-dom"; ...@@ -3,6 +3,9 @@ import { Link, useLocation, useNavigate } from "react-router-dom";
import { catchErrors } from "../helpers"; import { catchErrors } from "../helpers";
import { SpinnerIcon } from "../icons"; import { SpinnerIcon } from "../icons";
import { useAuth } from "./auth.context"; import { useAuth } from "./auth.context";
import { REST_API_KEY, REDIRECT_URI } from "../auth";
// import { authApi } from "../apis";
import KakaoLoginImg from "../icons/kakao_login_medium_wide.png";
interface LocationState { interface LocationState {
state: { from: string }; state: { from: string };
...@@ -35,6 +38,20 @@ export const Login = () => { ...@@ -35,6 +38,20 @@ export const Login = () => {
} }
} }
// async function kakaoLogin() {
// try {
// // await authApi.kakaoLogin();
// console.log("성공?");
// } catch (error) {
// setLoading(false);
// catchErrors(error, setError);
// }
// }
const kakaoLogin = () => {
window.location.href = `https://kauth.kakao.com/oauth/authorize?client_id=${REST_API_KEY}&redirect_uri=${REDIRECT_URI}&response_type=code`;
};
return ( return (
<div className="flex flex-col items-center"> <div className="flex flex-col items-center">
<div className="text-2xl mt-20">로그인</div> <div className="text-2xl mt-20">로그인</div>
...@@ -88,6 +105,11 @@ export const Login = () => { ...@@ -88,6 +105,11 @@ export const Login = () => {
</Link> </Link>
</div> </div>
</form> </form>
<div>
<button type="button" onClick={kakaoLogin}>
<img src={KakaoLoginImg} className="my-2"></img>
</button>
</div>
</div> </div>
); );
}; };
import React, { useEffect, useState } from "react";
import { authApi } from "../apis";
export const OAuthRedirectHandler = () => {
const [message, setMessage] = useState(
"잠시만 기다려 주세요! 로그인 중입니다."
);
const [code, setCode] = useState("");
useEffect(() => {
setCode(new URL(window.location.href).searchParams.get("code") as string); //인가코드
}, []);
useEffect(() => {
const getKakaoUserData = async (code: string) => {
const userData = await authApi.getKakaoUserData(code);
console.log(userData);
};
if (code) {
console.log("code=", code);
getKakaoUserData(code);
}
}, [code]);
return (
<div>
<p>{message}</p>
</div>
);
};
...@@ -2,3 +2,5 @@ export { Login } from "./Login"; ...@@ -2,3 +2,5 @@ export { Login } from "./Login";
export { AuthProvider, useAuth } from "./auth.context"; export { AuthProvider, useAuth } from "./auth.context";
export { SignUp } from "./SignUp"; export { SignUp } from "./SignUp";
export { RequireAuth } from "./RequireAuth"; export { RequireAuth } from "./RequireAuth";
export { REST_API_KEY, REDIRECT_URI} from "./OauthKey"
import React from "react";
import { Link } from "react-router-dom";
export const LoginSuccess = () => {
return (
<div className="flex flex-col mt-10 justify-center text-center text-5xl">
<h1 className="text-4xl">로그인이 완료되었습니다.</h1>
<Link to={"/"} className="mt-4">
홈으로
</Link>
</div>
);
};
...@@ -34,8 +34,10 @@ ...@@ -34,8 +34,10 @@
"typescript": "^4.7.4" "typescript": "^4.7.4"
}, },
"dependencies": { "dependencies": {
"axios": "^0.27.2",
"bcryptjs": "^2.4.3", "bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.6", "cookie-parser": "^1.4.6",
"dotenv": "^16.0.3",
"express": "^4.18.1", "express": "^4.18.1",
"formidable": "^2.0.1", "formidable": "^2.0.1",
"jsonwebtoken": "^8.5.1", "jsonwebtoken": "^8.5.1",
......
import cookieParser from "cookie-parser"; import cookieParser from "cookie-parser";
import * as dotenv from "dotenv";
dotenv.config();
import express, { Request, Response, NextFunction } from "express"; import express, { Request, Response, NextFunction } from "express";
import path from "path"; import path from "path";
import router from "./routes"; import router from "./routes";
const app = express(); const app = express();
app.use(express.json()); app.use(express.json());
......
...@@ -6,12 +6,17 @@ import isEmail from "validator/lib/isEmail"; ...@@ -6,12 +6,17 @@ import isEmail from "validator/lib/isEmail";
import { asyncWrap } from "../helpers"; import { asyncWrap } from "../helpers";
import { roleDb, userDb } from "../db"; import { roleDb, userDb } from "../db";
import { jwtCofig, envConfig, cookieConfig } from "../config"; import { jwtCofig, envConfig, cookieConfig } from "../config";
import axios from "axios";
export interface TypedRequestAuth<T> extends Request { export interface TypedRequestAuth<T> extends Request {
auth: T; auth: T;
user: any; user: any;
} }
const REST_API_KEY = process.env.REST_API_KEY as string;
const REDIRECT_URI = process.env.REDIRECT_URI as string;
const CLIENT_SECRET_KEY = process.env.CLIENT_SECRET_KEY as string;
console.log("restapikey", REST_API_KEY);
/** /**
* 함수를 호출하기 전에 req에 user 정보를 지정해야 합니다. * 함수를 호출하기 전에 req에 user 정보를 지정해야 합니다.
*/ */
...@@ -72,7 +77,9 @@ export const login = asyncWrap(async (req, res) => { ...@@ -72,7 +77,9 @@ export const login = asyncWrap(async (req, res) => {
const user = await userDb.findUserByEmail(email, true); const user = await userDb.findUserByEmail(email, true);
console.log("user =", user); console.log("user =", user);
if (!user) { if (!user) {
return res.status(422).send(`${email} 사용자가 존재하지않습니다 회원가입을 해주세요`); return res
.status(422)
.send(`${email} 사용자가 존재하지않습니다 회원가입을 해주세요`);
} }
// 2) 비밀번호 확인 // 2) 비밀번호 확인
const passwordMatch = await bcrypt.compare(password, user.password); const passwordMatch = await bcrypt.compare(password, user.password);
...@@ -149,3 +156,30 @@ export const signup = asyncWrap(async (req, res) => { ...@@ -149,3 +156,30 @@ export const signup = asyncWrap(async (req, res) => {
// 5) 사용자 반환 // 5) 사용자 반환
res.json(newUser); res.json(newUser);
}); });
export const kakaoAuthenticate = asyncWrap(async (req, res) => {
// console.log(req.query);
// const code = req.query.code as string;
console.log(req.body);
const code = req.body.code;
try {
const params = new URLSearchParams({
grant_type: "authorization_code",
client_id: REST_API_KEY,
redirect_uri: REDIRECT_URI,
code: code,
client_secret: CLIENT_SECRET_KEY,
});
const kakaoResponse = await axios.post(
"https://kauth.kakao.com/oauth/token",
params
);
console.log(kakaoResponse.data);
console.log("jwt decode:", jwt.decode(kakaoResponse.data.id_token));
// return res.redirect("http://localhost:8080/login/success");
res.json({ kakaoUserData: jwt.decode(kakaoResponse.data.id_token) });
} catch (error) {
console.log(error);
res.send("에러");
}
});
...@@ -5,6 +5,9 @@ const router = express.Router(); ...@@ -5,6 +5,9 @@ const router = express.Router();
router.route("/signup").post(authCtrl.signup); router.route("/signup").post(authCtrl.signup);
router.route("/login").post(authCtrl.login); router.route("/login").post(authCtrl.login);
router.route("/login/kakao").get(authCtrl.kakaoLogin);
router.route("/logout").get(authCtrl.logout); router.route("/logout").get(authCtrl.logout);
router.route("/oauth/kakao").post(authCtrl.kakaoAuthenticate);
export default router; export default router;
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment