Commit 77af16fc authored by Yoon, Daeki's avatar Yoon, Daeki 😅
Browse files

routes, models 수정

parent 9be920ba
......@@ -14,11 +14,13 @@
"author": "",
"license": "ISC",
"dependencies": {
"bcrypt": "^5.0.0",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"helmet": "^4.2.0",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.10.12"
}
}
const express = require('express')
const bodyParser = require('body-parser')
// import compress from 'compression'
const cors = require('cors')
const helmet = require('helmet')
const path = require('path')
// import userRoutes from './routes/user.routes'
// import authRoutes from './routes/auth.routes'
// import postRoutes from './routes/post.routes'
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const loginRouter = require('./routes/login');
const reservesRouter = require('./routes/reserves');
const noticeRouter = require('./routes/notices');
const writesRouter = require('./routes/writes');
const CURRENT_WORKING_DIR = process.cwd()
const app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
// app.use(compress())
app.use(helmet())
app.use(cors())
app.use('/dist', express.static(path.join(CURRENT_WORKING_DIR, 'dist')))
// app.use('/', userRoutes)
// app.use('/', authRoutes)
// app.use('/', postRoutes)
app.use('/', indexRouter);
app.use('/users', usersRouter, reservesRouter);
app.use('/login', loginRouter);
app.use('/reserves', reservesRouter);
app.use('/notices', noticeRouter);
app.use('/writes', writesRouter);
app.use((err, req, res, next) => {
if (err.name === 'UnauthorizedError') {
......
const mongoose = require('mongoose');
const { Schema } = mongoose;
const NoticeSchema = new Schema({
notice_img: {
type: Array,
},
notice_title: {
type: String,
required: true,
},
notice_author: {
type: String,
required: true,
},
post_date: {
type: Date,
default: Date.now,
required: true,
},
notice_content: {
type: String,
required: true,
},
});
module.exports = mongoose.model('Notice', NoticeSchema);
\ No newline at end of file
const mongoose = require('mongoose');
const { Schema } = mongoose;
const { Types: { ObjectId } } = Schema;
const ReserveSchema = new Schema({
user: {
type: ObjectId,
required: true,
ref: 'User',
},
date: {
type: String,
},
starttime: {
type: Number,
},
usetime: {
type: Number,
},
start: {
type: String,
},
end: {
type: String,
},
room: {
type: String,
},
reason: {
type: String,
},
students: {
type: Array,
},
approve: {
type: Boolean,
default: false,
},
check: {
type: Boolean,
default: false,
},
num: {
type: Number,
},
});
module.exports = mongoose.model('Reserve', ReserveSchema);
\ No newline at end of file
const mongoose = require('mongoose');
const bcrypt = require("bcrypt");
const saltRounds = 10;
const { Schema } = mongoose;
const UserSchema = new Schema({
name: {
type: String,
required: true,
},
password: {
type: String,
},
role: {
type: String,
default: 'user',
},
answer: {
type: String,
},
question: {
type: String,
},
id: {
type: Number,
required: true,
},
});
UserSchema.pre("save", function (next) {
let user = this; //User모델 자체를 가르킴.
//model 안의 paswsword가 변경 또는 생성될 때 암호화
if (user.isModified("password")) {
bcrypt.genSalt(saltRounds, function (err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, function (err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
} else {
next();
}
});
module.exports = mongoose.model('User', UserSchema);
\ No newline at end of file
const express = require('express');
const User = require('../models/user');
const router = express.Router();
/* GET home page. */
// router.get('/', function(req, res, next) {
// res.render('index', { title: 'Express' });
// });
module.exports = router;
\ No newline at end of file
const express = require('express');
const bcrypt = require("bcrypt");
const jwt = require('jsonwebtoken');
const User = require('../models/user');
const router = express.Router();
router.get('/', function (req, res, next) {
console.log('/login get request', req.body)
User.find({})
.then((signups) => {
res.json(signups);
})
.catch((err) => {
console.error(err);
next(err);
});
});
router.post('/', function (req, res, next) {
console.log('/login post request', req.body)
User.findOne({ id: req.body.id }, 'id password name', function (err, users) {
if (err) return res.status(500).json({ error: err });
if (!users) {
return res.status(404).json({ error: '해당 학번이 존재하지 않습니다.' });
}
bcrypt.compare(req.body.password, users.password, function (err, result) {
if (err) {
console.log(err)
return res.status(500).json({ error: err });
}
if (result) {
const token = jwt.sign({
id: users.id,
}, process.env.JWT_SECRET, {
expiresIn: '1h',
});
return res.status(201).json({
token,
users,
});
}
res.status(404).json({ error: '비밀번호를 다시 입력해주세요.' });
});
})
});
router.post('/find', function (req, res, next) {
console.log('/find post request', req.body)
User.findOne({ id: req.body.id }, 'id question answer', function (err, users) {
if (err) return res.status(500).json({ error: err });
if (!users) return res.status(404).json({ error: '해당 학번이 존재하지 않습니다.' });
if (users.question === req.body.question) {
if (users.answer === req.body.answer) {
return res.status(201).json({ users });
}
return res.status(404).json({ error: '답변이 일치하지 않습니다.' });
}
return res.status(404).json({ error: '질문을 다시 선택해주세요.' });
})
});
module.exports = router;
\ No newline at end of file
const jwt = require('jsonwebtoken');
exports.isLoggedIn = (req, res, next) => {
if (req.isAuthenticated()) {
next();
} else {
res.status(403).send('로그인 필요');
}
};
exports.isNotLoggedIn = (req, res, next) => {
if (!req.isAuthenticated()) {
next();
} else {
res.redirect('/');
}
};
exports.verifyToken = (req, res, next) => {
try {
req.decoded = jwt.verify(req.headers.authorization, process.env.JWT_SECRET);
console.log('decode', req.decoded)
return next();
} catch (error) {
if (error.name === 'TokenExpiredError') { // 유효기간 초과
return res.status(419).json({
code: 419,
error: '토큰이 만료되었습니다. 다시 로그인 해주세요.',
});
}
return res.status(401).json({
code: 401,
error: '유효하지 않은 토큰입니다. 다시 로그인 해주세요.',
});
}
};
\ No newline at end of file
const express = require('express');
const Notice = require('../models/notice');
const router = express.Router();
router.get('/', function (req, res, next) {
Notice.find({}).sort({ post_date: -1 })
.then((notices) => {
res.status(201).json(notices);
})
.catch((err) => {
console.error(err);
next(err);
});
// res.status(404).json({error:"없음."})
res.status(201).json(notices);
});
module.exports = router;
\ No newline at end of file
const express = require('express');
const User = require('../models/user');
const Reserve = require('../models/reserve');
const { verifyToken } = require('./middlewares');
const router = express.Router();
router.post('/', function (req, res, next) {
console.log('/reserve post req.body', req.body)
let num = req.body.students.length + 1;
for (let ele of req.body.students) {
if (ele.member === '') {
num -= 1;
};
};
if (req.body.roomInfo > num) return res.status(404).json({ error: "사용할 강의실의 최소 인원을 맞춰주세요." })
const reserve = new Reserve({
user: req.body._id,
date: req.body.date,
starttime: Number(req.body.starttime),
usetime: Number(req.body.usetime),
start: `${req.body.date}T` + `${req.body.starttime}:00:00`,
end: `${req.body.date}T` + `${Number(req.body.starttime) + Number(req.body.usetime)}:00:00`,
room: req.body.room,
reason: req.body.reason,
students: req.body.students,
approve: true,
check: true,
num: req.body.students.length + 1,
});
Reserve.find({ room: req.body.room, approve: true }, function (err, reserves) {
if (err) return res.status(500).json({ error: err });
if (!reserves) {
reserve.save()
.then((result) => {
console.log(result);
res.status(201).json(result);
})
.catch((err) => {
console.error(err);
next(err);
});
}
const strt = new Date(reserve.start)
const endt = new Date(reserve.end)
const reserveArr = reserves.map(item => (
(strt >= new Date(item.start) && strt < new Date(item.end)) ||
(endt > new Date(item.start) && endt <= new Date(item.end)) ?
"item" :
null
))
console.log("array", reserveArr)
if (!reserveArr.includes("item")) {
reserve.save()
.then((result) => {
console.log(result);
res.status(201).json(reserves);
})
.catch((err) => {
console.error(err);
next(err);
});
}
else return res.status(404).json({ error: "다른 시간을 선택해주세요." })
})
});
router.get('/room/:room', function (req, res, next) {
console.log('reserves get room req.params', req.params)
Reserve.find({ room: req.params.room, approve: true }, function (err, reserve) {
if (err) return res.status(500).json({ error: err });
console.log('reserve room list', reserve);
res.status(201).json(reserve);
})
})
router.get('/:_id', verifyToken, function (req, res, next) {
console.log('/reserves get req.params', req.params)
Reserve.find({ user: req.params._id }, function (err, reserve) {
if (err) return res.status(500).json({ error: err });
// console.log(reserve, Date.now())
const reserves = reserve.map(item => (
new Date(item.end) >= Date.now() ? item : ""
));
if (!reserves) {
console.log("no신청")
res.status(404).json({ error: "신청내역이 없습니다." })
}
console.log("reserves", reserves)
res.status(201).json(reserves);
})
});
router.get('/admin/:_id', verifyToken, function (req, res, next) {
console.log('/reserves/admin get req.params', req.params)
Reserve.find({ approve: false }).populate('user').exec(function (err, reserve) {
if (err) return res.status(500).json({ error: err });
console.log('reserve list', reserve)
res.status(201).json(reserve);
})
});
router.delete('/:_id', function (req, res, next) {
console.log('/reserves delete req.params', req.params)
Reserve.findOne({ _id: req.params._id }, function (err, reserve) {
if (err) return res.status(500).json({ error: err });
reserve.remove()
.then(() => {
console.log();
res.status(201).json();
})
.catch((err) => {
console.error(err);
next(err);
});
})
});
router.put('/:id', function (req, res, next) {
console.log('/reserves put req.body', req.params)
Reserve.findOne({ _id: req.params.id }, 'check approve', function (err, reserve) {
if (err) return res.status(500).json({ error: err });
reserve.check = true;
reserve.approve = req.body.approve;
reserve.save()
.then((result) => {
console.log(result);
res.status(201).json(result);
})
.catch((err) => {
console.error(err);
next(err);
});
});
});
module.exports = router;
\ No newline at end of file
const express = require('express');
const User = require('../models/user');
const bcrypt = require("bcrypt");
const { verifyToken } = require('./middlewares');
const router = express.Router();
router.post('/', function (req, res, next) {
console.log('/users post req.body', req.body)
User.findOne({ id: req.body.id }, function (err, users) {
if (err) return res.status(500).json({ error: err });
if (users) {
return res.status(404).json({ error: '이미 존재하는 학번입니다.' })
};
const user = new User({
name: req.body.name,
id: req.body.id,
password: req.body.password,
question: req.body.question,
answer: req.body.answer,
});
user.save()
.then((result) => {
console.log(result);
res.status(201).json(result);
})
.catch((err) => {
console.error(err);
next(err);
});
})
});
router.get('/:_id', verifyToken, function (req, res, next) {
console.log('/users get req.params', req.params)
User.findOne({ _id: req.params._id }, function (err, user) {
if (err) return res.status(500).json({ error: err });
res.status(201).json(user);
})
});
router.get('/admin/:_id', function (req, res, next) {
console.log('/admin get req.params', req.params)
User.findOne({ _id: req.params._id }, 'role', function (err, user) {
if (err) return res.status(500).json({ error: err });
if (user.role == 'admin') {
next();
}
else return res.status(404).json({ error: '권한이 없습니다.' })
})
});
router.put('/change/:id', function (req, res, next) {
console.log('/change put req.body', req.params)
User.findOne({ _id: req.params.id }, 'password', function (err, user) {
if (err) return res.status(500).json({ error: err });
bcrypt.compare(req.body.password, user.password, function (err, result) {
if (err) {
console.log(err)
return res.status(500).json({ error: err });
}
if (result) {
return res.status(404).json({ error: '새로운 비밀번호를 입력해주세요.' })
}
});
user.password = req.body.password;
user.save()
.then((result) => {
console.log(result);
res.status(201).json(result);
})
.catch((err) => {
console.error(err);
next(err);
});
})
});
module.exports = router;
const express = require('express');
// const path = require('path');
// const multer = require('multer');
// const fs = require('fs');
const Notice = require('../models/notice');
const router = express.Router();
router.post('/', function (req, res, next) {
console.log("writes req.body", req.body)
const notice = new Notice({
notice_title: req.body.title,
notice_author: "예진",
notice_content: req.body.content
});
console.log(notice);
notice.save()
.then((result) => {
console.log(result);
res.status(201).json(result);
})
.catch((err) => {
console.error(err);
next(err);
});
});
module.exports = router;
\ No newline at end of file
This diff is collapsed.
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