-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
162 lines (138 loc) · 4.66 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
const express = require('express');
const session = require('express-session');
const passport = require('passport');
const app = express();
const { MongoClient, ObjectId } = require('mongodb');
const methodOverride = require('method-override');
const LocalStrategy = require('passport-local');
const bcrypt = require('bcrypt');
const { createServer } = require('http');
const { Server } = require('socket.io');
const server = createServer(app);
const io = new Server(server);
const path = require('path');
// 필요한 전역 객체 설정 (Node.js 환경에서 self를 글로벌 객체로 설정)
if (typeof self === 'undefined') {
global.self = global;
}
const MongoStore = require('connect-mongo');
require('dotenv').config();
const { S3Client } = require('@aws-sdk/client-s3');
const multer = require('multer');
const multerS3 = require('multer-s3');
const s3 = new S3Client({
region: 'ap-northeast-2',
credentials: {
accessKeyId: process.env.S3_KEY,
secretAccessKey: process.env.S3_SECRET
}
});
const upload = multer({
storage: multerS3({
s3: s3,
bucket: 'shareeat',
key: function (req, file, cb) {
cb(null, Date.now().toString()) //업로드 시 파일명 변경 가능
}
})
});
var favicon = require('serve-favicon');
app.use(express.static(path.join(__dirname, 'public/images')));
// 미들웨어 설정
app.use(methodOverride('_method'));
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
let connectDB = require('./database.js');
let db;
connectDB.then((client) => {
console.log('DB connected_app');
db = client.db('shareEat');
server.listen(8080, () => {
console.log('http://localhost:8080 에서 서버 실행 중');
});
}).catch((err) => {
console.log(err);
});
// Express 세션 미들웨어 설정
const sessionMiddleware = session({
secret: 'secret',
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: process.env.DB_URL,
dbName: 'shareEat'
})
});
app.use(sessionMiddleware);
// Passport 초기화 및 세션 설정
app.use(passport.initialize());
app.use(passport.session());
// Passport Serialize 및 Deserialize 설정
passport.serializeUser((user, done) => {
process.nextTick(() => {
done(null, { id: user._id, username: user.username });
});
});
passport.deserializeUser(async (user, done) => {
try {
const result = await db.collection('user').findOne({ _id: new ObjectId(user.id) });
if (result) {
delete result.password;
return done(null, result);
} else {
return done(new Error('User not found'));
}
} catch (err) {
return done(err);
}
});
// 사용자의 인증 상태를 확인하는 미들웨어
app.use((req, res, next) => {
const isLoggedIn = req.isAuthenticated(); // Passport를 사용하여 인증 상태 확인
res.locals.isLoggedIn = isLoggedIn;
next();
});
// 라우트 설정
const mainRoutes = require('./routes/mainRoutes');
const userRoutes = require('./routes/userRoutes');
const communityRoutes = require('./routes/communityRoutes');
const informationRoutes = require('./routes/informationRoutes');
const chatRoutes = require('./routes/chatRoutes');
const flashRoutes = require('./routes/flashRoutes');
const regularRoutes = require('./routes/regularRoutes');
app.use('/', mainRoutes);
app.use('/user', userRoutes);
app.use('/user', communityRoutes);
app.use('/user', informationRoutes);
app.use('/user', chatRoutes);
app.use('/user', flashRoutes);
app.use('/user', regularRoutes);
// 채팅 웹 소켓 설정
io.use((socket, next) => {
sessionMiddleware(socket.request, {}, next);
});
io.on('connection', (socket) => {
console.log('websocket connected');
socket.on('ask-join', async (data) => {
socket.join(data);
});
socket.on('message-send', async (data) => {
const senderId = data.senderId; // 메시지를 보낸 사용자의 ID
await db.collection('chatMessage').insertOne({
parentRoom: new ObjectId(data.room),
content: data.message,
who: new ObjectId(socket.request.session.passport.user.id),
date: new Date().toLocaleString()
});
io.to(data.room).emit('message-broadcast', { message: data.message, senderId: data.senderId});
});
// 새로운 메시지 받기
socket.on('message-broadcast', (data) => {
socket.broadcast.to(data.room).emit('message-broadcast', { message: data.message, senderId: data.senderId });
});
socket.on('disconnect', () => {
console.log('websocket disconnected');
});
});