Skip to content

Commit

Permalink
feat(#8): 소셜로그인 (로그인 성공)
Browse files Browse the repository at this point in the history
  • Loading branch information
LeeSunghuck committed Nov 3, 2024
1 parent f6b983a commit 95e85a8
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 100 deletions.
12 changes: 1 addition & 11 deletions src/Router.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import Payment from "./pages/PaymentPage/Payment.jsx";
import PaymentEnd from "./pages/PaymentPage/PaymentEnd.jsx";
import CancelPay from "./pages/PaymentPage/CancelPay.jsx";
import PetEditPage from "./pages/MyPage/PetEditPage.jsx";

function Router() {
return (
<BrowserRouter>
Expand All @@ -40,34 +39,27 @@ function Router() {
path="shoppingDetail/:productId"
element={<ShoppingDetail />}
/>

<Route path="nanumList" element={<Outlet />}>
<Route index element={<NanumList />} />
<Route path="write" element={<NanumWrite />} />
<Route path="detail/:no" element={<NanumDetail />} />
</Route>

<Route path="userRegister/:userId" element={<UserRegisterPage />} />

<Route path="petRegister" element={<PetRegisterPage />} />

<Route path="walking" element={<WalkPage />} />

<Route path="myPage" element={<Outlet />}>
<Route index element={<MyPage />} />
<Route path="editPetRegister" element={<PetEditPage />} />
<Route path="editUserRegister" element={<UserEditPage />} />
<Route path="missingSave" element={<RegisterMissingSavePage />} />
<Route path="missingRegister" element={<RegisterMissing />} />

</Route>
</Route>
</Routes>
<Footer />
</BrowserRouter>
);
}

function NavSelector() {
const location = useLocation();
const path = location.pathname;
Expand All @@ -78,8 +70,6 @@ function NavSelector() {
"/myPage",
];
const isNavPath = navPaths.some((navPath) => path.startsWith(navPath));

return isNavPath ? <SideNav /> : <MainNav />;
}

export default Router;
export default Router;
104 changes: 26 additions & 78 deletions src/pages/LoginPage/LoginPage.jsx
Original file line number Diff line number Diff line change
@@ -1,110 +1,55 @@
import React, { useEffect } from 'react';
import styled from "styled-components";
import { images } from "../../components/Images";
import { useNavigate, useLocation } from 'react-router-dom';
import axios from 'axios';
import { useNavigate } from "react-router-dom";

const LoginPage = () => {
const navigate = useNavigate();
const location = useLocation();

useEffect(() => {
const queryParams = new URLSearchParams(location.search);
const jwtToken = queryParams.get('jwtToken');
const accessToken = queryParams.get('accessToken');
const refreshToken = queryParams.get('refreshToken');
const userId = queryParams.get('userId');

console.log('Received tokens from URL:', { jwtToken, accessToken, refreshToken });

if (jwtToken && accessToken && refreshToken) {
localStorage.setItem('jwtToken', jwtToken);
localStorage.setItem('accessToken', accessToken);
localStorage.setItem('refreshToken', refreshToken);
localStorage.setItem('userId',userId);
console.log('Tokens saved to localStorage:', { jwtToken, accessToken, refreshToken });

fetchUserId(jwtToken); // jwtToken을 fetchUserId 함수에 전달
} else {
console.log('Tokens not found in URL');
}
}, [location, navigate]);

const fetchUserId = async (jwtToken) => {
try {
const response = await axios.get('http://localhost:8080/api/users', {
headers: {
Authorization: `Bearer ${jwtToken}`
}
});

// 서버 응답 데이터 확인
console.log('Server response:', response.data);

// userId가 서버에서 제대로 전달됐는지 확인하고 로컬 스토리지에 저장
const userId = response.data.userId; // 서버 응답에서 userId 가져오기
if (userId) {
localStorage.setItem('userId', userId);
console.log('User ID saved to localStorage:', userId);
} else {
console.error('User ID is missing in server response');
}
} catch (error) {
console.error("Error fetching user ID:", error);
}
};

const handleKakaoLogin = () => {
const REST_API_KEY = import.meta.env.VITE_KAKAO_REST_API_KEY;
const REDIRECT_URI = 'http://localhost:8080/test';
window.location.href = `https://kauth.kakao.com/oauth/authorize?client_id=${REST_API_KEY}&redirect_uri=${REDIRECT_URI}&response_type=code`;
};

return (
<Container>
<Image src={images.loginDogCat} alt="로그인 화면 강아지와 고양이 그림" />
<Title>지금 가입하면 5천원 즉시 할인!</Title>
<Subtitle>우리 댕냥이 엄마쇼핑 시작해볼까요?</Subtitle>
<KakaoButton onClick={handleKakaoLogin}>카카오 계정으로 로그인</KakaoButton>
<OtherMethodButton>다른 방법으로 시작하기</OtherMethodButton>
<SkipButton onClick={() => navigate('/home')}>일단 둘러보기</SkipButton>
</Container>
);
const navigate = useNavigate(); // useNavigate 훅 사용



return (
<Container>
<Image src={images.loginDogCat} alt="로그인 화면 강아지와 고양이 그림" />
<Title>지금 가입하면 5천원 즉시 할인!</Title>
<Subtitle>우리 댕냥이 엄마쇼핑 시작해볼까요?</Subtitle>
<KakaoButton ><a href="http://localhost:8080/api/oauth2/authorization/kakao">카카오 계정으로 로그인</a></KakaoButton>
<OtherMethodButton>다른 방법으로 시작하기</OtherMethodButton>
<SkipButton onClick={() => navigate('/main')}>일단 둘러보기</SkipButton>
</Container>
);
};

export default LoginPage;

// 스타일링 코드

const Container = styled.div`
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
background-color: #ffffff;
padding: 20px;
padding: 20px;
`;

const Image = styled.img`
width: 150px;
height: auto;
margin-top: 30px;
margin-bottom: 20px;
margin-bottom: 20px;
`;

const Title = styled.h2`
font-size: 20px;
font-weight: bold;
margin-bottom: 8px;
margin-bottom: 8px;
color: #000000;
text-align: center;
`;

const Subtitle = styled.p`
font-size: 14px;
color: #666666;
margin-bottom: 30px;
margin-bottom: 30px;
text-align: center;
`;

Expand All @@ -115,6 +60,7 @@ const Button = styled.button`
border-radius: 30px;
font-size: 16px;
margin-bottom: 15px;
cursor: pointer;
transition: background-color 0.3s, transform 0.2s;
`;
Expand All @@ -125,7 +71,7 @@ const KakaoButton = styled(Button)`
&:hover {
background-color: #ffd600;
transform: scale(1.05); /* 살짝 커지는 효과 */
transform: scale(1.05);
}
`;

Expand All @@ -135,7 +81,7 @@ const OtherMethodButton = styled(Button)`
&:hover {
background-color: #e0e0e0;
transform: scale(1.05); /* 살짝 커지는 효과 */
transform: scale(1.05);
}
`;

Expand All @@ -144,6 +90,8 @@ const SkipButton = styled.p`
color: #888888;
cursor: pointer;
text-decoration: underline;
margin-top: 70px;
margin-bottom: 80px;
margin-top: 70px;
margin-bottom: 80px;
`;


4 changes: 2 additions & 2 deletions src/pages/RegisterPage/UserRegisterPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -396,7 +396,7 @@ const UserEditPage = () => {
}

try {
await axios.put(`http://localhost:8080/api/users/${storedUserId}`, {
await axios.post(`http://localhost:8080/api/user/Register`, {
nickname,
phoneNumber,
address,
Expand Down Expand Up @@ -526,7 +526,7 @@ const UserEditPage = () => {
</ThirdToggleContainer>
</SubContainer>
</Container>
<RegisterButton onClick={handleRegister}>저장하기</RegisterButton>
<RegisterButton onClick={handleRegister}>저장하기</RegisterButton>
</ScrollableContainer>
);
};
Expand Down
10 changes: 1 addition & 9 deletions vite.config.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,7 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react-swc';

// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
server: {
proxy: {
'/api': {
target: 'http://localhost:8080', // 백엔드 서버 주소
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''), // "/api" 제거 후 전달
},
},
},
});

0 comments on commit 95e85a8

Please sign in to comment.