-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
339 lines (303 loc) · 8.01 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
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
var express = require('express');
var app = express();
var path = require('path');
var cookieParser = require('cookie-parser')
var bodyParser = require('body-parser')
var exphbs = require('express-handlebars')
var expressValidator = require('express-validator')
var flash = require('connect-flash')
var session = require('express-session')
var passport = require('passport')
var LocalStrategy = require('passport-local').Strategy;
var scramble = require('./assets/scramble');
var mongo = require('mongodb');
var mongoose = require('mongoose');
let url = 'mongodb://localhost:27017/test';
mongoose.connect(url);
var db = mongoose.connection;
var server = require('http').Server(app);
var io = require('socket.io')(server);
//var routes = require('./routes/index');
var users = require('./routes/users');
var User = require('./models/user');
var Room = require('./models/room');
var getRoomInfo = (id, callback) => {
mongo.MongoClient.connect(url, (err, db) => {
var collection = db.collection('rooms');
var room = collection.findOne({_id: mongo.ObjectID(id.toString())}, (err, room) => {
if (err) throw err;
callback(room);
});
})
}
var ensureAuthenticated = (req, res, next) => {
if (req.isAuthenticated()) {
return next();
} else {
req.flash('error_msg', 'You are not logged in');
res.redirect('/users/login');
}
}
var ensureValidRoom = (req, res, next) => {
var id = req.query.id;
try {
var modifiedID = mongo.ObjectID(id.toString());
Room.getAllRooms({_id: modifiedID}, (rooms) => {
if (rooms.length == 0 ) {
req.flash('error_msg', 'The specified room does not exist.');
res.redirect('/rooms')
} else {
next();
}
})
} catch (err) {
req.flash('error_msg', 'Invalid room.')
res.redirect('/rooms')
}
}
var checkPassword = (req, res, next) => {
Room.getRoomByID(req.body.id, (room) => {
if (room.password != '') {
console.log(req.body);
Room.comparePassword(req.body.password, room.password, (err, isMatch) => {
if (err) throw err;
if (isMatch) {
next();
} else {
req.flash('error_msg', 'Incorrect password.');
res.redirect('/rooms/');
}
})
} else {
next();
}
})
}
var checkPassed = (req, res, next) => {
if (req.session['passed']) {
next();
} else {
req.flash('error_msg', 'Password invalid.');
res.redirect('/rooms/')
}
}
var hbs = exphbs.create({
defaultLayout: 'layout',
helpers: {
reverse: function(arr) {arr.reverse();},
}
})
// View Engine
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
// Body Parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
// Public folder
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true,
store: new session.MemoryStore({ reapInterval: 600 * 10 })
}))
// Passport
app.use(passport.initialize());
app.use(passport.session());
// Express Validator
app.use(expressValidator({
errorFormatter: (param, msg, value) => {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
},
customValidators: { // code from: https://maketips.net/tip/161/validate-username-available-using-express-validator
userTaken: (value) => {
return new Promise((resolve, reject) => {
User.findOne({ username: value }, (err, user) => {
if (err) throw err;
if(user == null) {
resolve();
} else {
reject();
}
});
});
},
emailTaken: (value) => {
return new Promise((resolve, reject) => {
User.findOne({ email: value }, (err, email) => {
if (err) throw err;
if(email == null) {
resolve();
} else {
reject();
}
});
});
}
}
}));
// Flash
app.use(flash());
app.use((req, res, next) => {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.user = req.user || null;
next();
})
//app.use('/', routes);
app.use('/users', users);
app.get('/', (req, res) => {
res.render('index')
})
app.get('/rooms', ensureAuthenticated, (req, res) => {
req.session['passed'] = false;
Room.getAllRooms({}, (r) => {
res.render('rooms', {rooms: r});
})
})
app.post('/rooms', (req, res) => {
var name = req.body.name;
var event = req.body.event;
var password = req.body.password;
req.checkBody('name', 'Name is required').notEmpty();
var errors = req.validationErrors();
if (errors) {
res.render('rooms', {
errors: errors
})
} else {
var newRoom = new Room({
name: name,
event: event,
password: password,
users: [],
currentRow: 0,
times: [],
currentTime: [],
})
Room.createRoom(newRoom, (err, room) => {
if (err) throw err;
var id = room._id.valueOf();
req.session['passed'] = true;
res.redirect('/rooms/play/?id=' + id);
})
}
})
var nsp = io.of('/rooms/play/')
nsp.on('connection', (socket) => {
var username, roomID = 0, event;
// when user connects to a room
socket.on('user connection', (data) => {
roomID = data[0]; username = data[1];
socket.join(roomID, (err) => {
if (err) throw err;
console.log('connected')
getRoomInfo(roomID, (room1) => {
event = room1.event;
if (room1.users.length == 0) {
Room.addUserToRoom(roomID, username, (r) => {
socket.emit('load page', r.times, r.currentTime, r.users);
nsp.in(roomID).emit('user join', username, r.users);
socket.emit('new host', username);
})
} else {
Room.addUserToRoom(roomID, username, (r) => {
socket.emit('load page', r.times, r.currentTime, r.users);
nsp.in(roomID).emit('user join', username, r.users);
})
}
})
})
})
// when user leaves a room
socket.on('disconnection', (socket) => {
delete socket;
console.log('disconnected')
Room.removeUserFromRoom(roomID, username, (r) => {
if (r.users.length == 0) {
//Room.deleteRoom(roomID, () => {});
} else {
Room.decNumUsers(roomID, (r3) => {
nsp.in(roomID).emit('new host', r.users[0].username);
nsp.in(roomID).emit('user leave', username, r.users);
if(r3.numUsers == r3.currentTime.length) {
Room.updateTimeDatabase(roomID, (r2) => {
nsp.in(roomID).emit('times', r.currentTime)
})
}
})
}
})
})
// when user chats
socket.on('chat message', (arr) => {
nsp.in(roomID).emit('chat', arr[1], arr[2]);
});
socket.on('ready', (host) => {
scramble.scramble(event, (s) => {
nsp.in(roomID).emit('new scramble', s.scramble_string)
Room.updateNumUsers(roomID, (r) => {
if(r.currentTime.length != 0) {
Room.updateTimeDatabase(roomID, (r2) => {
nsp.in(roomID).emit('times', r.currentTime);
})
}
})
});
})
socket.on('new time', (username, time, penalty) => {
Room.addTimeToRoom(roomID, username, time, penalty, (r) => {
if(r.numUsers == r.currentTime.length) {
Room.updateTimeDatabase(roomID, (r2) => {
nsp.in(roomID).emit('times', r.currentTime)
})
}
})
})
})
app.get('/rooms/play/', ensureAuthenticated, ensureValidRoom, checkPassed, (req, res) => {
var id = req.query.id;
Room.getAllRooms({_id: mongo.ObjectID(id.toString()), 'users.username': req.user.username}, (rooms) => {
if (rooms.length == 0) {
getRoomInfo(id, (r) => {
res.render('singleroom', {id: id, r: r})
});
} else {
Room.getAllRooms({}, (r) => {
res.render('rooms', {rooms: r, errors: [{msg: 'You are already in this room.'}]})
})
}
})
})
app.post('/rooms/pass/', checkPassword, (req, res) => {
req.session['passed'] = true;
res.redirect('/rooms/play/?id=' + req.body.id)
})
app.get('/api/user_data', function(req, res) {
if (req.user === undefined) {
// The user is not logged in
res.json({});
} else {
res.json({
username: req.user.username
});
}
});
server.listen(3000, () => {
console.log('listening on 3000')
scramble.initialize();
});