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