Skip to content

Commit

Permalink
Merge pull request #61 from ii-sol/feature/7-login,signup
Browse files Browse the repository at this point in the history
feat: 로그인 완료
  • Loading branch information
jiminpark23 authored Jun 21, 2024
2 parents 37e8067 + f6ecf38 commit 1eef7b9
Show file tree
Hide file tree
Showing 7 changed files with 50 additions and 33 deletions.
13 changes: 10 additions & 3 deletions src/pages/Auth/Login.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import React, { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { styled } from "styled-components";
import { login } from "../../services/user";
import { store } from "../../store/stores";
import { loginSuccess } from "../../store/reducers/Auth/user";
import tw from "twin.macro";

import Button from "../../components/common/Button";
Expand All @@ -17,11 +19,16 @@ const Login = () => {
const phoneNum = userData.phoneNum;
const accountInfo = userData.accountInfo;
try {
const userInfo = await login(phoneNum, accountInfo);
console.log("로그인 성공:", userInfo);
const { userInfo, accessToken, refreshToken } = await login(phoneNum, accountInfo);
store.dispatch(
loginSuccess({
userInfo: userInfo,
accessToken: accessToken,
refreshToken: refreshToken,
})
);
navigate("/");
} catch (error) {
console.error("로그인 실패:", error);
alert(error);
}
};
Expand Down
5 changes: 4 additions & 1 deletion src/pages/Loan/Child/Main.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import LoanCard from "../../../components/Loan/LoanCard";
import RequestCard from "../../../components/Loan/RequestCard.jsx";
import Header from "../../../components/common/Header.jsx";
import { styled } from "styled-components";
import { BASE_URL, baseInstance } from "../../../services/api.jsx";

const Main = () => {
const navigate = useNavigate();
Expand All @@ -18,9 +19,11 @@ const Main = () => {
const [loans, setLoans] = useState([]);

useEffect(() => {
const baseUrl = "/loan";

const fetchLoans = async () => {
try {
const response = await axios.get("http://localhost:8082/loan");
const response = await baseInstance.get(baseUrl);
setLoans(response.data.response || []); // response.data.response 사용
} catch (error) {
console.error("Failed to fetch loans", error);
Expand Down
30 changes: 20 additions & 10 deletions src/services/api.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import axios from "axios";
import { getCookie, setCookie, removeCookie } from "./cookie";
import { store } from "../store/stores";
import { loginSuccess, logout } from "../store/reducers/Auth/user";

export const BASE_URL = "http://127.0.0.1:8080";

Expand Down Expand Up @@ -35,35 +37,43 @@ baseInstance.interceptors.request.use(
baseInstance.interceptors.response.use(
(response) => response,
async (error) => {
console.log(error);
const statusCode = error.response?.status;
if (statusCode === 401) {
if (statusCode == 401) {
console.log("dfsg");
try {
const refreshToken = getCookie("refreshToken");
if (!refreshToken) {
removeCookie("accessToken");
store.dispatch(logout());
return Promise.reject(error);
}
const refreshResponse = await axios.post(`${process.env.REACT_APP_HOST}/api/auth/token`, null, {
params: {
accountId: "1",
token: refreshToken,
},
const refreshResponse = await axios.post(`${BASE_URL}/auth/token`, null, {
headers: {
Authorization: `Bearer ${refreshToken}`,
"Refresh-Token": `${refreshToken}`,
},
});

const newAccessToken = refreshResponse.data.result.accessToken;
console.log("refreshResponse", refreshResponse);
const newAccessToken = refreshResponse.headers.authorization;
setCookie("accessToken", newAccessToken, {
path: "/",
});

error.config.headers.Authorization = `Bearer ${newAccessToken}`;
store.dispatch(
loginSuccess({
userInfo: store.getState().user.userInfo,
accessToken: newAccessToken,
refreshToken: refreshToken,
})
);

error.config.headers.Authorization = newAccessToken;

return axios(error.config);
} catch (err) {
removeCookie("accessToken");
removeCookie("refreshToken");
store.dispatch(logout());
return Promise.reject(err);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/services/user.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const login = async (phoneNum, accountInfo) => {
setCookie("accessToken", accessToken, { path: "/" });
setCookie("refreshToken", refreshToken, { path: "/" });

return userInfo;
return { userInfo, accessToken, refreshToken };
} catch (error) {
throw error;
}
Expand Down
2 changes: 1 addition & 1 deletion src/store/reducers/Auth/user.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { createSlice } from "@reduxjs/toolkit";

const initialState = {
isLoggedIn: false,
userInfo: null,
userInfo: { sn: "1", familyInfo: [] },
accessToken: null,
refreshToken: null,
};
Expand Down
15 changes: 4 additions & 11 deletions src/store/stores.jsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,18 @@
import { combineReducers, configureStore } from "@reduxjs/toolkit";
import storage from "redux-persist/lib/storage";
import {
FLUSH,
PAUSE,
PERSIST,
PURGE,
REGISTER,
REHYDRATE,
persistReducer,
persistStore,
} from "redux-persist";
import { FLUSH, PAUSE, PERSIST, PURGE, REGISTER, REHYDRATE, persistReducer, persistStore } from "redux-persist";
import logger from "redux-logger";
import loanReducer from "./reducers/Loan/loan";
import historyReducer from "./reducers/common/history";
import investReducer from "./reducers/Invest/invest";
import missionReducer from "./reducers/Mission/mission";
import notiReducer from "./reducers/Noti/notification";
import userReducer from "./reducers/Auth/user";

const rootPersistConfig = {
key: "root",
storage: storage,
whitelist: ["invest"],
whitelist: ["invest", "user"],
};

const rootReducer = combineReducers({
Expand All @@ -29,6 +21,7 @@ const rootReducer = combineReducers({
mission: missionReducer,
loan: loanReducer,
noti: notiReducer,
user: userReducer,
});

const persistedReducer = persistReducer(rootPersistConfig, rootReducer);
Expand Down
16 changes: 10 additions & 6 deletions src/utils/FetchSSE.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,28 @@ import React, { useEffect, useRef, useState } from "react";
import { EventSourcePolyfill, NativeEventSource } from "event-source-polyfill";
import "react-toastify/dist/ReactToastify.css";
import { StyledToastContainer, Toast } from "./Toast";
import isLogin from "./isLogin";
// import isLogin from "./isLogin";
import { getCookie } from "../services/cookie";
import { useSelector } from "react-redux";

const FetchSSE = () => {
// const sn = useSelector((state) => state.user.userInfo.sn);
const isLoggedIn = useSelector((state) => state.user.isLoggedIn);
// console.log("ssss", sn);
const accessToken = getCookie("accessToken");
const [realtimeData, setRealtimeData] = useState(null);

const eventSource = useRef(null);
const EventSource = EventSourcePolyfill || NativeEventSource;

useEffect(() => {
if (isLogin()) {
if (isLoggedIn) {
try {
const fetchSSE = async () => {
eventSource.current = new EventSource("http://127.0.0.1:8080/notifications/subscribe/1", {
eventSource.current = new EventSource(`http://127.0.0.1:8080/notifications/subscribe/${sn}`, {
headers: {
"Content-Type": "text/event-stream",
"Authorization": `Bearer ${accessToken}`,
// "Authorization": `Bearer ${accessToken}`,
},
withCredentials: true,
});
Expand All @@ -38,7 +42,7 @@ const FetchSSE = () => {
console.log("Connection opened", event);
};
};
fetchSSE();
// fetchSSE();
} catch (error) {
throw error;
}
Expand All @@ -47,7 +51,7 @@ const FetchSSE = () => {
return () => {
eventSource.current?.close();
};
}, [isLogin]);
}, [isLoggedIn]);

console.log(realtimeData);
return <StyledToastContainer />;
Expand Down

0 comments on commit 1eef7b9

Please sign in to comment.