-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
98 lines (85 loc) · 2.57 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
'use strict';
require('dotenv').config();
const express = require('express');
const myDB = require('./connection');
const fccTesting = require('./freeCodeCamp/fcctesting.js');
const session = require('express-session');
const passport = require('passport');
const routes = require('./routes');
const auth = require('./auth.js');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
const passportSocketIo = require('passport.socketio');
const cookieParser = require('cookie-parser');
const MongoStore = require('connect-mongo')(session);
const URI = process.env.MONGO_URI;
const store = new MongoStore({ url: URI });
app.set('view engine', 'pug');
fccTesting(app); //For FCC testing purposes
app.use('/public', express.static(process.cwd() + '/public'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
cookie: { secure: false },
key: 'express.sid',
store: store
}));
app.use(passport.initialize());
app.use(passport.session());
io.use(
passportSocketIo.authorize({
cookieParser: cookieParser,
key: 'express.sid',
secret: process.env.SESSION_SECRET,
store: store,
success: onAuthorizeSuccess,
fail: onAuthorizeFail
})
);
myDB(async (client) => {
const myDataBase = await client.db('database').collection('users');
routes(app, myDataBase);
auth(app, myDataBase);
let currentUsers = 0;
io.on('connection', (socket) => {
++currentUsers;
io.emit('user', {
name: socket.request.user.name,
currentUsers,
connected: true
});
socket.on('chat message', (message) => {
io.emit('chat message', { name: socket.request.user.name, message });
});
console.log('A user has connected');
socket.on('disconnect', () => {
console.log('A user has disconnected');
--currentUsers;
io.emit('user', {
name: socket.request.user.name,
currentUsers,
connected: false
});
});
});
}).catch((e) => {
app.route('/').get((req, res) => {
res.render('pug', { title: e, message: 'Unable to login' });
});
});
function onAuthorizeSuccess(data, accept) {
console.log('successful connection to socket.io');
accept(null, true);
}
function onAuthorizeFail(data, message, error, accept) {
if (error) throw new Error(message);
console.log('failed connection to socket.io:', message);
accept(null, false);
}
http.listen(process.env.PORT || 3000, () => {
console.log('Listening on port ' + process.env.PORT);
});