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

context

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