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

회원가입, 로그인

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