Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨카카오 로그인 1차 프론트구현 #24

Merged
merged 6 commits into from
Oct 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
100 changes: 100 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"preview": "vite preview"
},
"dependencies": {
"axios": "^1.7.7",
"eslint-config-prettier": "^9.1.0",
"prop-types": "^15.8.1",
"react": "^18.3.1",
Expand Down
69 changes: 69 additions & 0 deletions src/api/LoginHandeler.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
//LoginHandeler.jsx

import { useNavigate } from "react-router-dom";
import { useEffect, useState } from "react";
import axios from "axios";

const LoginHandler = () => {
const navigate = useNavigate();
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
const code = new URL(window.location.href).searchParams.get("code");

useEffect(() => {
const kakaoLogin = async () => {
try {
const response = await axios({
method: "GET",
url: `${import.meta.env.VITE_REACT_APP_REDIRECT_URL}/?code=${code}`,
headers: {
"Content-Type": "application/json;charset=utf-8",
"Access-Control-Allow-Origin": "*",
},
});

console.log(response);
localStorage.setItem("name", response.data.account.kakaoName);
navigate("/mainpage");
} catch (err) {
console.error("Login error:", err);
setError("로그인 중 오류가 발생했습니다.");
} finally {
setIsLoading(false);
}
};

if (code) {
kakaoLogin();
} else {
setError("인가 코드를 찾을 수 없습니다.");
setIsLoading(false);
}
}, [code, navigate]);

if (isLoading) {
return (
<div className="LoginHandler">
<div className="notice">
<p>로그인 중입니다.</p>
<p>잠시만 기다려주세요.</p>
<div className="spinner"></div>
</div>
</div>
);
}

if (error) {
return (
<div className="LoginHandler">
<div className="notice">
<p>{error}</p>
</div>
</div>
);
}

return null;
};

export default LoginHandler;
4 changes: 4 additions & 0 deletions src/component/OAuth.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const CLIENT_ID = import.meta.env.VITE_REACT_APP_REST_API_KEY;
const REDIRECT_URI = import.meta.env.VITE_REACT_APP_REDIRECT_URL;

export const KAKAO_AUTH_URL = `https://kauth.kakao.com/oauth/authorize?client_id=${CLIENT_ID}&redirect_uri=${REDIRECT_URI}&response_type=code`;
12 changes: 8 additions & 4 deletions src/containers/LoginForm.jsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
// LoginForm.jsx

import { useNavigate } from "react-router-dom";
import Sidebar from "./SideForm";
import Button from "../component/Button";
import Input from "../component/Input";
import Logo_black from "../image/Logo_black.png";
import Logo_black from "../image/logo_black.png";
import "./styles/LoginForm.scss";
import { KAKAO_AUTH_URL } from "../component/OAuth";

const LoginForm = () => {
const navigate = useNavigate();
Expand All @@ -14,10 +13,14 @@ const LoginForm = () => {
navigate("/signup");
};

const handleKakaoLogin = () => {
window.location.href = KAKAO_AUTH_URL;
};

return (
<div className="start-container">
<div className="sidebar-area">
<Sidebar showLogout={false} /> {/* showLogout prop을 false로 설정 */}
<Sidebar showLogout={false} />
</div>
<div className="content-wrapper">
<div className="login-area">
Expand All @@ -30,6 +33,7 @@ const LoginForm = () => {
text="카카오로 로그인"
backgroundColor="#FEE500"
color="#3D3D3D"
onClick={handleKakaoLogin}
/>
<p className="no-account" onClick={handleSignup}>
아직 계정이 없나요?
Expand Down
107 changes: 107 additions & 0 deletions src/containers/LoginHandler.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import { useNavigate } from "react-router-dom";
import { useEffect, useState } from "react";
import axios from "axios";
import PropTypes from "prop-types";

const LoginHandler = () => {
const navigate = useNavigate();
const [state, setState] = useState({
isLoading: true,
error: null,
});

const code = new URL(window.location.href).searchParams.get("code");

useEffect(() => {
const kakaoLogin = async () => {
try {
const response = await fetchKakaoData(code);
handleLoginResponse(response.data);
} catch (err) {
handleError(err);
} finally {
setState((prev) => ({ ...prev, isLoading: false }));
}
};

if (code) {
kakaoLogin();
} else {
handleError(new Error("인가 코드를 찾을 수 없습니다."));
}
}, [code, navigate]);

const fetchKakaoData = async (code) => {
return await axios({
method: "GET",
url: `${import.meta.env.VITE_REACT_APP_SERVER_URL}/oauth2/callback/kakao?code=${code}`,
headers: {
"Content-Type": "application/json;charset=utf-8",
"Access-Control-Allow-Origin": "*",
},
});
};

const handleLoginResponse = (data) => {
console.log("Server response:", data);
if (data.isExistingUser) {
localStorage.setItem("name", data.account.nickname);
localStorage.setItem("token", data.token);
navigate("/mainpage");
} else {
localStorage.setItem("kakaoNickname", data.account.nickname);
if (data.account.profileImage) {
localStorage.setItem("kakaoProfileImage", data.account.profileImage);
}
navigate("/kakaosignup");
}
};

const handleError = (err) => {
console.error("Login error:", err);
setState((prev) => ({
...prev,
error:
err.response?.data?.message ||
err.message ||
"로그인 중 오류가 발생했습니다.",
isLoading: false,
}));
};

if (state.isLoading) {
return <LoadingView />;
}

if (state.error) {
return <ErrorView error={state.error} onRetry={() => navigate("/login")} />;
}

return null;
};

const LoadingView = () => (
<div className="LoginHandler">
<div className="notice">
<p>로그인 중입니다.</p>
<p>잠시만 기다려주세요.</p>
<div className="spinner"></div>
</div>
</div>
);

const ErrorView = ({ error, onRetry }) => (
<div className="LoginHandler">
<div className="notice">
<p>{error}</p>
<button onClick={onRetry}>로그인 페이지로 돌아가기</button>
</div>
</div>
);

ErrorView.propTypes = {
error: PropTypes.string.isRequired,
onRetry: PropTypes.func.isRequired,
};

export default LoginHandler;
Loading