Commit e8156733 authored by Choi Ga Young's avatar Choi Ga Young
Browse files

context, 로그인, 로그아웃 적용

parent 4c649483
...@@ -10,11 +10,13 @@ import StudyPlanPage from "./pages/StudyPlanPage"; ...@@ -10,11 +10,13 @@ import StudyPlanPage from "./pages/StudyPlanPage";
import StudyPlanEditPage from "./pages/StudyPlanEditPage"; import StudyPlanEditPage from "./pages/StudyPlanEditPage";
import SubjectEditPage from "./pages/SubjectEditPage"; import SubjectEditPage from "./pages/SubjectEditPage";
import AdminPage from "./pages/Admin/AdminPage"; import AdminPage from "./pages/Admin/AdminPage";
import { AuthProvider } from "./utils/context.js";
import PrivateRoute from "./components/PrivateRoute"; import PrivateRoute from "./components/PrivateRoute";
import ErrorPage from "./pages/ErrorPage"; import ErrorPage from "./pages/ErrorPage";
function App() { function App() {
return ( return (
<AuthProvider >
<Router basename={process.env.PUBLIC_URL}> <Router basename={process.env.PUBLIC_URL}>
<div id="box" className="container position-relative vh-100 mx-sm-auto"> <div id="box" className="container position-relative vh-100 mx-sm-auto">
<Switch> <Switch>
...@@ -38,6 +40,7 @@ function App() { ...@@ -38,6 +40,7 @@ function App() {
</Switch> </Switch>
</div> </div>
</Router> </Router>
</AuthProvider>
); );
} }
......
import axios from "axios"; import axios from "axios";
import baseUrl from "../utils/baseUrl.js"; import baseUrl from "../utils/baseUrl.js";
const getUser = async () => {
const url = `${baseUrl}/api/auth/user`
const { data } = await axios.get(url)
return data
}
const signup = async (user) => { const signup = async (user) => {
const url = `${baseUrl}/api/auth/signup`; const url = `${baseUrl}/api/auth/signup`;
const { data, status } = await axios.post(url, user); const { data } = await axios.post(url, user);
return { data, status } return data
} }
const login = async (user) => { const login = async (user) => {
const url = `${baseUrl}/api/auth/login`; const url = `${baseUrl}/api/auth/login`;
const { data, status } = await axios.post(url, user); const { data } = await axios.post(url, user);
return { data, status } return data
}
const logout = async () => {
const url = `${baseUrl}/api/auth/logout`;
const { data } = await axios.get(url);
return data
} }
const authApi = { const authApi = {
getUser,
signup, signup,
login login,
logout
}; };
export default authApi export default authApi
\ No newline at end of file
import { useState } from 'react'; import { useState } from 'react';
import { Redirect, Link } from "react-router-dom"; import { Redirect, Link } from "react-router-dom";
import { Formik } from 'formik'; import { Formik } from 'formik';
import { useAuth } from "../../utils/context.js";
import * as Yup from 'yup'; import * as Yup from 'yup';
import authApi from '../../apis/auth.api';
import catchErrors from "../../utils/catchErrors.js"; import catchErrors from "../../utils/catchErrors.js";
import styles from "./form.module.scss"; import styles from "./form.module.scss";
const LoginForm = () => { const LoginForm = () => {
const { login } = useAuth();
const [success, setSuccess] = useState(false); const [success, setSuccess] = useState(false);
const [error, setError] = useState(""); const [error, setError] = useState("");
...@@ -28,9 +29,10 @@ const LoginForm = () => { ...@@ -28,9 +29,10 @@ const LoginForm = () => {
})} })}
onSubmit={async (values, { setSubmitting, resetForm }) => { onSubmit={async (values, { setSubmitting, resetForm }) => {
try { try {
console.log('login values', values)
setError("") setError("")
const result = await authApi.login(values) const result = await login(values)
if (result.status === 201) { if (result) {
setSuccess(true) setSuccess(true)
} }
} catch (error) { } catch (error) {
......
import { Link, Redirect } from "react-router-dom"; import { Link, Redirect } from "react-router-dom";
import { useAuth } from "../../utils/context.js";
import moment from "moment"; import moment from "moment";
import styles from "./menu.module.scss"; import styles from "./menu.module.scss";
const Menu = () => { const Menu = () => {
const { logout } = useAuth();
return ( return (
<> <>
<button className="btn btn-crimson shadow-none mt-2" type="button" data-bs-toggle="collapse" data-bs-target="#menuContent" aria-controls="menuContent" aria-expanded="false" aria-label="menu"> <button className="btn btn-crimson shadow-none mt-2" type="button" data-bs-toggle="collapse" data-bs-target="#menuContent" aria-controls="menuContent" aria-expanded="false" aria-label="menu">
...@@ -39,7 +41,7 @@ const Menu = () => { ...@@ -39,7 +41,7 @@ const Menu = () => {
<Link className="text-dark text-decoration-none" to={`/schedule/${moment().format("YYYY-MM-DD")}`}><i className="bi bi-check"></i>일정</Link> <Link className="text-dark text-decoration-none" to={`/schedule/${moment().format("YYYY-MM-DD")}`}><i className="bi bi-check"></i>일정</Link>
<Link className="text-dark text-decoration-none" to="/studyplan"><i className="bi bi-check"></i>학업별 계획</Link> <Link className="text-dark text-decoration-none" to="/studyplan"><i className="bi bi-check"></i>학업별 계획</Link>
</div> </div>
<p className={`position-absolute bottom-0 text-dark ${styles.logout}`}>로그아웃</p> <p className={`position-absolute bottom-0 text-dark ${styles.logout}`} onClick={logout}>로그아웃</p>
</div> </div>
</div> </div>
</div> </div>
......
import { Redirect, Route } from "react-router-dom"; import { Redirect, Route } from "react-router-dom";
// import { useAuth } from "../context/auth_context"; import { useAuth } from "../utils/context.js"
import ErrorPage from "../pages/ErrorPage"; import ErrorPage from "../pages/ErrorPage";
const PrivateRoute = ({ component: Component, ...rest }) => { const PrivateRoute = ({ component: Component, ...rest }) => {
// const { user } = useAuth(); const { user } = useAuth();
// return ( // return (
// <Route // <Route
// {...rest} // {...rest}
......
import { createContext, useCallback, useContext, useEffect, useState } from 'react';
import { Redirect } from 'react-router-dom';
import authApi from "../apis/auth.api";
import catchErrors from './catchErrors';
const AuthContext = createContext({
error: "",
user: { id: "", role: "user", name: "" },
setUser: () => { },
login: () => Promise.resolve(false),
logout: () => { },
catchErrorAuth: (error, displayError) => { },
});
const AuthProvider = ({ children }) => {
const [error, setError] = useState("");
const [user, setUser] = useState({ id: "", role: "user", name: "" });
const getUser = async () => {
const { id, role, userName } = await authApi.getUser();
const user = { id: id, role: role, name: userName };
setUser(user);
}
useEffect(() => {
getUser();
}, []);
const login = useCallback(async (data) => {
try {
setError("");
const user = await authApi.login(data);
console.log('user in context', user)
setUser(user);
console.log('setUser 결과', user)
return true;
} catch (error) {
catchErrors(error, setError);
return false;
}
}, []);
const logout = useCallback(async () => {
try {
setError("");
const user = await authApi.logout();
setUser(user);
alert("로그아웃 되었습니다.");
} catch (error) {
catchErrors(error, setError);
}
}, []);
const catchErrorAuth = useCallback(async (error, displayError) => {
let errMsg;
if (error.response) {
if (typeof error.response.data === "string") {
errMsg = error.response.data;
console.log('Error response:', errMsg);
} else {
const { data } = error.response;
if (data.redirectUrl) {
errMsg = data.message;
console.log('Error response with redirected message:', errMsg);
return await logout();
}
}
} else if (error.request) {
errMsg = error.request;
console.log('Error request:', errMsg);
} else {
errMsg = error.message;
console.log("Error message:", errMsg)
}
displayError(errMsg);
}, []);
return (
<AuthContext.Provider value={{ error, user, setUser, login, logout, catchErrorAuth }} >
{children}
</AuthContext.Provider>
);
};
const useAuth = () => useContext(AuthContext);
export { AuthProvider, useAuth };
...@@ -2,6 +2,22 @@ import jwt from "jsonwebtoken"; ...@@ -2,6 +2,22 @@ import jwt from "jsonwebtoken";
import { User } from '../db/index.js'; import { User } from '../db/index.js';
import config from "../config/app.config.js"; import config from "../config/app.config.js";
const getUser = async (req, res) => {
try {
if (req.cookies.todayku) {
const token = req.cookies.todayku;
const { id, role, name } = jwt.verify(token, config.jwtSecret);
res.json({ id, role, name });
} else {
res.json({ id: "", role: "user", name: "" });
}
} catch (error) {
console.error(error);
return res.status(500).send("유저를 가져오지 못했습니다.");
}
}
const signup = async (req, res) => { const signup = async (req, res) => {
console.log('server/signup req.body', req.body) console.log('server/signup req.body', req.body)
const { userId, password, userName, userStudNum } = req.body; const { userId, password, userName, userStudNum } = req.body;
...@@ -15,7 +31,7 @@ const signup = async (req, res) => { ...@@ -15,7 +31,7 @@ const signup = async (req, res) => {
password: password, password: password,
userName: userName, userName: userName,
studNum: userStudNum, studNum: userStudNum,
role:"user" role: "user"
}); });
res.status(201).json("success") res.status(201).json("success")
} catch (error) { } catch (error) {
...@@ -38,7 +54,8 @@ const login = async (req, res) => { ...@@ -38,7 +54,8 @@ const login = async (req, res) => {
const signData = { const signData = {
id: user.userID, id: user.userID,
name: user.userName role: "user",
name: user.userName,
}; };
const token = jwt.sign(signData, config.jwtSecret, { const token = jwt.sign(signData, config.jwtSecret, {
...@@ -52,7 +69,7 @@ const login = async (req, res) => { ...@@ -52,7 +69,7 @@ const login = async (req, res) => {
secure: config.env === "production", secure: config.env === "production",
}); });
res.status(201).json(user) res.status(201).json(signData)
} else { } else {
res.status(401).send("비밀번호가 일치하지 않습니다.") res.status(401).send("비밀번호가 일치하지 않습니다.")
} }
...@@ -63,7 +80,23 @@ const login = async (req, res) => { ...@@ -63,7 +80,23 @@ const login = async (req, res) => {
} }
} }
const logout = async (req, res) => {
try {
res.clearCookie(config.cookieName);
res.json({
id:"",
role:"user",
name:""
})
} catch (error) {
console.log(error);
return res.status(500).send("로그아웃 에러발생")
}
}
export default { export default {
getUser,
signup, signup,
login login,
logout
} }
\ No newline at end of file
...@@ -11,4 +11,7 @@ router ...@@ -11,4 +11,7 @@ router
.route("/login") .route("/login")
.post(userCtrl.login) .post(userCtrl.login)
router
.route("/logout")
.get(userCtrl.logout )
export default router; export default router;
\ No newline at end of file
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