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 { Room, User } from "../models/index.js";
//import { customAlphabet } from 'nanoid' import { customAlphabet } from 'nanoid'
import { Op } from 'sequelize';
import config from "../config/app.config.js"; import config from "../config/app.config.js";
import isLength from 'validator/lib/isLength.js' import isLength from 'validator/lib/isLength.js'
//const nanoid = customAlphabet('1234567890abcdef', 10) const nanoid = customAlphabet('1234567890abcdef', 10)
const roomJoin = async (req, res) => { const joinRoom = async (req, res) => {
try { console.log('req.body.value:', req.body)
console.log("room= ", req.body); const { userId, roomId } = req.body
res.json("안녕"); const room_Id = await Room.findOne({ where: { id: roomId } });
} catch (error) { console.log('room_Id1:', room_Id)
console.log(error); console.log('room_Id있는지:', Boolean(room_Id))
return res.status(500).send("안녕 중 에러"); 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 { name, owner, member, profileimg } = req.body;
const id = nanoid() const id = nanoid()
const Id = await Room.findOne({ id }) const Id = await Room.findOne({ where: { id: id } });
while (Id) { console.log('id:', id)
id = nanoid() while (Boolean(Id)) {
Id = await Room.findOne({ id }) const id = nanoid()
const Id = await Room.findOne({ where: { id: id } });
} }
try { try {
if (!isLength(name, { min: 3, max: 20 })) { if (!isLength(name, { min: 3, max: 20 })) {
console.log('방이름은 3-20자여야 합니다.')
return res.status(422).send('방이름은 3-20자여야 합니다.') return res.status(422).send('방이름은 3-20자여야 합니다.')
} }
const newRoom = {
const newRoom = await new Room({ id: id,
id, name: name,
name, owner: owner,
owner, member: [member],
member, profileimg: profileimg,
profileimg, }
}).save() console.log('newRoom:', newRoom)
// console.log(newRoom) await Room.create(newRoom)
console.log('room정보:', id, name, owner, [member], profileimg)
res.json(newRoom) res.json(newRoom)
} catch (error) { } catch (error) {
console.log(error) console.log(error)
...@@ -45,5 +85,5 @@ const roomCreate = async (req, res) => { ...@@ -45,5 +85,5 @@ const roomCreate = async (req, res) => {
} }
export default { export default {
roomJoin, roomCreate joinRoom, createRoom
}; };
import { User } from "../models/index.js"; import { User } from '../models/index.js'
import jwt from "jsonwebtoken"; import jwt from 'jsonwebtoken'
import config from "../config/app.config.js"; import config from '../config/app.config.js'
import isLength from 'validator/lib/isLength.js' import isLength from 'validator/lib/isLength.js'
import bcrypt from "bcryptjs"; import bcrypt from "bcryptjs";
<<<<<<< HEAD
const multer = require('multer'); const multer = require('multer');
const uploadimg = multer({ dest: 'uploads/' }); const uploadimg = multer({ dest: 'uploads/' });
...@@ -24,66 +25,94 @@ const update = async (req, res) => { ...@@ -24,66 +25,94 @@ const update = async (req, res) => {
res.status(500).send('이미지 업데이트 실패') 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) => { const login = async (req, res) => {
try { try {
console.log("login= ", req.body); console.log('login= ', req.body)
const { email, password } = req.body; const { email, password } = req.body
const user = await User.findOne({ where: { email: email } }); const user = await User.findOne({ where: { email: email } })
if (!user) if (!user) {
return res.status(422).send(`${email} 사용자가 존재하지 않습니다.`); return res.status(422).send(`${email} 사용자가 존재하지 않습니다.`)
} else {
const passworMatch = await user.comparePassword(password); const passworMatch = await user.comparePassword(password)
if (passworMatch) { if (passworMatch) {
const token = jwt.sign({ userID: user.id }, config.jwtSecret, { const token = jwt.sign({ userID: user.id }, config.jwtSecret, {
expiresIn: config.jwtExpires, expiresIn: config.jwtExpires,
}); })
res.cookie(config.cookieName, token, { res.cookie(config.cookieName, token, {
path: "/", path: '/',
httpOnly: true, httpOnly: true,
secure: true, secure: true,
}); })
res.json({ user }); res.json(user)
} else { } else {
res.status(401).send("비밀번호가 일치하지 않습니다."); res.status(401).send('비밀번호가 일치하지 않습니다.')
}
} }
} catch (error) { } catch (error) {
console.log(error); console.log(error)
return res.status(500).send("로그인 중 에러"); return res.status(500).send('로그인 중 에러')
} }
}; }
const signup = async (req, res) => { const signup = async (req, res) => {
try { try {
console.log('signup= ', req.body); console.log('sign up= ', req.body)
const { name, password, id } = req.body; const { name, email, password, gender, phone } = req.body
if (!isLength(name, {min: 3, max: 10})) { const id = Math.floor(Math.random() * (9999 - 1000) + 1000)
return res.status(422).send('이름은 3-10자 사이입니다') console.log('id:', id)
} else if (!isLength(password, {min: 6})) { const Id = await User.findOne({ where: { id: id } })
return res.status(422).send('비밀번호는 6자 이상입니다') console.log('Id 중복확인:', Id)
} else if (!isLength(id, {min:3, max10})) { while (Id) {
return res.status(422).send('아이디는 3-10자 사이입니다') 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) if (user)
return res.status(422).send(`${email} 이미 존재하는 사용자입니다/+ `); return res.status(422).send(`${email} 이미 존재하는 사용자입니다.`)
const hash = await bcrypt.hash(password, 10) if (!isLength(name, { min: 3, max: 10 })) {
const newUser = await new User ({ return res.status(422).send('이름은 3-10자 사이입니다')
name, } else if (!isLength(password, { min: 6 })) {
password: hash, return res.status(422).send('비밀번호는 6자이상 입니다')
id } else if (!isLength(email, { min: 3, max: 10 })) {
}).save() return res.status(422).send('아이디는 3-10자 사이입니다')
console.log(newUser) }
res.json(newUser) 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) { } catch (error) {
console.log(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 { export default {
getUser,
login, login,
signup, signup,
update, logout,
imgUpload }
};
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
import dotenv from "dotenv"; import dotenv from "dotenv";
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 { sequelize, User } from "./models/index.js"; import { Room, sequelize, User } from "./models/index.js";
dotenv.config({ dotenv.config({
path: `${ path: `${
...@@ -15,13 +15,21 @@ sequelize ...@@ -15,13 +15,21 @@ sequelize
.then(async () => { .then(async () => {
console.log(" DB 연결 성공"); console.log(" DB 연결 성공");
await User.create({ await User.create({
id: 9999, id: "9999",
name: "admin", name: "admin",
email: "admin", email: "admin",
password: "admin!", password: "admin!",
gender: 0, gender: 0,
}); });
await Room.create({
id: "1234567890",
name: "room",
owner: "8888",
member: ['8888'],
profileimg: "C:\fakepath\스크린샷(1).png",
});
app.listen(appConfig.port, () => { app.listen(appConfig.port, () => {
console.log(`Server is running on port ${appConfig.port}`); console.log(`Server is running on port ${appConfig.port}`);
}); });
...@@ -30,39 +38,3 @@ sequelize ...@@ -30,39 +38,3 @@ sequelize
console.log("연결 실패"); console.log("연결 실패");
console.log(err); 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) => { ...@@ -5,7 +5,7 @@ const RoomModel = (sequelize) => {
"room", "room",
{ {
id: { id: {
type: DataTypes.INTEGER, type: DataTypes.STRING,
primaryKey: true, primaryKey: true,
}, },
name: { name: {
...@@ -16,19 +16,21 @@ const RoomModel = (sequelize) => { ...@@ -16,19 +16,21 @@ const RoomModel = (sequelize) => {
}, },
member: { member: {
type: DataTypes.ARRAY(DataTypes.INTEGER), type: DataTypes.ARRAY(DataTypes.INTEGER),
//type: DataTypes.STRING,
}, },
profileimg: { profileimg: {
type: DataTypes.STRING, type: DataTypes.STRING,
default: '3cd14b9bcb2007f324fcb82e0b566cce', defaultValue: "/user.png"
}, },
channel: { channel: {
type: DataTypes.ARRAY(DataTypes.JSON), type: DataTypes.ARRAY(DataTypes.JSON),
defaultValue: [{'회의':""}],
}, },
}, },
{ timestamps: true } { timestamps: true }
); );
return Room; return Room;
}; };
export default RoomModel; export default RoomModel;
...@@ -22,10 +22,11 @@ const UserModel = (sequelize) => { ...@@ -22,10 +22,11 @@ const UserModel = (sequelize) => {
type: DataTypes.INTEGER, type: DataTypes.INTEGER,
}, },
phone: { phone: {
type: DataTypes.STRING, type: DataTypes.INTEGER,
}, },
img: { img: {
type: DataTypes.STRING, type: DataTypes.STRING,
defaultValue: "/user.png"
}, },
roomNumber: { roomNumber: {
type: DataTypes.ARRAY(DataTypes.STRING), type: DataTypes.ARRAY(DataTypes.STRING),
......
...@@ -8,6 +8,9 @@ ...@@ -8,6 +8,9 @@
"dev": "nodemon -r esm index.js", "dev": "nodemon -r esm index.js",
"build": "tsc -p ." "build": "tsc -p ."
}, },
"nodemonConfig": {
"ignore": ["test/*", "docs/*", "client/*"]
},
"repository": { "repository": {
"type": "git", "type": "git",
"url": "https://compmath.korea.ac.kr/gitlab/research/bora_it.git" "url": "https://compmath.korea.ac.kr/gitlab/research/bora_it.git"
...@@ -25,6 +28,7 @@ ...@@ -25,6 +28,7 @@
"http": "0.0.1-security", "http": "0.0.1-security",
"jsonwebtoken": "^8.5.1", "jsonwebtoken": "^8.5.1",
"multer": "^1.4.2", "multer": "^1.4.2",
"nanoid": "^3.1.23",
"nodemon": "^2.0.7", "nodemon": "^2.0.7",
"pg": "^8.6.0", "pg": "^8.6.0",
"pg-hstore": "^2.3.4", "pg-hstore": "^2.3.4",
......
...@@ -5,6 +5,6 @@ import roomRouter from "./room.route.js"; ...@@ -5,6 +5,6 @@ import roomRouter from "./room.route.js";
const router = express.Router(); const router = express.Router();
router.use("/", userRouter); router.use("/", userRouter);
router.use("/room/:userId/:channelId", roomRouter); router.use("/room", roomRouter);
export default router; export default router;
...@@ -3,8 +3,8 @@ import roomCrtl from "../controllers/room.controller.js"; ...@@ -3,8 +3,8 @@ import roomCrtl from "../controllers/room.controller.js";
const router = express.Router(); const router = express.Router();
//router.route("/").get(roomCrtl.login); router.route("/create").post(roomCrtl.createRoom);
router.route("/room/create")
.post(roomCrtl.roomCreate) router.route("/join").put(roomCrtl.joinRoom);
export default router; export default router;
...@@ -3,6 +3,7 @@ import userCtrl from "../controllers/user.controller.js"; ...@@ -3,6 +3,7 @@ import userCtrl from "../controllers/user.controller.js";
const router = express.Router(); const router = express.Router();
router.route("/getUser").post(userCtrl.getUser);
router.route("/login").post(userCtrl.login); router.route("/login").post(userCtrl.login);
router.route("/signup").post(userCtrl.signup); 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