Commit 63618602 authored by 이재연's avatar 이재연
Browse files

Merge remote-tracking branch 'origin/seoyeon2' into jaeyeoniiiiii

parents e72932e2 3aa0a668
import { Room } from "../models/index.js";
//import { customAlphabet } from 'nanoid'
import { Room, User } from "../models/index.js";
import { customAlphabet } from 'nanoid'
import { Op } from 'sequelize';
import config from "../config/app.config.js";
import isLength from 'validator/lib/isLength.js'
//const nanoid = customAlphabet('1234567890abcdef', 10)
const nanoid = customAlphabet('1234567890abcdef', 10)
const roomJoin = async (req, res) => {
try {
console.log("room= ", req.body);
res.json("안녕");
} catch (error) {
console.log(error);
return res.status(500).send("안녕 중 에러");
const joinRoom = async (req, res) => {
console.log('req.body.value:', req.body)
const { userId, roomId } = req.body
const room_Id = await Room.findOne({ where: { id: roomId } });
console.log('room_Id1:', room_Id)
console.log('room_Id있는지:', Boolean(room_Id))
console.log('room_Id.member1:', room_Id.member)
if (Boolean(room_Id)) {
//roomId에 일치하는 방의 member정보에 userId 저장하기
const matchedUserId = room_Id.member.filter(memberId => memberId === userId)
console.log('matchedUserId:', matchedUserId)
// if (matchedUserId.length === 0) {
// room_Id.member.push(userId)
// }
// else {
// return res.status(422).send('이미 참여된 방입니다.')
// }
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)
const matchedRoomId = user_Id.roomNumber.filter(roomNum => roomNum === roomId)
console.log('matchedRoomId:',matchedRoomId)
console.log('matchedRoomId boo:',Boolean(matchedRoomId))
console.log('user_Id.roomNumber1:', user_Id.roomNumber)
console.log('user_Id.roomNumber1:', Boolean(user_Id.roomNumber))
if (Boolean(user_Id.roomNumber)) {
user_Id.roomNumber.push(roomId)
}
else {
user_Id.roomNumber = [roomId]
}
console.log('user_Id.roomNumber2:', user_Id.roomNumber)
await User.update({ 'roomNumber': user_Id.roomNumber }, { where: { id: userId } })
const userID = await User.findOne({ where: { id: userId } });
console.log('user_Id2:', userID.roomNumber)
} else {
return res.status(422).send('참여코드와 일치하는 방이 존재하지 않습니다.')
}
};
const roomCreate = async (req, res) => {
const createRoom = async (req, res) => {
console.log('룸정보', req.body)
const { name, owner, member, profileimg } = req.body;
const id = nanoid()
const Id = await Room.findOne({ id })
while (Id) {
id = nanoid()
Id = await Room.findOne({ id })
const Id = await Room.findOne({ where: { id: 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 new Room({
id,
name,
owner,
member,
profileimg,
}).save()
// console.log(newRoom)
const newRoom = {
id: id,
name: name,
owner: owner,
member: [member],
profileimg: profileimg,
}
console.log('newRoom:', newRoom)
await Room.create(newRoom)
console.log('room정보:', id, name, owner, [member], profileimg)
res.json(newRoom)
} catch (error) {
console.log(error)
......@@ -45,5 +85,5 @@ const roomCreate = async (req, res) => {
}
export default {
roomJoin, roomCreate
joinRoom, createRoom
};
import { User } from "../models/index.js";
import jwt from "jsonwebtoken";
import config from "../config/app.config.js";
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";
<<<<<<< HEAD
const multer = require('multer');
const uploadimg = multer({ dest: 'uploads/' });
......@@ -24,66 +25,94 @@ const update = async (req, res) => {
res.status(500).send('이미지 업데이트 실패')
}
}
=======
const getUser = async (req, res) => {
console.log('유저가져왔다아아아ㅏㅇ:',req.body)
console.log('id:',req.body.id)
const id = req.body.id
const user = await User.findOne({ where: { id: id } });
console.log('user:',user)
req.json(user)
};
>>>>>>> origin/seoyeon2
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)
return res.status(422).send(`${email} 사용자가 존재하지 않습니다.`);
const passworMatch = await user.comparePassword(password);
console.log('login= ', req.body)
const { email, password } = req.body
const user = await User.findOne({ where: { email: email } })
if (!user) {
return res.status(422).send(`${email} 사용자가 존재하지 않습니다.`)
} else {
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: "/",
path: '/',
httpOnly: true,
secure: true,
});
res.json({ user });
})
res.json(user)
} else {
res.status(401).send("비밀번호가 일치하지 않습니다.");
res.status(401).send('비밀번호가 일치하지 않습니다.')
}
}
} catch (error) {
console.log(error);
return res.status(500).send("로그인 중 에러");
console.log(error)
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,
}).then(_ =>
console.log('회원가입 정보', id, name, email, password, gender, phone),
)
} catch (error) {
console.log(error);
return res.status(500).send("회원가입 중 에러")
console.log(error)
return res.status(500).send('회원가입 중 에러')
}
}
const logout = (req, res) => {
res.clearCookie('token')
res.send('Logout Successful')
}
export default {
getUser,
login,
signup,
update,
imgUpload
};
logout,
}
......@@ -2,7 +2,7 @@
import dotenv from "dotenv";
import app from "./app.js";
import appConfig from "./config/app.config.js";
import { sequelize, User } from "./models/index.js";
import { Room, sequelize, User } from "./models/index.js";
dotenv.config({
path: `${
......@@ -15,13 +15,21 @@ sequelize
.then(async () => {
console.log(" DB 연결 성공");
await User.create({
id: 9999,
id: "9999",
name: "admin",
email: "admin",
password: "admin!",
gender: 0,
});
await Room.create({
id: "1234567890",
name: "room",
owner: "8888",
member: ['8888'],
profileimg: "C:\fakepath\스크린샷(1).png",
});
app.listen(appConfig.port, () => {
console.log(`Server is running on port ${appConfig.port}`);
});
......@@ -30,39 +38,3 @@ sequelize
console.log("연결 실패");
console.log(err);
});
\ No newline at end of file
// production
// sequelize.sync().then(() => {
// app.listen(appConfig.port, () => {
// console.log(`Server is running on port ${appConfig.port}`)
// })
// })
// development
// 주의!!!: {force: true}는 서버가 다시 시작되면 기존 디비 모두 삭제되고 새로운 디비 생성
// sequelize
// .sync({ force: true })
// .then(async () => {
// // await Promise.all(
// // Object.keys(ROLE_NAME).map((name) => {
// // return Role.create({ name });
// // })
// // );
// // const adminRole = await Role.findOne({ where: { name: "admin" } });
// await User.create({
// id: "0000",
// name: "admin",
// email: "admin",
// password: "admin!",
// gender: 0,
// });
// app.listen(appConfig.port, () => {
// console.log(`Server is running on port ${appConfig.port}`);
// });
// })
// .catch((err) => {
// console.log(err);
// });
......@@ -5,7 +5,7 @@ const RoomModel = (sequelize) => {
"room",
{
id: {
type: DataTypes.INTEGER,
type: DataTypes.STRING,
primaryKey: true,
},
name: {
......@@ -16,19 +16,21 @@ const RoomModel = (sequelize) => {
},
member: {
type: DataTypes.ARRAY(DataTypes.INTEGER),
//type: DataTypes.STRING,
},
profileimg: {
type: DataTypes.STRING,
default: '3cd14b9bcb2007f324fcb82e0b566cce',
defaultValue: "/user.png"
},
channel: {
type: DataTypes.ARRAY(DataTypes.JSON),
defaultValue: [{'회의':""}],
},
},
{ timestamps: true }
);
return Room;
};
export default RoomModel;
......@@ -22,10 +22,11 @@ const UserModel = (sequelize) => {
type: DataTypes.INTEGER,
},
phone: {
type: DataTypes.STRING,
type: DataTypes.INTEGER,
},
img: {
type: DataTypes.STRING,
defaultValue: "/user.png"
},
roomNumber: {
type: DataTypes.ARRAY(DataTypes.STRING),
......
......@@ -8,6 +8,9 @@
"dev": "nodemon -r esm index.js",
"build": "tsc -p ."
},
"nodemonConfig": {
"ignore": ["test/*", "docs/*", "client/*"]
},
"repository": {
"type": "git",
"url": "https://compmath.korea.ac.kr/gitlab/research/bora_it.git"
......@@ -25,6 +28,7 @@
"http": "0.0.1-security",
"jsonwebtoken": "^8.5.1",
"multer": "^1.4.2",
"nanoid": "^3.1.23",
"nodemon": "^2.0.7",
"pg": "^8.6.0",
"pg-hstore": "^2.3.4",
......
......@@ -5,6 +5,6 @@ import roomRouter from "./room.route.js";
const router = express.Router();
router.use("/", userRouter);
router.use("/room/:userId/:channelId", roomRouter);
router.use("/room", roomRouter);
export default router;
......@@ -3,8 +3,8 @@ import roomCrtl from "../controllers/room.controller.js";
const router = express.Router();
//router.route("/").get(roomCrtl.login);
router.route("/room/create")
.post(roomCrtl.roomCreate)
router.route("/create").post(roomCrtl.createRoom);
router.route("/join").put(roomCrtl.joinRoom);
export default router;
......@@ -3,6 +3,7 @@ import userCtrl from "../controllers/user.controller.js";
const router = express.Router();
router.route("/getUser").post(userCtrl.getUser);
router.route("/login").post(userCtrl.login);
router.route("/signup").post(userCtrl.signup);
......
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