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

회원가입, 로그인

서버연동 완료
parent 598bf2fc
...@@ -61,7 +61,7 @@ const Login = () => { ...@@ -61,7 +61,7 @@ const Login = () => {
setError(""); setError("");
setLoading(true); setLoading(true);
const gusetData = guest; const gusetData = guest;
await authApi.post(gusetData); await authApi.login(gusetData);
alert('로그인이 완료되었습니다.') alert('로그인이 완료되었습니다.')
setSuccess(true); setSuccess(true);
}catch(error){ }catch(error){
......
...@@ -41,7 +41,8 @@ const Signup = () => { ...@@ -41,7 +41,8 @@ const Signup = () => {
//id(중복확인 체크, 형식 에러) //id(중복확인 체크, 형식 에러)
const handleOnClickId = async (e) => { const handleOnClickId = async (e) => {
e.preventDefault(); e.preventDefault();
// const existId = await authApi.compareId(user.userId) try{
setError("");
if (user.userId.length < 5) { if (user.userId.length < 5) {
setErrorMsg(errorMsg => ({ setErrorMsg(errorMsg => ({
...errorMsg, ...errorMsg,
...@@ -51,21 +52,35 @@ const Signup = () => { ...@@ -51,21 +52,35 @@ const Signup = () => {
setOverlapId(() => (false)); setOverlapId(() => (false));
}; };
} else { } else {
const userId = user.userId;
await authApi.compareId(userId);
if(!await authApi.compareId(userId)){
alert("이 아이디는 사용가능합니다.")
setErrorMsg(errorMsg => ({ setErrorMsg(errorMsg => ({
...errorMsg, ...errorMsg,
[e.target.name]: false [e.target.name]: false
})); }));
setOverlapId(() => (true)); setOverlapId(()=>(true));
alert("이 아이디는 사용가능합니다.") }else{
alert("이미 사용중인 아이디입니다.")
setOverlapId(()=>(false));
}
} }
}catch(error){
catchErrors(error,setError)
}finally {
setLoading(false);
}
} }
const handleOnSummit = async (e) => { const handleOnSummit = async (e) => {
e.preventDefault(); e.preventDefault();
try { try {
setError(""); setError(()=>(""));
//처리가 될때까지 버튼(가입하기)이 안눌리게 지정 //처리가 될때까지 버튼(가입하기)이 안눌리게 지정
setLoading(true); setLoading(()=>(true));
//유효성 검사 //유효성 검사
validation(); validation();
const userData = user; const userData = user;
...@@ -91,14 +106,13 @@ const Signup = () => { ...@@ -91,14 +106,13 @@ const Signup = () => {
} }
//유효성 검사 //유효성 검사
const validation = () => { const validation = () => {
setPreId(()=> (user.userId)); setPreId(user.userId);
//아이디 유효성 검사 //아이디 유효성 검사
if ((user.userId.length < 5)) { if ((user.userId.length < 5)) {
setErrorMsg(errorMsg => ({ ...errorMsg, errorId: true })); setErrorMsg(errorMsg => ({ ...errorMsg, errorId: true }));
} else if((user.userId.length >= 5) && (overlapId === true)){ } else if((user.userId.length >= 5) && (overlapId === true)){
if(preId !== user.userId){ if(preId !== user.userId){
console.log(preId); setOverlapId(false);
setOverlapId(()=> (false));
} }
} }
else if(user.userId >= 5){ else if(user.userId >= 5){
...@@ -118,6 +132,8 @@ const Signup = () => { ...@@ -118,6 +132,8 @@ const Signup = () => {
// 최종 유효성 검사 // 최종 유효성 검사
if (overlapId && (Object.values(errorMsg).some((element) => (element)) === false)) { if (overlapId && (Object.values(errorMsg).some((element) => (element)) === false)) {
}else if(!overlapId && (Object.values(errorMsg).some((element) => (element)) === false)){
throw new Error("먼저 아이디 중복확인을 해주세요")
}else{ }else{
throw new Error("유효하지 않은 데이터입니다."); throw new Error("유효하지 않은 데이터입니다.");
} }
...@@ -131,7 +147,6 @@ const Signup = () => { ...@@ -131,7 +147,6 @@ const Signup = () => {
return ( return (
// 데이터 입력과 유효성 검사 후 보이는 경고창 // 데이터 입력과 유효성 검사 후 보이는 경고창
<form className={`d-flex col-md-6 col-12 justify-content-center`} onSubmit={handleOnSummit}> <form className={`d-flex col-md-6 col-12 justify-content-center`} onSubmit={handleOnSummit}>
{console.log("user==", user, errorMsg, overlapId)}
<div className="d-flex flex-column"> <div className="d-flex flex-column">
<span className={styles.title}>회원가입</span> <span className={styles.title}>회원가입</span>
<div className="d-flex flex-column"> <div className="d-flex flex-column">
...@@ -139,14 +154,13 @@ const Signup = () => { ...@@ -139,14 +154,13 @@ const Signup = () => {
<label className={styles.signupLabel}>아이디</label> <label className={styles.signupLabel}>아이디</label>
<div className="d-flex col-md-auto"> <div className="d-flex col-md-auto">
<input className={styles.input} type="text" name="userId" id="userId" placeholder="5~10자리 사이" onChange={handleUserOnChange} maxLength="10" required /> <input className={styles.input} type="text" name="userId" id="userId" placeholder="5~10자리 사이" onChange={handleUserOnChange} maxLength="10" required />
<button type="button" name="errorId" className={`rounded-2 mt-2 ${styles.butterYellowAndBtn} ${styles.btnHover}`} onClick={handleOnClickId}>중복확인</button> <button type="button" disabled={loading} name="errorId" className={`rounded-2 mt-2 ${styles.butterYellowAndBtn} ${styles.btnHover}`} onClick={handleOnClickId}>중복확인</button>
</div> </div>
</div> </div>
{(overlapId === false) && errorMsg.errorId && <p className={styles.passwordConfirmError}>5~10자리 사이로 입력해주세요.</p>} {(overlapId === false) && errorMsg.errorId && <p className={styles.passwordConfirmError}>5~10자리 사이로 입력해주세요.</p>}
{overlapId && (errorMsg.errorId === false) && <p className={styles.passwordConfirmError}>아이디 중복이 확인되었습니다.</p>} {overlapId && (errorMsg.errorId === false) && <p className={styles.passwordConfirmError}>아이디 중복이 확인되었습니다.</p>}
{(errorMsg.errorId === false) && (overlapId === false) && <p className={styles.passwordConfirmError}>아이디 중복확인을 해주세요.</p>} {(errorMsg.errorId === false) && (overlapId === false) && <p className={styles.passwordConfirmError}>아이디 중복확인을 해주세요.</p>}
</div> </div>
<div className="d-flex flex-column"> <div className="d-flex flex-column">
<div className={styles.inputContent}> <div className={styles.inputContent}>
<label className={styles.signupLabel}>별명</label> <label className={styles.signupLabel}>별명</label>
......
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
import config from "../config/app.config.js"; import config from "../config/app.config.js";
import { User } from '../db/index.js' import { User, Role } from '../db/index.js'
const login = async(req, res) => { const login = async(req, res) => {
try { try {
console.log(req.body);
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 } });
...@@ -12,7 +11,7 @@ const login = async(req, res) => { ...@@ -12,7 +11,7 @@ const login = async(req, res) => {
if (!user) { if (!user) {
return res.status(422).send(`사용자가 존재하지 않습니다`); return res.status(422).send(`사용자가 존재하지 않습니다`);
} }
// 2) 비밀번호 확인은 데이터베이스 프로토타입 메소드에서 처리 // 2) 비밀번호 확인은 데이터베이스 프로토타입 메소드에서 처리(사용자가 입력한 비밀번호와 서버에 있는 비번 비교)
const passwordMatch = await user.comparePassword(password); const passwordMatch = await user.comparePassword(password);
if (passwordMatch) { if (passwordMatch) {
// 3) 비밀번호가 맞으면 토큰 생성 // 3) 비밀번호가 맞으면 토큰 생성
...@@ -21,10 +20,10 @@ const login = async(req, res) => { ...@@ -21,10 +20,10 @@ const login = async(req, res) => {
userId: user.id, userId: user.id,
// 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,
...@@ -53,8 +52,8 @@ const login = async(req, res) => { ...@@ -53,8 +52,8 @@ const login = async(req, res) => {
const compareId = async (req, res) => { const compareId = async (req, res) => {
const id = req.params.userId; const id = req.params.userId;
const userid = await User.findAll({where:{userId: id}}); const userid = await User.findOne({where:{userId: id}});
if(userid){ if(userid !== null){
return res.json(true); return res.json(true);
}else{ }else{
return res.json(false); return res.json(false);
...@@ -65,21 +64,20 @@ const signup = async (req, res) => { ...@@ -65,21 +64,20 @@ const signup = async (req, res) => {
const { userId, userNickName, userBirthday, userPassword } = req.body; const { userId, userNickName, userBirthday, userPassword } = req.body;
// 휴대폰 중복 확인 // 휴대폰 중복 확인
const userMbnum = String(req.body.userMbnum); const userMbnum = String(req.body.userMbnum);
console.log(userMbnum);
console.log(typeof userMbnum);
try { try {
const mbnum = await User.findOne({ where: { phoneNumber: userMbnum } }); const mbnum = await User.findOne({ where: { phoneNumber: userMbnum } });
if (mbnum) { if (mbnum) {
return res.status(422).send(`이미 있는 휴대폰번호입니다.`); return res.status(422).send(`이미 있는 휴대폰번호입니다.`);
} }
const role = await Role.findOne({ where: {name: "user"} })
const newUser = await User.create({ const newUser = await User.create({
userId: userId, userId: userId,
nickname: userNickName, nickname: userNickName,
birth: userBirthday, birth: userBirthday,
phoneNumber: userMbnum, phoneNumber: userMbnum,
password: userPassword password: userPassword,
roleId: role.id
}); });
console.log("signup new user=", newUser);
res.json(newUser); res.json(newUser);
} catch (error) { } catch (error) {
console.error(error.message); console.error(error.message);
......
import { Sequelize } from "sequelize"; import { Sequelize } from "sequelize";
import UserModel from "../models/user.model.js"; import UserModel from "../models/user.model.js";
import RoleModel from "../models/role.model.js";
import MovieModel from "../models/movie.model.js"; import MovieModel from "../models/movie.model.js";
import dbConfig from "../config/db.config.js"; import dbConfig from "../config/db.config.js";
...@@ -20,10 +21,15 @@ const sequelize = new Sequelize( ...@@ -20,10 +21,15 @@ const sequelize = new Sequelize(
); );
const User = UserModel(sequelize) const User = UserModel(sequelize)
const Role = RoleModel(sequelize)
const Movie = MovieModel(sequelize) const Movie = MovieModel(sequelize)
User.belongsTo(Role);
Role.hasOne(User);
export { export {
sequelize, sequelize,
User, User,
Role,
Movie Movie
} }
\ No newline at end of file
import dotenv from "dotenv"; import dotenv from "dotenv";
import { sequelize } from "./db/index.js"; import { sequelize, Role } from "./db/index.js";
import app from "./app.js"; import app from "./app.js";
import appConfig from "./config/app.config.js"; import appConfig from "./config/app.config.js";
import { ROLE_NAME } from './models/role.model.js';
dotenv.config({ dotenv.config({
path: `${process.env.NODE_ENV === "production" ? ".env" : ".env.development" path: `${process.env.NODE_ENV === "production" ? ".env" : ".env.development"
...@@ -11,11 +12,11 @@ dotenv.config({ ...@@ -11,11 +12,11 @@ dotenv.config({
sequelize sequelize
.sync({ force: false }) .sync({ force: false })
.then(async () => { .then(async () => {
// await Promise.all( await Promise.all(
// Object.keys(ROLE_NAME).map((name) => { Object.keys(ROLE_NAME).map((name) => {
// return Role.create({ name }); return Role.create({ name });
// }) })
// ); );
// const adminRole = await Role.findOne({ where: { name: "admin" } }); // const adminRole = await Role.findOne({ where: { name: "admin" } });
......
...@@ -2,12 +2,12 @@ import Sequelize from "sequelize"; ...@@ -2,12 +2,12 @@ import Sequelize from "sequelize";
const { DataTypes } = Sequelize; const { DataTypes } = Sequelize;
// export const ROLE_NAME = { export const ROLE_NAME = {
// USER = "user", USER : "user",
// MEMBER = "member", MEMBER : "member",
// ADMIN = "admin", ADMIN : "admin",
// ROOT = "root", ROOT : "root",
// } }
const RoleModel = (sequelize) => { const RoleModel = (sequelize) => {
const Role = sequelize.define( const Role = sequelize.define(
......
...@@ -28,10 +28,8 @@ const UserModel = (sequelize) => { ...@@ -28,10 +28,8 @@ const UserModel = (sequelize) => {
password: { password: {
type: DataTypes.STRING, type: DataTypes.STRING,
}, },
// role: { // roleId: {
// type: DataTypes.ENUM({ // type: DataTypes.INTEGER
// values: Object.values(ROLE_NAME),
// }),
// } // }
}, },
{ {
......
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