Commit e617be58 authored by 한규민's avatar 한규민
Browse files

context

parent c10ff7b7
import React, { useState } from "react";
import styles from "./login.module.scss";
import { useState } from "react";
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변수를 갱신해주는 함수
......@@ -38,30 +40,17 @@ const Login = () => {
})
}
const handleOnSummitUser = async(e) => {
e.preventDefault();
try{
console.log("하하")
setError("");
setLoading(true);
const userData = login;
await authApi.login(userData);
alert('로그인이 완료되었습니다.')
setSuccess(true);
}catch(error){
catchErrors(error, setError);
}finally{
setLoading(false);
}
const requestServer = async (data) => {
await authApi.login(data);
}
const handleOnSummitGuest = async(e) => {
const handleOnSummit = async(e) => {
e.preventDefault();
try{
setError("");
setLoading(true);
const gusetData = guest;
await authApi.login(gusetData);
if(e.target.value === "Login"){ requestServer(login); }
else{ requestServer(guest); }
alert('로그인이 완료되었습니다.')
setSuccess(true);
}catch(error){
......@@ -71,8 +60,8 @@ const Login = () => {
}
}
if (success) {
store.setRole("member");
return <Redirect to="/" />;
}
......@@ -80,7 +69,6 @@ const Login = () => {
<div className={`d-flex flex-column col-md-5 col-10`}>
{/* nav-tabs */}
{/* {console.log(login)} */}
{console.log(success)}
<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"}}
......@@ -93,25 +81,23 @@ const Login = () => {
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={handleOnSummitUser}>
<form className="d-flex flex-column" 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="8" 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} />
<span><a href="./signup" className={styles.intoSignupPage}>회원이 아니십니까?</a></span>
</form>
</div>
{/* 비회원예매 학인 */}
<div className="tab-pane fade" id="guest" role="tabpanel" aria-labelledby="guest-tab">
<form className="d-flex flex-column" onSubmit={handleOnSummitGuest}>
<form className="d-flex flex-column" onSubmit={handleOnSummit}>
<input className={styles.input} type="text" name="guestName" id="guestName" placeholder="이름" onChange={handleGuestOnChange} maxLength="5" required />
<input className={styles.input} type="number" name="gusetBirthday" id="gusetBirthday" placeholder="생년월일" onChange={handleGuestOnChange} maxLength="6" required />
<input className={styles.input} type="number" name="gusetMbnum" id="gusetMbnum" placeholder="휴대폰 번호" onChange={handleGuestOnChange} maxLength="11" required />
<input className={styles.input} type="password" name="guestPassword" id="password" placeholder="비밀번호" onChange={handleGuestOnChange} maxLength="8" required />
<input className={styles.input} type="password" name="guestPassword" id="password" placeholder="비밀번호" onChange={handleGuestOnChange} maxLength="11" required />
<p className={`text-white ${styles.fontSizeTwo}`}>
비회원 정보 입력 예매 내역 확인/취소 티켓 발권이 어려울 있으니 다시 한번 확인해 주시기 바랍니다.
......
import React from "react";
import { AppContext } from "../../App";
const SubNav = () => {
return (
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="/login">로그인</a>
<a class="nav-link text-white" href="/signup">회원가입</a>
<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
const MyPage = () => {
return (
<div>
마이 페이지
</div>
)
}
......
......@@ -17,13 +17,12 @@ const login = async(req, res) => {
// 3) 비밀번호가 맞으면 토큰 생성
// const userRole = await user.getRole();
const signData = {
userId: user.id,
userId: user.userid,
// role: userRole.name,
};
const token = jwt.sign(signData, config.jwtSecret, {
expiresIn: config.jwtExpires,
});
console.log("token = ", token);
// 4) 토큰을 쿠키에 저장
res.cookie(config.cookieName, token, {
maxAge: config.cookieMaxAge,
......@@ -34,8 +33,7 @@ const login = async(req, res) => {
// 5) 사용자 반환
res.json({
userId: user.id,
isLoggedIn: true,
// role: userRole.name,
role: userRole.name,
// isMember: user.isMember,
});
} else {
......@@ -49,6 +47,14 @@ const login = async(req, res) => {
}
const logout = async(req, res) => {
try{
res.cookie()
}catch(error) {
console.error(error);
return res.status(500).send("로그인 에러");
}
const compareId = async (req, res) => {
const id = req.params.userId;
......
......@@ -21,8 +21,10 @@ sequelize
// const adminRole = await Role.findOne({ where: { name: "admin" } });
// await User.create({
// name: "admin",
// email: "admin@example.com",
// userId: "admin",
// nickname: "admin@example.com",
// birth: "990926",
// phoneNumber: "01086074580",
// password: "admin!",
// isMember: true,
// roleId: adminRole?.id,
......
......@@ -28,9 +28,9 @@ const UserModel = (sequelize) => {
password: {
type: DataTypes.STRING,
},
// roleId: {
// type: DataTypes.INTEGER
// }
roleId: {
type: DataTypes.INTEGER
}
},
{
timestamps: true,
......
......@@ -7,11 +7,14 @@ router
.route("/login")
.post(userCtrl.login)
router
.route("/logout")
.get(userCtrl.logout)
router
.route("/signup")
.post(userCtrl.signup)
router
.route("/:userId")
.get(userCtrl.compareId)
......
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