Skip to content

Commit

Permalink
Merge pull request #8 from SW-Palindrome/feature/google-oauth
Browse files Browse the repository at this point in the history
[STUD-10] 구글 로그인 기능 구현
  • Loading branch information
milkbottle0305 authored Feb 29, 2024
2 parents 54f32ef + 81db92f commit f350657
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 24 deletions.
10 changes: 2 additions & 8 deletions src/pages/Callback/Callback.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,11 @@ function Callback() {
const refreshToken = params.get("refresh_token");

if (accessToken) {
var currentDate = new Date();
var accessExpirationTime = new Date(currentDate.getTime() + 15 * 60000);
document.cookie = `studitAccessToken=${accessToken}; expires=${accessExpirationTime.toUTCString()}; path=/`;
localStorage.setItem("studitAccessToken", accessToken);
}

if (refreshToken) {
currentDate = new Date();
var refreshExpirationTime = new Date(
currentDate.getTime() + 7 * 24 * 60 * 60000,
);
document.cookie = `studitRefreshToken=${refreshToken}; expires=${refreshExpirationTime.toUTCString()}; path=/`;
localStorage.setItem("studitRefreshToken", refreshToken);
}
window.location.href = "http://localhost:3000/home";
};
Expand Down
12 changes: 6 additions & 6 deletions src/pages/PrivateRoute/PrivateRoute.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Navigate, Outlet } from "react-router-dom";
import { validateToken } from "../../services/api";

export default function PrivateRoute({ authentication }) {
/**
Expand All @@ -7,16 +8,15 @@ export default function PrivateRoute({ authentication }) {
* 로그인 안했을 경우 : null or false(로그아웃 버튼 눌렀을경우 false로 설정) 반환
*/

// studitAccessToken이 있으면 로그인 한 상태
const isAuthenticated = document.cookie
.split(";")
.some((item) => item.trim().startsWith("studitAccessToken="));
const isAuthenticated = validateToken(
localStorage.getItem("studitAccessToken"),
);

if (authentication) {
// 인증이 반드시 필요한 페이지

// 인증을 안했을 경우 로그인 페이지로, 했을 경우 해당 페이지로
return isAuthenticated === null || isAuthenticated === "false" ? (
return isAuthenticated === null || isAuthenticated === false ? (
<Navigate to="/" />
) : (
<Outlet />
Expand All @@ -25,7 +25,7 @@ export default function PrivateRoute({ authentication }) {
// 인증이 반드시 필요 없는 페이지

// 인증을 안햇을 경우 해당 페이지로 인증을 한 상태일 경우 main페이지로
return isAuthenticated === null || isAuthenticated === "false" ? (
return isAuthenticated === null || isAuthenticated === false ? (
<Outlet />
) : (
<Navigate to="/home" />
Expand Down
21 changes: 12 additions & 9 deletions src/pages/Splash/components/Header.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { Link } from "react-router-dom";
import styled from "styled-components";
import { useEffect } from "react";
import { validateToken } from "../../../services/api";

const StyledHeader = styled.header`
display: flex;
Expand Down Expand Up @@ -36,22 +38,23 @@ const StyledButton = styled.button`

function Header({ setSigninClicked, setSignupClicked }) {
function logout() {
document.cookie =
"studitAccessToken=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
document.cookie =
"studitRefreshToken=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
localStorage.removeItem("studitAccessToken");
localStorage.removeItem("studitRefreshToken");
window.location.href = "/";
}

const isLoggedIn = document.cookie.includes("studitAccessToken");
let isAuthenticated = false;
// 컴포넌트가 렌더링 될 때마다 토큰이 유효한지 확인
useEffect(() => {
isAuthenticated = validateToken(localStorage.getItem("studitAccessToken"));
}, []);

return (
<StyledHeader>
<Link to="/home">
<StyledLogo src={require("../../../assets/logo.png")} alt="logo" />
</Link>
<StyledButtonRow>
{!isLoggedIn && (
{!isAuthenticated && (
<StyledButton
className="signin-btn"
marginRight={true}
Expand All @@ -60,15 +63,15 @@ function Header({ setSigninClicked, setSignupClicked }) {
Sign In
</StyledButton>
)}
{!isLoggedIn && (
{!isAuthenticated && (
<StyledButton
className="signup-btn"
onClick={() => setSignupClicked(true)}
>
Sign Up
</StyledButton>
)}
{isLoggedIn && (
{isAuthenticated && (
<StyledButton className="logout-btn" onClick={() => logout()}>
Log Out
</StyledButton>
Expand Down
12 changes: 11 additions & 1 deletion src/pages/Splash/components/Modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,11 @@ const StyledBottomButton = styled.button`
`;

function Modal({ setSigninClicked, setSignupClicked, isSignin }) {
function requestGoogleLogin() {
window.location.href =
"http://13.124.72.126:8080/oauth2/authorization/google?redirect_uri=http://localhost:3000/callback";
}

function requestGithubLogin() {
window.location.href =
"http://13.124.72.126:8080/oauth2/authorization/github?redirect_uri=http://localhost:3000/callback";
Expand All @@ -103,7 +108,12 @@ function Modal({ setSigninClicked, setSignupClicked, isSignin }) {
<StyledModalTitle>
{isSignin ? "로그인" : "회원가입"}
</StyledModalTitle>
<StyledActionButton src={require("../../../assets/google.png")} />
<StyledActionButton
src={require("../../../assets/google.png")}
onClick={function () {
requestGoogleLogin();
}}
/>
<StyledActionButton
src={require("../../../assets/github.png")}
onClick={function () {
Expand Down
23 changes: 23 additions & 0 deletions src/services/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const BASE_URL = "http://13.124.72.126:8080";

export const validateToken = async (token) => {
try {
const response = await fetch(`${BASE_URL}/auth/token-info/${token}`);

if (!response.ok) {
// 상태 코드가 200 OK가 아니면 오류 발생
throw new Error("Failed to validate token");
}

const data = await response.json();

if (data.sub !== null && !isNaN(data.sub)) {
return true; // 토큰이 유효한 경우
} else {
return false; // 토큰이 유효하지 않은 경우
}
} catch (error) {
console.error("Error validating token:", error);
throw error; // 오류 처리
}
};

0 comments on commit f350657

Please sign in to comment.