Commit 303f5519 authored by Kim, Chaerin's avatar Kim, Chaerin
Browse files

merge19

parent 4361c312
{
"lockfileVersion": 1
}
node_modules/
package-lock.json
config/
env.development
\ No newline at end of file
env.development
/uploads
\ No newline at end of file
import { Room, User } from "../models/index.js";
import { customAlphabet } from 'nanoid'
import config from "../config/app.config.js";
import isLength from 'validator/lib/isLength.js'
const nanoid = customAlphabet('1234567890abcdef', 10)
const joinRoom = async (req, res) => {
console.log('req.body.value:', req.body)
const { userId, roomId } = req.body
console.log('userId:', userId)
console.log('roomId:', roomId)
const room_Id = await Room.findOne({ where: { id: roomId } });
console.log('room_Id:', room_Id)
if (room_Id) {
if (Boolean(room_Id)) { //roomId에 일치하는 방이 존재할때
//roomId에 일치하는 방의 member정보에 userId 저장하기
console.log('room_Id.member1:', room_Id.member)
room_Id.member.push(userId)
console.log('room_Id.member2:', room_Id.member)
await Room.update({ 'member': room_Id.member }, { where: { id: roomId } })
const roomID = await Room.findOne({ where: { id: roomId } });
console.log('room_Id2:', roomID.member)
//userId에 일치하는 사용자의 roomNumber에 roomId저장하기
// const user_Id = await User.findOne({ where: { id: userId } });
// console.log('user_Id:', user_Id)
// console.log('user_Id.roomNumber1:', user_Id.roomNumber)
// user_Id.roomNumber.push(roomId)
// console.log('user_Id.roomNumber2:', user_Id.roomNumber)
// await User.update({ 'roomNumber': roomId }, { where: { id: userId } })
// const userID = await User.findOne({ where: { id: userId } });
// console.log('user_Id2:', userID.roomNumber)
//member정보에 userId가 이미 저장되어 있는지 확인 -> 이미 참여된 방인지 확인
const includeUserId = room_Id.member.includes(parseInt(userId));
// console.log('Include확인:',includeUserId)
if (!includeUserId) { //아직 참여되지 않은 방인경우
room_Id.member.push(userId) //member에 userId추가
// console.log('room_Id.member2:', room_Id.member)
await Room.update({ 'member': room_Id.member }, { where: { id: roomId } })
//userId에 일치하는 사용자의 roomNumber에 roomId저장하기
const user_Id = await User.findOne({ where: { id: userId } });
if (Boolean(user_Id.roomNumber)) { //다른 roomNumber가 이미 들어가 있는 경우 roomId추가
user_Id.roomNumber.push(roomId)
}
else { //첫 roomNumber인 경우
user_Id.roomNumber = [roomId]
}
// console.log('user_Id.roomNumber2:', user_Id.roomNumber)
await User.update({ 'roomNumber': user_Id.roomNumber }, { where: { id: userId } })
} else {
return res.status(422).send('이미 참여된 방입니다.')
}
} else {
return res.status(422).send('참여코드와 일치하는 방이 존재하지 않습니다.')
}
};
// const changemember = async (req, res) => {
// const { userId, roomId } = req.body
// // console.log(roomId)
// let room = await Room.findOne({ roomId: roomId }).select('member')
// const isPresent = room.member.indexOf(userId)
// indexOf : userId가 몇번째 인덱스인지 찾기
// try {
// if (isPresent < 0) {
// const memberId = room.member.push(userId)
// await Room.updateOne({ 'roomId': roomId }, { 'member': room.member })
// // console.log('room.member 업데이트 완료')
// return res.json(true)
// }
// else {
// return res.json(false)
// }
// } catch (error) {
// res.status(500).send('멤버 업데이트 실패')
// }
// }
const createRoom = async (req, res) => {
console.log('룸정보', req.body)
const { name, owner, member, profileimg, channel } = req.body;
console.log('owner:', owner)
// console.log('룸정보', req.body)
const { name, owner, member, profileimg } = req.body;
const id = nanoid()
console.log('id:', id)
const Id = await Room.findOne({ where: { id: id } });
console.log("Id중복확인:", Id)
while (Id) {
// console.log('id:', id)
while (Boolean(Id)) {
const id = nanoid()
const Id = await Room.findOne({ where: { id: id } });
}
try {
if (!isLength(name, { min: 3, max: 20 })) {
console.log('방이름은 3-20자여야 합니다.')
return res.status(422).send('방이름은 3-20자여야 합니다.')
}
const newRoom = await Room.create({
//새로운 RoomDB생성
const newRoom = {
id: id,
name: name,
owner: owner,
member: member,
member: [member],
profileimg: profileimg,
channel: channel,
}).then(_ => console.log('room정보:', id, name, owner, member, profileimg, channel))
console.log('newRoom:', newRoom)
}
// console.log('newRoom:', newRoom)
await Room.create(newRoom)
//user.roomNumber에 id추가
const user_Id = await User.findOne({ where: { id: owner } });
if (user_Id.roomNumber) { //다른 roomNumber가 이미 들어가 있는 경우 id추가
user_Id.roomNumber.push(id)
}
else { //첫 roomNumber인 경우
user_Id.roomNumber = [id]
}
// console.log('user_Id.roomNumber2:', user_Id.roomNumber)
await User.update({ 'roomNumber': user_Id.roomNumber }, { where: { id: owner } })
res.json(newRoom)
} catch (error) {
console.log(error)
......@@ -91,6 +77,10 @@ const createRoom = async (req, res) => {
}
}
const getRoom = async (req, res) => {
console.log('req.body:', req.body)
}
export default {
joinRoom, createRoom
joinRoom, createRoom, getRoom
};
import { User } from "../models/index.js";
import jwt from "jsonwebtoken";
import config from "../config/app.config.js";
import isLength from 'validator/lib/isLength.js'
import bcrypt from "bcryptjs";
import isLength from "validator/lib/isLength.js";
import multer from "multer";
const test = async (req, res) => {
const uploadimg = multer({ dest: "uploads/" });
const imgUpload = uploadimg.fields([{ name: "img", maxCount: 1 }]);
const update = async (req, res) => {
try {
console.log(req);
res.json("안녕");
console.log("id:", req.body.id);
const id = req.body.id;
const avatar = req.files["img"][0];
const img = avatar.filename;
console.log(img);
await User.update({ img: img }, { where: { id: id } });
res.json(img);
} catch (error) {
console.log(error);
return res.status(500).send("test 중 에러");
res.status(500).send("이미지 업데이트 실패");
}
};
const getUser = async (req, res) => {
const user = await User.findOne({ where: { id: req.params.id } });
res.json(user)
};
const updateinfo = async (req, res) => {
console.log(req.body);
const { id, name, email, phone, img } = req.body;
console.log("id:", id);
const A = {
name: name,
email: email,
phone: phone,
img: img,
};
await User.update(A, { where: { id: id } });
const user = await User.findOne({ where: { id: id } });
console.log('user:',user)
};
const login = async (req, res) => {
try {
console.log("login= ", req.body);
const { email, password } = req.body;
const user = await User.findOne({ where: { email: email } });
if (!user)
const { email, password } = req.body
const user = await User.findOne({ where: { email: email } })
if (!user) {
return res.status(422).send(`${email} 사용자가 존재하지 않습니다.`);
const passworMatch = await user.comparePassword(password);
if (passworMatch) {
const token = jwt.sign({ userID: user.id }, config.jwtSecret, {
expiresIn: config.jwtExpires,
});
res.cookie(config.cookieName, token, {
path: "/",
httpOnly: true,
secure: true,
});
res.json({ user });
} else {
res.status(401).send("비밀번호가 일치하지 않습니다.");
const passworMatch = await user.comparePassword(password);
if (passworMatch) {
const token = jwt.sign({ userID: user.id }, config.jwtSecret, {
expiresIn: config.jwtExpires,
});
res.cookie(config.cookieName, token, {
path: "/",
httpOnly: true,
secure: true,
});
res.json(user);
} else {
res.status(401).send("비밀번호가 일치하지 않습니다.");
}
}
} catch (error) {
console.log(error);
return res.status(500).send("로그인 중 에러");
return res.status(500).send('로그인 중 에러')
}
};
const signup = async (req, res) => {
try {
console.log('signup= ', req.body);
const { name, password, id } = req.body;
if (!isLength(name, {min: 3, max: 10})) {
return res.status(422).send('이름은 3-10자 사이입니다')
} else if (!isLength(password, {min: 6})) {
return res.status(422).send('비밀번호는 6자 이상입니다')
} else if (!isLength(id, {min:3, max10})) {
return res.status(422).send('아이디는 3-10자 사이입니다')
// console.log('sign up= ', req.body)
const { name, email, password, gender, phone } = req.body
const id = Math.floor(Math.random() * (9999 - 1000) + 1000)
// console.log('id:', id)
const Id = await User.findOne({ where: { id: id } })
// console.log('Id 중복확인:', Id)
while (Id) {
const id = Math.floor(Math.random() * (9999 - 1000) + 1000);
const Id = await User.findOne({ where: { id: id } });
}
const user = await User.scope("password").findOne({ where: email });
const user = await User.findOne({ where: { email: email } });
if (user)
return res.status(422).send(`${email} 이미 존재하는 사용자입니다/+ `);
return res.status(422).send(`${email} 이미 존재하는 사용자입니다.`);
const hash = await bcrypt.hash(password, 10)
const newUser = await new User ({
name,
password: hash,
id
}).save()
console.log(newUser)
res.json(newUser)
if (!isLength(name, { min: 3, max: 10 })) {
return res.status(422).send("이름은 3-10자 사이입니다");
} else if (!isLength(password, { min: 6 })) {
return res.status(422).send("비밀번호는 6자이상 입니다");
} else if (!isLength(email, { min: 3, max: 10 })) {
return res.status(422).send("아이디는 3-10자 사이입니다");
}
const newUser = await User.create({
id: id,
name: name,
email: email,
password: password,
gender: gender,
phone: phone,
})
} catch (error) {
console.log(error);
return res.status(500).send("회원가입 중 에러")
return res.status(500).send("회원가입 중 에러");
}
}
};
const logout = (req, res) => {
res.clearCookie("token");
res.send("Logout Successful");
};
export default {
test,
getUser,
login,
signup,
logout,
imgUpload,
update,
updateinfo,
};
......@@ -20,15 +20,23 @@ sequelize
email: "admin",
password: "admin!",
gender: 0,
roomNumber : ["1234567abc","abc7654321"],
});
await Room.create({
id: "1234567890",
id: "1234567abc",
name: "room",
owner: [ '600112d16d09ac6b7892d900' ],
member: [ '600112d16d09ac6b7892d900' ],
owner: 8888,
member: [8888,9999],
profileimg: "C:\fakepath\스크린샷(1).png",
});
await Room.create({
id: "abc7654321",
name: "room1",
owner: 9999,
member: [9999],
profileimg: "C:\fakepath\스크린샷(1).png",
channel: [ '회의' ],
});
app.listen(appConfig.port, () => {
......
import pkg from "sequelize";
import pkg from 'sequelize';
const { DataTypes } = pkg;
const RoomModel = (sequelize) => {
......@@ -13,16 +13,19 @@ const RoomModel = (sequelize) => {
type: DataTypes.STRING,
},
owner: {
type: DataTypes.ARRAY(DataTypes.STRING),
type: DataTypes.INTEGER,
},
member: {
type: DataTypes.ARRAY(DataTypes.STRING),
type: DataTypes.ARRAY(DataTypes.INTEGER),
//type: DataTypes.STRING,
},
profileimg: {
type: DataTypes.STRING,
defaultValue: "/user.png"
},
channel: {
type: DataTypes.ARRAY(DataTypes.JSON),
defaultValue: [{'회의':""}],
},
},
{ timestamps: true }
......
import bcrypt from "bcryptjs";
import pkg from "sequelize";
import pkg from 'sequelize';
const { DataTypes } = pkg;
// import img from 'bora_it\client\public\user.png'
const UserModel = (sequelize) => {
const User = sequelize.define(
......@@ -23,10 +24,11 @@ const UserModel = (sequelize) => {
type: DataTypes.INTEGER,
},
phone: {
type: DataTypes.INTEGER,
type: DataTypes.STRING,
},
img: {
type: DataTypes.STRING,
// defaultValue: img
},
roomNumber: {
type: DataTypes.ARRAY(DataTypes.STRING),
......
......@@ -25,6 +25,7 @@
"express": "4.17.1",
"http": "0.0.1-security",
"jsonwebtoken": "^8.5.1",
"multer": "^1.4.2",
"nanoid": "^3.1.20",
"nodemon": "^2.0.7",
"pg": "^8.6.0",
......
......@@ -2,9 +2,8 @@ import express from "express";
import roomCrtl from "../controllers/room.controller.js";
const router = express.Router();
router.route("/getRoom").post(roomCrtl.getRoom);
router.route("/create").post(roomCrtl.createRoom);
router.route("/join").put(roomCrtl.joinRoom);
export default router;
......@@ -3,7 +3,14 @@ import userCtrl from "../controllers/user.controller.js";
const router = express.Router();
router.route("/getUser/:id").get(userCtrl.getUser);
router.route("/login").post(userCtrl.login);
router.route("/signup").post(userCtrl.signup);
router.route("/profileimg")
.put(userCtrl.imgUpload, userCtrl.update)
router.route("/updateinfo")
.put(userCtrl.updateinfo)
router.route("/").post(userCtrl.signup);
export default router;
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