-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathserver.js
More file actions
583 lines (487 loc) · 17.7 KB
/
server.js
File metadata and controls
583 lines (487 loc) · 17.7 KB
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
const express = require('express');
const http = require('http');
const socketio = require('socket.io');
const path = require('path');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// Load .env file with explicit path
require('dotenv').config({ path: path.join(__dirname, '.env') });
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const session = require('express-session');
const MongoStore = require('connect-mongo');
const { MongoClient } = require('mongodb');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const auth = require('./auth/auth');
const adminRoutes = require('./routes/adminRoutes');
// Parse process.env.operatingHours to figure out start hour and end hour
const operatingHoursString = process.env.operatingHours;
if (!operatingHoursString) {
console.error('Error: operatingHours environment variable not set');
process.exit(1);
}
const matches = /(\d{1,2})(am|pm)\s*[-–—]\s*(\d{1,2})(am|pm)/i.exec(operatingHoursString);
const startHour = parseInt(matches[1]);
const startAmPm = matches[2];
const endHour = parseInt(matches[3]);
const endAmPm = matches[4];
function hourWithAmPmTo24H(hour, amPm) {
if (amPm == 'pm' && hour != 12) {
return hour + 12;
} else if (amPm == 'am' && hour == 12) {
return 0;
}
return hour;
}
const START_HOUR = hourWithAmPmTo24H(startHour, startAmPm);
const END_HOUR = hourWithAmPmTo24H(endHour, endAmPm);
// Create a shared MongoDB client for better performance
let mongoClient = null;
async function getMongoClient() {
if (!mongoClient) {
const mongoUrl = process.env.MONGO_PUBLIC_URL || process.env.DATABASE_URL;
mongoClient = new MongoClient(mongoUrl, {
maxPoolSize: 10,
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000,
});
await mongoClient.connect();
}
return mongoClient;
}
// Simple in-memory cache for user sessions to reduce DB calls
const userCache = new Map();
const CACHE_TTL = 5 * 60 * 1000; // 5 minutes
///////////////////////////////////////////////////////////////////////
// Passport Config
///////////////////////////////////////////////////////////////////////
app.use(bodyParser.urlencoded({extended: true}));
// app.use(session(
// { secret: 'secret',
// resave: true,
// saveUninitialized: true,
// cookie: { maxAge : 3600000 * 24 } // 24 hours
// }));
// Use DATABASE_URL as fallback if MONGO_PUBLIC_URL is not available
const mongoUrl = process.env.MONGO_PUBLIC_URL || process.env.DATABASE_URL;
// Session configuration with fallback
let sessionConfig = {
name: 'sessionId',
secret: 'secret',
resave: false,
saveUninitialized: false,
cookie: { maxAge : 3600000 * 24 } // 24 hours
};
if (mongoUrl) {
try {
sessionConfig.store = MongoStore.create({
mongoUrl: mongoUrl,
touchAfter: 24 * 3600 // lazy session update
});
} catch (error) {
// Fall back to memory session store on error
}
}
app.use(session(sessionConfig));
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy((username, password, done) => {
try {
auth.strategy(username, password, (err, user) => {
done(err, user);
});
} catch (error) {
done(error);
}
}));
passport.serializeUser((user, done) => {
try {
auth.serialize(user, (err, result) => {
done(err, result);
});
} catch (error) {
done(error);
}
});
passport.deserializeUser(async (id, done) => {
try {
// Check cache first
const cached = userCache.get(id);
if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
return done(null, cached.user);
}
// If not in cache or expired, fetch from database
const client = await getMongoClient();
const db = client.db();
const adminsCollection = db.collection('admins');
const user = await adminsCollection.findOne({ username: id });
if (user) {
const userObj = { id: user._id, username: user.username, email: user.email, role: user.role };
// Cache the user
userCache.set(id, {
user: userObj,
timestamp: Date.now()
});
done(null, userObj);
} else {
// Remove from cache if user not found
userCache.delete(id);
done(null, false);
}
} catch (error) {
done(error);
}
});
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// parse application/json
app.use(bodyParser.json());
// initialize admin id array
let admins = [];
let currentConversations = [];
let unsentMessageBuffer = {};
function removeConversation(room) {
currentConversations = currentConversations.filter((ele) => {
return ele.room != room;
});
delete unsentMessageBuffer[room];
}
///////////////////////////////////////////////////////////////////////
// Server Configuration
///////////////////////////////////////////////////////////////////////
// Trust proxy for Railway deployment
app.set('trust proxy', 1);
// Force HTTPS only when explicitly enabled (not for local development)
const forceHttps = process.env.FORCE_HTTPS === 'true';
if (forceHttps) {
app.use((req, res, next) => {
if (!req.secure) {
return res.redirect(301, 'https://' + req.headers.host + req.url);
}
next();
});
}
///////////////////////////////////////////////////////////////////////
// Routes
///////////////////////////////////////////////////////////////////////
// Original login route with MongoDB lookup
app.post('/admin/login', async (req, res, next) => {
const { username, password } = req.body;
try {
// Direct MongoDB authentication instead of using auth.js
const client = await getMongoClient();
const db = client.db();
const adminsCollection = db.collection('admins');
const user = await adminsCollection.findOne({ username });
if (!user) {
// Check if it's an AJAX request or form submission
if (req.xhr || req.headers.accept?.indexOf('json') > -1) {
return res.status(401).json({ ok: false, error: 'Invalid credentials' });
} else {
return res.redirect('/admin/login?error=invalid');
}
}
const bcrypt = require('bcrypt');
const isValid = await bcrypt.compare(password, user.password);
if (!isValid) {
// Check if it's an AJAX request or form submission
if (req.xhr || req.headers.accept?.indexOf('json') > -1) {
return res.status(401).json({ ok: false, error: 'Invalid credentials' });
} else {
return res.redirect('/admin/login?error=invalid');
}
}
// Login the user
req.logIn(user, (err) => {
if (err) {
if (req.xhr || req.headers.accept?.indexOf('json') > -1) {
return res.status(500).json({ ok: false, error: 'Login error' });
} else {
return res.redirect('/admin/login?error=server');
}
}
// Check if it's explicitly an AJAX request
const isAjax = req.xhr ||
req.headers['x-requested-with'] === 'XMLHttpRequest' ||
(req.headers.accept && req.headers.accept.includes('application/json'));
if (isAjax) {
return res.json({ ok: true, user: { id: user._id, username: user.username, email: user.email } });
} else {
// Always redirect for form submissions
return res.redirect('/admin');
}
});
} catch (error) {
if (req.xhr || req.headers.accept?.indexOf('json') > -1) {
return res.status(500).json({ ok: false, error: 'Authentication error' });
} else {
return res.redirect('/admin/login?error=server');
}
}
});
app.use('/admin', adminRoutes);
app.get('/', (req, res) => {
res.sendFile('index.html', {root: path.join(__dirname, 'public')});
});
var ISAVAILABLE = (process.env.ISAVAILABLE === 'true' ? true : (process.env.ISAVAILABLE === 'false' ? false : true));
const DOAVAILCHECK = (process.env.DOAVAILCHECK === 'true' ? true : false);
app.get('/available', (req, res) => {
let now = new Date();
const standardAvailability = (now.getHours() < END_HOUR || now.getHours() >= START_HOUR);
const isAvailable = !DOAVAILCHECK || (ISAVAILABLE && standardAvailability);
res.json({isAvailable: isAvailable});
});
app.get('/keepalive', (req, res) => {
res.sendStatus(200);
});
app.get('/hours', (req, res) => {
res.json({hours: process.env.operatingHours});
});
app.post('/setavailable', adminRoutes.ensureAuthenticated, (req, res) => {
ISAVAILABLE = req.body.isAvailable;
res.sendStatus(200);
});
app.get('/css/:file', (req, res) => {
res.sendFile(req.params.file, {root: path.join(__dirname, 'public', 'css')});
});
app.get('/javascript/:file', (req, res) => {
res.sendFile(req.params.file, {root: path.join(__dirname, 'public', 'javascript')});
});
app.get('/img/:file', (req, res) => {
res.sendFile(req.params.file, {root: path.join(__dirname, 'public', 'img')});
});
app.get('/img/icons/:icon', (req, res) => {
res.sendFile(req.params.icon, {root: path.join(__dirname, 'public', 'img', 'icons')});
});
app.get('/audio/:file', (req, res) => {
res.sendFile(req.params.file, {root: path.join(__dirname, 'public', 'audio')});
});
app.post('/admin', adminRoutes.ensureAuthenticated, (req, res) => {
admins.push(req.body.admin);
res.json(currentConversations);
});
app.post('/admin/removeConversation', adminRoutes.ensureAuthenticated, (req, res) => {
removeConversation(req.body.userId);
res.sendStatus(200);
});
///////////////////////////////////////////////////////////////////////
// Sockets
///////////////////////////////////////////////////////////////////////
let overflow_id = 0;
let icons = [
'bear', 'ox', 'flamingo', 'panda', 'giraffe', 'raccoon', 'chimpanzee', 'bullhead',
'doe', 'mandrill', 'badger', 'squirrel', 'rhino', 'dog', 'monkey', 'lynx',
'brownbear', 'marmoset', 'funnylion', 'deer', 'zebra', 'meerkat', 'elephant', 'cat',
'hare', 'puma', 'owl', 'antelope', 'lion', 'fox', 'wolf', 'hippo'
];
let reconnectionTimeouts = {};
io.on('connection', (socket) => {
// PHASE I
socket.on('user connect', () => {
if (icons.length == 0) {
overflow_id++;
socket.icon = overflow_id.toString();
} else {
socket.icon = icons.splice(Math.floor(Math.random() * icons.length), 1)[0];
}
for (let admin of admins) {
socket.broadcast.to(admin).emit('user waiting', socket.id, socket.icon);
}
currentConversations.push(
{ user: socket.id,
icon: socket.icon,
room: socket.id,
active: false,
everAccepted: false,
connected: true,
connected_admin: null,
messages: [],
readTo: new Date(0)
});
});
// PHASE II
// Admin Accepts User:
// 1. put admin in same room as user
// 2. tell user we joined
// 3. tell other admins to remove user from their lists
socket.on('accept user', (user_room_id) => {
// TODO what if user_room_id no longer exists
socket.join(user_room_id);
for (let conversation of currentConversations) {
if (conversation.room === user_room_id) {
conversation.active = true;
// everAccepted will never be set to false again
conversation.everAccepted = true;
conversation.connected_admin = socket.id;
}
}
socket.broadcast.to(user_room_id).emit('invalid');
socket.broadcast.to(user_room_id).emit('admin matched');
for (let admin of admins) {
socket.broadcast.to(admin).emit('user matched', user_room_id);
}
});
// PHASE III
// receive chat message from admin or user, and send it to a specific user's room
socket.on('chat message', (data) => {
// Add message to conversation
for (let conversation of currentConversations) {
if (conversation.room === data.room) {
conversation.messages.push(data);
if (data.role == 'user') {
if (conversation.connected_admin === null) {
// no specific admin connected, update all admins with the new message
admins.forEach((adminId) => {
socket.broadcast.to(adminId).emit('chat message', data);
});
} else {
// send message to the specific connected admin
socket.broadcast.to(data.room).emit('chat message', data);
}
} else {
if (conversation.connected) {
socket.broadcast.to(data.room).emit('chat message', data);
} else {
if (typeof unsentMessageBuffer[data.room] === 'undefined') {
unsentMessageBuffer[data.room] = [];
}
unsentMessageBuffer[data.room].push(data);
}
}
}
}
});
// PHASE IV
// User Disconnects:
socket.on('disconnect', () => {
let socket_is_user = false;
// iterate through all the current conversations to figure out who's disconnecting
for (let conversation of currentConversations) {
if (conversation.user === socket.id) {
// disconnecting socket was a user
/*
* If we know the disconnecting socket was a user in a room,
* use conversation.room as the original socketid that admins are tracking.
* Let room know if user has been accepted, else tell all admins.
*/
if (conversation.everAccepted || conversation.connected_admin != null) {
// notify anyone else in the room the user left
io.to(conversation.room).emit('user disconnect', conversation.room);
} else {
// user was never accepted so let admins all admins know
for (let admin of admins) {
io.to(admin).emit('user disconnect', conversation.room);
}
}
socket_is_user = true;
conversation.connected = false;
// delete the room after a delayed time
reconnectionTimeouts[conversation.room] = setTimeout(() => {
// tell anyone connected to room the user didnt reconnect in the allowed time
io.to(conversation.room).emit('user gone for good', conversation.room);
// remove related objects from data structs
delete reconnectionTimeouts[conversation.room];
removeConversation(conversation.room);
let room = io.sockets.adapter.rooms[conversation.room];
if (room) {
for (let id in room.sockets) {
io.sockets.connected[id].leave(conversation.room);
}
}
// recycle icon
if (typeof socket.icon !== 'undefined' && isNaN(parseInt(socket.icon))) {
icons.push(socket.icon);
}
}, process.env.DISCONNECT_GRACE_PERIOD || 60 * 60000); // 60 minutes
} else if (conversation.connected_admin === socket.id) {
// disconnecting socket was an admin
conversation.connected_admin = null;
conversation.active = false;
// let other admins pick up the conversation
for (let admin of admins) {
socket.broadcast.to(admin).emit('user unmatched', conversation);
}
}
}
// on top of notifying any connected users their admin is gone,
// remove the admin from the related admins data structs
if (!socket_is_user) {
for (let i = 0; i < admins.length; i++) {
if (admins[i] == socket.id) {
admins.splice(i, 1);
}
}
}
});
socket.on('user reconnect', (old_room_id) => {
let foundUser = false;
for (let conversation of currentConversations) {
if (conversation.room === old_room_id) {
clearTimeout(reconnectionTimeouts[conversation.room]);
delete reconnectionTimeouts[conversation.room];
foundUser = true;
socket.join(conversation.room);
conversation.user = socket.id;
conversation.connected = true;
socket.emit('reconnected with old socket id');
if (conversation.connected_admin === null) {
// no specific admin connected, update all admins with the new message
admins.forEach((adminId) => {
socket.broadcast.to(adminId).emit('user reconnect', conversation.room);
});
} else {
// send message to the specific connected admin
socket.broadcast.to(conversation.room).emit('user reconnect', conversation.room);
}
if (conversation.everAccepted == true) {
socket.emit('admin matched');
}
if (typeof unsentMessageBuffer[conversation.room] !== 'undefined') {
for (let message of unsentMessageBuffer[conversation.room]) {
socket.emit('chat message', message);
}
unsentMessageBuffer[conversation.room] = [];
}
}
}
if (!foundUser) {
socket.emit('invalid old socket id');
}
});
//User Typing Event:
socket.on('typing', (data) => {
let receiver = data['room'];
socket.broadcast.to(receiver).emit('typing', {room: receiver});
});
socket.on('stop typing', (data) => {
let receiver = data['room'];
socket.broadcast.to(receiver).emit('stop typing', {room: receiver});
});
socket.on('read to timestamp', (data) => {
currentConversations.forEach((conv) => {
if (conv.room === data.room) {
conv.readTo = data.ts;
if (conv.connected_admin === null) {
admins.forEach((adminId) => {
socket.broadcast.to(adminId).emit('read to timestamp', data);
});
} else {
socket.broadcast.to(data.room).emit('read to timestamp', data);
}
}
});
});
socket.on('sound on', () => {
socket.emit('sound on');
});
});
server.listen(process.env.PORT || 3000, () => {
console.log('Node app is running on port 3000');
});
module.exports = app;
module.exports.admins = admins;
module.exports.currentConversations = currentConversations;
module.exports.unsentMessageBuffer = unsentMessageBuffer;