forked from Bellisario/BChat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
369 lines (295 loc) · 9.24 KB
/
server.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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
require('dotenv').config();
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const eta = require('eta');
const path = require('path');
const lusca = require('lusca');
const basicAuth = require('express-basic-auth');
const errorHandler = require('errorhandler');
const ua = require('express-useragent');
const socketSession = require('express-socket.io-session');
const { customAlphabet } = require('nanoid');
const seo = require('./tools/seo');
const terminate = require('./tools/terminate');
app.use(ua.express());
app.use(require('cookie-parser')('thankyoujesus'));
// eslint-disable-next-line import/order
const cookieSession = require('cookie-session')({
name: 'bubbl-chat-session',
keys: ['key'],
// Cookie Options
cookie: {
path: '/',
maxAge: 1000 * 60 * 24, // 24 hours,
httpOnly: true,
secure: true,
overwrite: false,
},
maxAge: 7 * 24 * 60 * 60 * 1000, // 24 hours x 7
});
const Dbloader = require('./tools/db');
const { shutdown } = require('./tools/persist-db');
const SocketServer = require('./classes/SocketServer');
const ChatServer = require('./classes/ChatServer');
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieSession);
function setCache(req, res, next) {
// here you can define period in second, this one is 5 minutes
const period = 60 * 5;
// you only want to cache for GET requests
if (req.method == 'GET') {
res.set('Cache-control', `public, max-age=${period}, must-revalidate`);
} else {
// for the other requests set strict no caching parameters
res.set('Cache-control', `no-store`);
}
next();
}
/** ETA TEMPLATE ENGINE */
app.engine('eta', eta.renderFile);
app.set('view engine', 'eta');
app.set('views', path.join(__dirname, 'views')); // crucial! lol
eta.configure({ views: path.resolve('views'), useWith: true });
/** security */
app.use(lusca.xframe('SAMEORIGIN'));
app.use(lusca.xssProtection(true));
app.use(lusca.nosniff());
// app.use(lusca.csrf());
app.disable('x-powered-by');
app.use(setCache);
app.use('/', express.static(`${__dirname}/www`));
app.use((req, res, next) => {
if (req.session.bubbl_chat_user_id && req.session.bubbl_chat_signedin) {
res.locals.bubbl_user = req.signedCookies['bubbl-user'];
res.locals.user_id = req.session.bubbl_chat_user_id;
res.locals.nickname = req.session.bubbl_chat_nickname;
res.locals.loggedIn = true;
}
res.locals.env = process.env.NODE_ENV;
res.locals.host = req.hostname;
console.log('nicknaaaa', req.session.bubbl_chat_nickname);
res.locals.env = process.env.NODE_ENV.trim();
res.locals.route = {
query: req.query,
params: req.params,
originalUrl: req.originalUrl,
baseUrl: req.baseUrl,
path: req.path,
};
next(); // <-- important!
});
io.use(socketSession(cookieSession));
let db;
let Chat;
Dbloader()
.then((d) => {
db = d;
Chat = new ChatServer(db);
Chat.loadData().then(() => {
// eslint-disable-next-line no-new
new SocketServer(io, Chat);
});
const exitHandler = terminate(server, db, {
coredump: false,
timeout: 500,
});
process.on('uncaughtException', exitHandler(1, 'Unexpected Error'));
process.on('unhandledRejection', exitHandler(1, 'Unhandled Promise'));
process.on('SIGTERM', exitHandler(0, 'SIGTERM'));
process.on('SIGINT', exitHandler(0, 'SIGINT'));
})
.catch((err) => {
console.error('Error loading database => ', err);
});
app.get('/', (req, res) => {
return res.render('index');
});
// Add a health check route in express
// from https://blog.heroku.com/best-practices-nodejs-errors
app.get('/_health', (req, res) => {
res.status(200).send('ok');
});
// TODO add better auth!
app.get(
'/admin',
basicAuth({
users: {
admin: 'iloveyou',
},
challenge: true,
}),
(req, res) => {
return res.render('admin');
}
);
app.get('/delete/users', async (req, res) => {
await Chat.deleteAllUsers();
return res.send('Users deleted succesfully!');
});
app.get('/api/users', async (req, res) => {
const users = await Chat.getUsers('db');
return res.status(200).json(users);
});
app.get('/api/rooms', async (req, res) => {
const rooms = await Chat.getRooms('db');
return res.status(200).json(rooms);
});
app.get('/delete/rooms', async (req, res) => {
await Chat.deleteAllRooms();
return res.send('Rooms deleted succesfully!');
});
app.get('/login', async (req, res) => {
delete req.session.target;
if (!req.query.user) {
console.log('User not logged in correctly. Try again!');
return res.redirect('/');
}
if (req.session.bubbl_chat_signedin && req.session.bubbl_chat_user_id) {
return res.redirect('/app');
}
const bubbl_username = req.signedCookies['bubbl-user'];
console.log('Bubbl username => ', bubbl_username);
const current_user = await db.users.findOne({ username: bubbl_username });
if (current_user) {
// user already exists!
req.session.bubbl_chat_signedin = true;
req.session.bubbl_chat_user_id = current_user.id;
req.session.bubbl_chat_nickname = current_user.nickname;
Chat.addUser(current_user);
return res.redirect('/app');
}
const _user_id = customAlphabet('1234567890abcdef', 6)();
const nickname = `user-${_user_id}`;
req.session.bubbl_chat_signedin = true;
req.session.bubbl_chat_user_id = _user_id;
req.session.bubbl_chat_nickname = nickname;
// This is a new user o
const u = Chat.addUser({
id: _user_id,
nickname,
bubbl_username: req.query.user || req.signedCookies['bubbl-user'],
});
try {
await db.users.insert(u);
} catch (err) {
console.error('Error saving user => ', err);
}
return res.redirect('/app');
});
function isAuth(req, res, next) {
if (!req.session.bubbl_chat_signedin && !req.session.bubbl_chat_user_id) {
return res.redirect('/?reason=not_logged_in');
}
return next();
}
app.get('/logout', (req, res) => {
if (!req.query.user) {
return res.send('User not logged out correctly!');
}
req.session = null;
res.clearCookie('bubbl-chat-session', { path: '/' });
// Here delete all the things you need to delete and inform all sockets...
console.log('User logged out successfully! => ', req.query.user);
return res.redirect('/');
});
app.get('/app#/room/:id', isAuth, async (req, res) => {
const room = await Chat.getRoomDb(req.params.id);
console.log(room);
if (!room) return res.status(404).send('Room does not exist!');
return res.render('app');
});
app.get('/app#/lobby', isAuth, (req, res) => {
return res.render('app');
});
/** For redirecting to chat room */
app.get(
'/app/room/:id',
seo.redirectToVue('/app#/room/', [{ key: 'id' }]),
async (req, res) => {
// first fetch chatroom from db, then send page back...
if (!req.params.id) return res.status(404).send('Room id not sent!');
const room = await Chat.getRoomDb(req.params.id);
if (!room)
return res
.status(404)
.send('<html><head><title>Room does not exist!</title></head></html>');
const title = `Chat in the ${room.name} room | BChat`;
const meta = seo.generateMeta(
title,
`Join other AUN students chatting in ${room.name}`,
null,
req.baseUrl + req.path,
null
);
return res.render('seo/index', { title, meta });
}
);
app.get('/get/rooms/:id', async (req, res) => {
if (!req.params.id) return res.status(404).send('Room id not sent!');
const room = await Chat.getRoomDb(req.params.id);
if (!room) return res.status(404).send('Room does not exist!');
return res.status(200).send('Room found!');
});
app.get(
'/app/lobby',
seo.redirectToVue('/app#/lobby', [{ key: null }]),
async (req, res) => {
const title = `Find a chatroom in the BChat lobby`;
const meta = seo.generateMeta(
title,
`Find a new chatroom now in the BChat lobby`,
null,
req.baseUrl + req.path,
null
);
return res.render('seo/index', { title, meta });
}
);
app.use('/app', (req, res, next) => {
return next();
});
app.get('/app', isAuth, (req, res) => {
return res.render('app');
});
app.patch('/change-nickname', isAuth, (req, res) => {
if (req.body.new_nickname) {
Chat.changeUserNickname(
req.session.bubbl_chat_user_id,
req.body.new_nickname
);
req.session.bubbl_chat_nickname = req.body.new_nickname;
return res
.status(200)
.json({ success: true, nickname: req.body.new_nickname });
}
return res.status(404).send('Missing username!');
});
app.get('/eventor-158', (req, res) => {
console.log(
`${new Date().getHours()}:${new Date().getMinutes()} Event name`,
req.query.event
);
return res.status(200).send('seen! thank you eventor!');
});
const port = process.env.PORT || 3100;
if (process.env.NODE_ENV.trim() === 'dev') {
// only use in development
app.use(errorHandler());
} else {
// Render an actual error page here :/
// eslint-disable-next-line no-unused-vars
app.use((err, req, res, next) => {
console.error(err);
return res.render('error', { error: err.message });
});
}
app.all('*', (req, res) => {
res.locals.route_name = '404';
res.render('error', { error: '404 - Page not found!' });
});
server.listen(port, () => {
console.log('Server started on port %s', port);
});