Commit 6aa99cb4 authored by 한규민's avatar 한규민
Browse files

push

parent e617be58
import React, { useState, useEffect } from "react";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import { AuthProvider } from "./context/auth_context";
import Header from "./components/Header"; import Header from "./components/Header";
import SubNav from "./components/Navs/SubNav"; import SubNav from "./components/Navs/SubNav";
import MainNav from "./components/Navs/MainNav"; import MainNav from "./components/Navs/MainNav";
...@@ -14,15 +14,11 @@ import AdminPage from "./pages/AdminPage/AdminPage"; ...@@ -14,15 +14,11 @@ import AdminPage from "./pages/AdminPage/AdminPage";
import TicketingPage from "./pages/TicketingPage"; import TicketingPage from "./pages/TicketingPage";
import SearchPage from "./pages/SearchPage"; import SearchPage from "./pages/SearchPage";
const AppContext = React.createContext();
function App() { function App() {
const [role, setRole] = useState("user");
const store = {role, setRole};
return ( return (
<div className="" style={{ backgroundColor: "black" }}> <div className="" style={{ backgroundColor: "black" }}>
<AppContext.Provider value={store}> <AuthProvider>
<Router style={{ backgroundColor: "black" }}> <Router style={{ backgroundColor: "black" }}>
<SubNav /> <SubNav />
<Header /> <Header />
...@@ -38,10 +34,9 @@ function App() { ...@@ -38,10 +34,9 @@ function App() {
<Route path="/admin" component={AdminPage} /> <Route path="/admin" component={AdminPage} />
</Switch> </Switch>
</Router> </Router>
</AppContext.Provider> </AuthProvider>
</div> </div>
); );
} }
export { AppContext }
export default App; export default App;
...@@ -3,40 +3,40 @@ import styles from "./login.module.scss"; ...@@ -3,40 +3,40 @@ import styles from "./login.module.scss";
import authApi from "../../apis/auth.api.js"; import authApi from "../../apis/auth.api.js";
import { Redirect } from "react-router"; import { Redirect } from "react-router";
import catchErrors from "../../utils/catchErrors"; import catchErrors from "../../utils/catchErrors";
import {AppContext} from "../../App";
const Login = () => { const Login = () => {
const store = React.useContext(AppContext);
//useState를 이용해서 각 state 생성 및 초기값 저장 //useState를 이용해서 각 state 생성 및 초기값 저장
const [state, setState] = useState(true); // 이 줄은 css에 해당하는 state const [state, setState] = useState(true); // 이 줄은 css에 해당하는 state
//state변수 지정 하지만 이 변수는 react에 의해 없어지지 않음, 그리고 그 다음 변수는 state변수를 갱신해주는 함수 //state변수 지정 하지만 이 변수는 react에 의해 없어지지 않음, 그리고 그 다음 변수는 state변수를 갱신해주는 함수
const [login, setLogin] = useState({ const [login, setLogin] = useState({
id:'', id: '',
password:'' password: ''
}); });
const [error, setError] = useState(""); const [error, setError] = useState("");
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [success, setSuccess] = useState(false); const [success, setSuccess] = useState(false);
const [guest, setGuset] = useState({ const [guest, setGuset] = useState({
guestName:'', guestName: '',
gusetBirthday:'', gusetBirthday: '',
gusetMbnum:'', gusetMbnum: '',
guestPassword:'' guestPassword: ''
}) })
//input태그에 걸려있는 onchange에서 실행할 함수설정 //input태그에 걸려있는 onchange에서 실행할 함수설정
const handleLoginOnChange = (e) =>{ const handleLoginOnChange = (e) => {
// ... 전개 연산자 // ... 전개 연산자
// 현재 state에 방금 변화한 값을 다시 저장함 // 현재 state에 방금 변화한 값을 다시 저장함
setLogin({ ...login, setLogin({
[e.target.name]:e.target.value ...login,
[e.target.name]: e.target.value
}) })
}; };
const handleGuestOnChange = (e) =>{ const handleGuestOnChange = (e) => {
setGuset({ ...guest, setGuset({
[e.target.name]:e.target.value ...guest,
[e.target.name]: e.target.value
}) })
} }
...@@ -44,24 +44,29 @@ const Login = () => { ...@@ -44,24 +44,29 @@ const Login = () => {
await authApi.login(data); await authApi.login(data);
} }
const handleOnSummit = async(e) => { const handleOnSummit = async (e) => {
e.preventDefault(); e.preventDefault();
try{ try {
setError(""); setError("");
setLoading(true); setLoading(true);
if(e.target.value === "Login"){ requestServer(login); } console.log(e.target.name);
else{ requestServer(guest); } if (e.target.name === "login") {
requestServer(login);
alert('로그인이 완료되었습니다.') alert('로그인이 완료되었습니다.')
setSuccess(true); setSuccess(true);
}catch(error){ }
else {
requestServer(guest);
alert('로그인이 완료되었습니다.')
}
} catch (error) {
catchErrors(error, setError); catchErrors(error, setError);
}finally{ } finally {
setLoading(false); setLoading(false);
} }
} }
if (success) { if (success) {
store.setRole("member");
return <Redirect to="/" />; return <Redirect to="/" />;
} }
...@@ -71,7 +76,7 @@ const Login = () => { ...@@ -71,7 +76,7 @@ const Login = () => {
{/* {console.log(login)} */} {/* {console.log(login)} */}
<ul className="nav nav-fill nav-tabs w-100" id="loginTab" role="tablist"> <ul className="nav nav-fill nav-tabs w-100" id="loginTab" role="tablist">
<li className="nav-item fs-6" role="presentation"> <li className="nav-item fs-6" role="presentation">
<button className={`nav-link active px-2 ${styles.fontSize}`} style={{ color: state ? "black" : "#FEDC00", backgroundColor: state ? "#FEDC00" : "black"}} <button className={`nav-link active px-2 ${styles.fontSize}`} style={{ color: state ? "black" : "#FEDC00", backgroundColor: state ? "#FEDC00" : "black" }}
id="login-tab" data-bs-toggle="tab" data-bs-target="#login" type="button" role="tab" aria-controls="login" aria-selected="true" id="login-tab" data-bs-toggle="tab" data-bs-target="#login" type="button" role="tab" aria-controls="login" aria-selected="true"
onClick={() => setState(true)}>로그인</button> onClick={() => setState(true)}>로그인</button>
</li> </li>
...@@ -84,8 +89,8 @@ const Login = () => { ...@@ -84,8 +89,8 @@ const Login = () => {
<div className="tab-content w-100" id="myTabContent"> <div className="tab-content w-100" id="myTabContent">
{/* 로그인 */} {/* 로그인 */}
<div className="tab-pane fade show active" id="login" role="tabpanel" aria-labelledby="login-tab"> <div className="tab-pane fade show active" id="login" role="tabpanel" aria-labelledby="login-tab">
<form className="d-flex flex-column" onSubmit={handleOnSummit}> <form className="d-flex flex-column" name="login" onSubmit={handleOnSummit}>
<input className={styles.input} type="text" name="id" placeholder="ID" onChange={handleLoginOnChange} maxLength="10" required/> <input className={styles.input} type="text" name="id" placeholder="ID" onChange={handleLoginOnChange} maxLength="10" required />
<input className={styles.input} type="password" name="password" placeholder="Password" onChange={handleLoginOnChange} maxLength="11" required /> <input className={styles.input} type="password" name="password" placeholder="Password" onChange={handleLoginOnChange} maxLength="11" required />
<input className={`rounded-2 mt-2 ${styles.butterYellowAndBtn} ${styles.btnHover}`} type="submit" value="Login" disabled={loading} /> <input className={`rounded-2 mt-2 ${styles.butterYellowAndBtn} ${styles.btnHover}`} type="submit" value="Login" disabled={loading} />
<span><a href="./signup" className={styles.intoSignupPage}>회원이 아니십니까?</a></span> <span><a href="./signup" className={styles.intoSignupPage}>회원이 아니십니까?</a></span>
...@@ -102,7 +107,7 @@ const Login = () => { ...@@ -102,7 +107,7 @@ const Login = () => {
<p className={`text-white ${styles.fontSizeTwo}`}> <p className={`text-white ${styles.fontSizeTwo}`}>
비회원 정보 입력 예매 내역 확인/취소 티켓 발권이 어려울 있으니 다시 한번 확인해 주시기 바랍니다. 비회원 정보 입력 예매 내역 확인/취소 티켓 발권이 어려울 있으니 다시 한번 확인해 주시기 바랍니다.
</p> </p>
<input className={`rounded-2 mt-2 ${styles.butterYellowAndBtn} ${styles.btnHover}`} type="submit" value="비회원 예매 확인" disabled={loading}/> <input className={`rounded-2 mt-2 ${styles.butterYellowAndBtn} ${styles.btnHover}`} type="submit" value="비회원 예매 확인" disabled={loading} />
</form> </form>
</div> </div>
</div> </div>
......
import React from "react";
import { AppContext } from "../../App";
const SubNav = () => { const SubNav = () => {
const store = React.useContext(AppContext);
useEffect(() => {
window.localStorage.setItem("user", JSON.stringify(store.role));
}, [store]);
const handleOnClick = () => { const handleOnClick = () => {
store.setRole("user");
await authApi.logout();
} }
if (store.role === "user") {
return ( return (
<nav class="nav justify-content-end py-1"> <nav class="nav justify-content-end py-1">
<a class="nav-link text-white" href="/login">로그인</a> <a class="nav-link text-white" href="/login">로그인</a>
<a class="nav-link text-white" href="/signup">회원가입</a> <a class="nav-link text-white" href="/signup">회원가입</a>
</nav> </nav>
) )
} else if (store.role === "member") {
return (
<nav class="nav justify-content-end py-1">
<a class="nav-link text-white" href="/">마이페이지</a>
<a class="nav-link text-white" onClick={handleOnClick}>로그아웃</a>
</nav>
)
} else if (store.role === "admin") {
<nav class="nav justify-content-end py-1">
<a class="nav-link text-white" href="/admin">관리자페이지</a>
<a class="nav-link text-white" href="/">로그아웃</a>
</nav>
} else {
<nav class="nav justify-content-end py-1">
<a class="nav-link text-white" href="/">로그인 오류</a>
</nav>
}
} }
// else if (store.role === "member") {
// return (
// <nav class="nav justify-content-end py-1">
// <a class="nav-link text-white" href="/">마이페이지</a>
// <a class="nav-link text-white" onClick={handleOnClick}>로그아웃</a>
// </nav>
// )
// } else if (store.role === "admin") {
// <nav class="nav justify-content-end py-1">
// <a class="nav-link text-white" href="/admin">관리자페이지</a>
// <a class="nav-link text-white" href="/">로그아웃</a>
// </nav>
// } else {
// <nav class="nav justify-content-end py-1">
// <a class="nav-link text-white" href="/">로그인 오류</a>
// </nav>
// }
export default SubNav export default SubNav
\ No newline at end of file
import axios from "axios";
import { createContext, useCallback, useContext, useState } from "react";
import authApi from "../apis/auth.api";
import { getLocalUser } from "../utils/auth";
import {baseUrl} from "../utils/baseUrl";
import catchErrors from "../utils/catchErrors";
import config from "../utils/clientConfig";
const AuthContext = createContext({
error: "",
loading: false,
user: null,
setUser: () => { },
login: () => Promise.resolve(false),
logout: () => { },
catchErrorAuth: (error, displayError) => { },
});
const AuthProvider = ({ children }) => {
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
const [user, setUser] = useState(getLocalUser());
const login = useCallback(async (email, password) => {
try {
setError("");
setLoading(true);
const user = await authApi.login(email, password);
localStorage.setItem(config.loginUser, JSON.stringify(user));
setUser(user);
return true;
} catch (error) {
catchErrors(error, setError);
return false;
} finally {
setLoading(false);
}
}, []);
const logout = useCallback(async () => {
try {
setError("");
setUser(null);
alert("로그아웃되었습니다.");
localStorage.removeItem(config.loginUser);
setLoading(true);
await axios.get(`${baseUrl}/api/auth/logout`);
} catch (error) {
catchErrors(error, setError);
} finally {
setLoading(false);
}
}, []);
const catchErrorAuth = useCallback(async (error, displayError) => {
let errorMsg;
if (error.response) {
if (typeof error.response.data === "string") {
errorMsg = error.response.data;
console.log("Error response:", errorMsg);
} else {
const { data } = error.response;
if (data.redirectUrl) {
errorMsg = data.message;
console.log("Error response with redirected message:", errorMsg);
console.log("redirect url", data.redirectUrl);
return await logout();
}
}
} else if (error.request) {
errorMsg = error.request;
console.log("Error request:", errorMsg);
} else {
errorMsg = error.message;
console.log("Error message:", errorMsg);
}
displayError(errorMsg);
}, []);
return (
<AuthContext.Provider
value={{ error, loading, user, setUser, login, logout, catchErrorAuth }}
>
{children}
</AuthContext.Provider>
);
};
const useAuth = () => useContext(AuthContext);
export { AuthProvider, useAuth };
\ No newline at end of file
import config from "./clientConfig";
export function handleLogin(user) {
if (user) {
localStorage.setItem(config.loginUser, JSON.stringify(user));
}
}
export function getLocalUser() {
const userData = localStorage.getItem(config.loginUser);
let user = null;
if (userData) {
user = JSON.parse(userData);
}
return user;
}
\ No newline at end of file
...@@ -7,7 +7,7 @@ const login = async(req, res) => { ...@@ -7,7 +7,7 @@ const login = async(req, res) => {
const { id, password } = req.body; const { id, password } = req.body;
//사용자 존재 확인 //사용자 존재 확인
const user = await User.scope("withPassword").findOne({ where: { userId: id } }); const user = await User.scope("withPassword").findOne({ where: { userId: id } });
console.log("user : ", user);
if (!user) { if (!user) {
return res.status(422).send(`사용자가 존재하지 않습니다`); return res.status(422).send(`사용자가 존재하지 않습니다`);
} }
...@@ -15,10 +15,11 @@ const login = async(req, res) => { ...@@ -15,10 +15,11 @@ const login = async(req, res) => {
const passwordMatch = await user.comparePassword(password); const passwordMatch = await user.comparePassword(password);
if (passwordMatch) { if (passwordMatch) {
// 3) 비밀번호가 맞으면 토큰 생성 // 3) 비밀번호가 맞으면 토큰 생성
// const userRole = await user.getRole(); const userRole = await user.getRole();
console.log("userRole : ", userRole);
const signData = { const signData = {
userId: user.userid, userId: user.userid,
// role: userRole.name, role: userRole.name,
}; };
const token = jwt.sign(signData, config.jwtSecret, { const token = jwt.sign(signData, config.jwtSecret, {
expiresIn: config.jwtExpires, expiresIn: config.jwtExpires,
...@@ -34,7 +35,6 @@ const login = async(req, res) => { ...@@ -34,7 +35,6 @@ const login = async(req, res) => {
res.json({ res.json({
userId: user.id, userId: user.id,
role: userRole.name, role: userRole.name,
// isMember: user.isMember,
}); });
} else { } else {
// 6) 비밀번호 불일치 // 6) 비밀번호 불일치
...@@ -53,7 +53,7 @@ const logout = async(req, res) => { ...@@ -53,7 +53,7 @@ const logout = async(req, res) => {
}catch(error) { }catch(error) {
console.error(error); console.error(error);
return res.status(500).send("로그인 에러"); return res.status(500).send("로그인 에러");
} } }
const compareId = async (req, res) => { const compareId = async (req, res) => {
...@@ -94,6 +94,7 @@ const signup = async (req, res) => { ...@@ -94,6 +94,7 @@ const signup = async (req, res) => {
export default { export default {
login, login,
logout,
compareId, compareId,
signup signup
} }
...@@ -28,9 +28,6 @@ const UserModel = (sequelize) => { ...@@ -28,9 +28,6 @@ const UserModel = (sequelize) => {
password: { password: {
type: DataTypes.STRING, type: DataTypes.STRING,
}, },
roleId: {
type: DataTypes.INTEGER
}
}, },
{ {
timestamps: true, timestamps: true,
......
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