Commit f3b19503 authored by 권병윤's avatar 권병윤
Browse files

master, woojiweon, byoungyun1 비교후 합침

parent 3e9c534c
import axios from "axios";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { Redirect } from "react-router-dom"; import { Redirect } from "react-router-dom";
import userApi from "../apis/user.api"; import userApi from "../apis/user.api";
......
import Header from '../components/Header'
import ChannelList from '../components/Room/ChannelList' import ChannelList from '../components/Room/ChannelList'
import RoomHeader from '../components/Room/RoomHeader' import RoomHeader from '../components/Room/RoomHeader'
import Screen from '../components/Room/Screen' import Screen from '../components/Room/Screen'
......
import { Room, User } from "../models/index.js";
import { customAlphabet } from 'nanoid'
import isLength from 'validator/lib/isLength.js'
const nanoid = customAlphabet('1234567890abcdef', 10)
const joinRoom = async (req, res) => {
const { userId, roomId } = req.body
const room_Id = await Room.findOne({ where: { id: roomId } });
if (Boolean(room_Id)) { //roomId에 일치하는 방이 존재할때
//roomId에 일치하는 방의 member정보에 userId 저장하기
//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 createRoom = async (req, res) => {
// console.log('룸정보', req.body)
const { name, owner, member, profileimg } = req.body;
const id = nanoid()
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 })) {
return res.status(422).send('방이름은 3-20자여야 합니다.')
}
//새로운 RoomDB생성
const newRoom = {
id: id,
name: name,
owner: owner,
member: [member],
profileimg: profileimg,
}
// console.log('newRoom:', newRoom)
await Room.create(newRoom)
//user.roomNumber에 id추가
const user_Id = await User.findOne({ where: { id: owner } });
if (Boolean(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)
res.status(500).send('방생성 에러')
}
}
const getRoom = async (req, res) => {
console.log('req.body:', req.body)
}
export default {
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";
const multer = require("multer");
const uploadimg = multer({ dest: "uploads/" });
const imgUpload = uploadimg.fields([{ name: "img", maxCount: 1 }]);
const update = async (req, res) => {
try {
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);
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 {
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: "/",
httpOnly: true,
secure: true,
});
res.json(user);
} else {
res.status(401).send("비밀번호가 일치하지 않습니다.");
}
}
} catch (error) {
return res.status(500).send('로그인 중 에러')
}
};
const signup = async (req, res) => {
try {
// 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.findOne({ where: { email: email } });
if (user)
return res.status(422).send(`${email} 이미 존재하는 사용자입니다.`);
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("회원가입 중 에러");
}
};
const logout = (req, res) => {
res.clearCookie("token");
res.send("Logout Successful");
};
export default {
getUser,
login,
signup,
logout,
imgUpload,
update,
updateinfo,
};
// server 진입점
import dotenv from "dotenv";
import app from "./app.js";
import appConfig from "./config/app.config.js";
import { Room, sequelize, User } from "./models/index.js";
dotenv.config({
path: `${
process.env.NODE_ENV === "production" ? ".env" : ".env.development"
}`,
});
sequelize
.sync({ force: true })
.then(async () => {
console.log(" DB 연결 성공");
await User.create({
id: "9999",
name: "admin",
email: "admin",
password: "admin!",
gender: 0,
roomNumber : ["1234567abc","abc7654321"],
});
await Room.create({
id: "1234567abc",
name: "room",
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",
});
app.listen(appConfig.port, () => {
console.log(`Server is running on port ${appConfig.port}`);
});
})
.catch((err) => {
console.log("연결 실패");
console.log(err);
});
\ No newline at end of file
import { Sequelize } from "sequelize";
import UserModel from "./user.model.js";
import RoomModel from "./room.model.js";
const env = process.env.NODE_ENV || "development";
import configs from "../config/config.js";
const config = configs[env];
const sequelize = new Sequelize(
config.database,
config.username,
config.password,
{ host: config.host, dialect: config.dialect }
);
const User = UserModel(sequelize);
const Room = RoomModel(sequelize);
User.hasMany(Room);
export { sequelize, User, Room };
import { DataTypes } from "sequelize";
const RoomModel = (sequelize) => {
const Room = sequelize.define(
"room",
{
id: {
type: DataTypes.STRING,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
},
owner: {
type: DataTypes.INTEGER,
},
member: {
type: DataTypes.ARRAY(DataTypes.INTEGER),
//type: DataTypes.STRING,
},
profileimg: {
type: DataTypes.STRING,
defaultValue: "/user.png"
},
channel: {
type: DataTypes.ARRAY(DataTypes.JSON),
defaultValue: [{'회의':""}],
},
},
{ timestamps: true }
);
return Room;
};
export default RoomModel;
import bcrypt from "bcryptjs";
import { DataTypes } from "sequelize";
// import img from 'bora_it\client\public\user.png'
const UserModel = (sequelize) => {
const User = sequelize.define(
"user",
{
id: {
type: DataTypes.INTEGER,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
},
email: {
type: DataTypes.STRING,
},
password: {
type: DataTypes.STRING,
},
gender: {
type: DataTypes.INTEGER,
},
phone: {
type: DataTypes.STRING,
},
img: {
type: DataTypes.STRING,
defaultValue:'defaultimg'
},
roomNumber: {
type: DataTypes.ARRAY(DataTypes.STRING),
},
},
{ timestamps: true }
);
User.beforeSave(async (user) => {
if (!user.changed("password")) {
return;
}
if (user.password) {
const hashedPassword = await bcrypt.hash(user.password, 10);
user.password = hashedPassword;
}
});
User.prototype.toJSON = function toJSON() {
const values = Object.assign({}, this.get());
delete values.password;
return values;
};
User.prototype.comparePassword = async function (plainPassword) {
const passwordMatch = await bcrypt.compare(plainPassword, this.password);
return passwordMatch;
};
return User;
};
export default UserModel;
{
"name": "bora_it",
"version": "1.0.0",
"description": "Streaming Service",
"main": "index.js",
"scripts": {
"start": "nodemon index.js",
"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"
},
"keywords": [],
"author": "Chaerin Kim,",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"cookie-parser": "^1.4.5",
"cors": "2.8.5",
"dotenv": "^10.0.0",
"esm": "^3.2.25",
"express": "4.17.1",
"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",
"postgres": "^1.0.2",
"sequelize": "^6.6.5",
"socket.io": "2.3.0",
"wrtc": "0.4.6"
},
"devDependencies": {
"nodemon": "2.0.7"
}
}
import express from "express";
import userRouter from "./user.route.js";
import roomRouter from "./room.route.js";
const router = express.Router();
router.use("/", userRouter);
router.use("/room", roomRouter);
export default router;
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;
import express from "express";
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