forked from vck3000/ProAvalon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
380 lines (297 loc) · 9.41 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
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
//=====================================
//INITIALISATION
//=====================================
var express = require("express"),
app = express(),
mongoose = require("mongoose"),
bodyParser = require("body-parser"),
methodOverride = require("method-override"),
User = require("./models/user"),
passport = require("passport"),
LocalStrategy = require("passport-local"),
passportSocketIo = require("passport.socketio"),
cookieParser = require('cookie-parser'),
flash = require("connect-flash")
var port = process.env.PORT || 80;
var dbLoc = process.env.DATABASEURL || "mongodb://localhost/TheNewResistanceUsers";
// console.log(process.env.DATABASEURL);
// mongoose.connect("mongodb://localhost/TheNewResistanceUsers");
mongoose.connect(dbLoc);
// mongodb://127.0.0.1/TheNewResistanceUsers
//mongodb://<dbuser>:<dbpassword>@ds131698.mlab.com:31698/playavalon
var session = require("express-session");
var MongoDBStore = require('connect-mongodb-session')(session);
var store = new MongoDBStore({
// uri: 'mongodb://localhost/TheNewResistanceUsers',
// uri: 'mongodb://127.0.0.1/TheNewResistanceUsers',
uri: dbLoc,
collection: 'mySessions'
});
// Catch errors
store.on('error', function (error) {
assert.ifError(error);
assert.ok(false);
});
//authentication
var secretKey = process.env.MY_SECRET_KEY || "MySecretKey";
app.use(session({
secret: secretKey,
resave: false,
saveUninitialized: false,
store: store
}));
app.use(flash());
//res.locals variables
app.use(function (req, res, next) {
res.locals.currentUser = req.user;
// headerActive default should be nothing, otherwise specify in the routes index.js file
res.locals.headerActive = " ";
res.locals.error = req.flash("error");
res.locals.success = req.flash("success");
next();
});
//HTTPS REDIRECT
// console.log("b");
// console.log(process.env.MY_PLATFORM);
var platform = process.env.MY_PLATFORM || "local";
if(platform === "online" || platform === "staging"){
app.use(function(request, response, next){
// console.log("A");
if(request.headers["x-forwarded-proto"] !== "https"){
// console.log("redirect to https");
// console.log(request.headers.host);
// console.log(request.hostname);
// console.log(request.url);
// console.log("https://" + request.hostname + request.url)
response.redirect("https://" + request.hostname + request.url);
}
else{
next();
}
});
}
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.set("view engine", "ejs");
//if the production site, then use a cache that lasts for 30 mins.
if(platform === "online"){
app.use(express.static("assets", {maxAge: 1800000})); //expires in 30 minutes.
}
else{
app.use(express.static("assets")); //expires in 30 minutes.
}
// var path = require('path');
// app.use(express.static(path.join(__dirname, 'assets'), { maxAge: '2 days' }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride("_method"));
var indexRoutes = require("./routes/index");
app.use(indexRoutes);
var forumRoutes = require("./routes/forum");
app.use("/forum", forumRoutes);
var profileRoutes = require("./routes/profile");
app.use("/profile", profileRoutes);
// seedDB();
//start server listening
var IP = process.env.IP || "192.168.1.66";
// var server = app.listen(port, IP , function(){
var server = app.listen(port, function () {
console.log("Server has started on " + IP + ":" + port + "!");
});
//=====================================
//SOCKETS
//=====================================
var socket = require("socket.io");
var io = socket(server),
passportSocketIo = require("passport.socketio");
require("./sockets/sockets")(io);
io.use(passportSocketIo.authorize({
cookieParser: cookieParser, //optional your cookie-parser middleware function. Defaults to require('cookie-parser')
// key: 'express.sid', //make sure is the same as in your session settings in app.js
secret: secretKey, //make sure is the same as in your session settings in app.js
store: store, //you need to use the same sessionStore you defined in the app.use(session({... in app.js
// success: onAuthorizeSuccess, // *optional* callback on success
// fail: onAuthorizeFail, // *optional* callback on fail/error
passport: passport
}));
//REMOVE THIS SOON AFTER UPLOADING TO SERVER ONCE
// User.find({}).populate("notifications").exec(function(err, foundUsers){
// // for(var i = 0; i < foundUsers.length; i++){
// // console.log(foundUsers.username);
// // }
// console.log(typeof(foundUsers));
// for(var key in foundUsers){
// if(foundUsers.hasOwnProperty(key)){
// console.log(foundUsers[key].username);
// console.log("key: " + key);
// foundUsers[key].usernameLower = foundUsers[key].username.toLowerCase();
// foundUsers[key].save();
// }
// }
// });
// if(platform === "local"){
// var testRoleStats = {
// "5p": {
// "merlin": {
// "wins": 2
// },
// "percival": {
// "losses": 2
// },
// "assassin": {
// "losses": 1
// },
// "morgana": {
// "losses": 2
// },
// "spy": {},
// "resistance": {
// "losses": 2,
// "wins": 1
// }
// },
// "8p": {
// "spy": {
// "wins": 1,
// "losses": 0
// },
// "assassin": {
// "wins": 1,
// "losses": 0
// }
// },
// "7p": {
// "resistance": {
// "wins": 1,
// "losses": 0
// },
// "merlin": {
// "wins": 0,
// "losses": 1
// }
// },
// "6p": {
// "resistance": {
// "wins": 3,
// "losses": 1
// },
// "merlin": {
// "wins": 1,
// "losses": 0
// },
// "assassin": {
// "wins": 1,
// "losses": 1
// },
// "morgana": {
// "wins": 0,
// "losses": 2
// }
// }
// };
// var User = require("./models/user");
// User.findOne({username: "123"}).exec(function(err, foundUser){
// foundUser.roleStats = testRoleStats;
// foundUser.save();
// console.log("test");
// });
// }
//RESTORING THE TOTAL GAMETIME PLAYED. REMOVE THIS SECTION AFTER ONE UPLOAD TO THE SERVER!!
//but if u dont remove it its still ok, doesn't break anything. itll just update every time it restarts
// var gameRecord = require("./models/gameRecord");
// var peopleTotalTime = {};
// var arrayUsernamesTimePlayed = [];
// var arrayTimePlayed = [];
// gameRecord.find({}, function(err, gameRecords){
// if(err){console.log(err);}
// else{
// console.log("c");
// gameRecords.forEach(function(record){
// var gameDuration = new Date(record.timeGameFinished.getTime() - record.timeGameStarted.getTime());
// console.log("Duration: ");
// console.log(gameDuration);
// console.log("Duration getTime: ");
// console.log(gameDuration.getTime());
// record.spyTeam.forEach(function(spyPlayer){
// if(!peopleTotalTime[spyPlayer.toLowerCase()]){
// peopleTotalTime[spyPlayer.toLowerCase()] = new Date(gameDuration.getTime());
// }
// else{
// peopleTotalTime[spyPlayer.toLowerCase()] = new Date(peopleTotalTime[spyPlayer.toLowerCase()].getTime() + gameDuration.getTime());
// }
// });
// record.resistanceTeam.forEach(function(resPlayer){
// if(!peopleTotalTime[resPlayer.toLowerCase()]){
// peopleTotalTime[resPlayer.toLowerCase()] = new Date(gameDuration.getTime());
// }
// else{
// peopleTotalTime[resPlayer.toLowerCase()] = new Date(peopleTotalTime[resPlayer.toLowerCase()].getTime() + gameDuration.getTime());
// }
// });
// });
// for(var key in peopleTotalTime){
// if(peopleTotalTime.hasOwnProperty(key)){
// // console.log("key");
// // console.log(key);
// // if(key === 'hakha3'){
// arrayUsernamesTimePlayed.push(key);
// arrayTimePlayed.push(peopleTotalTime[key]);
// }
// }
// // for(var i = 0; i < arrayUsernamesTimePlayed.length; i++){
// // User.findOne({usernameLower: arrayUsernamesTimePlayed[i]}).populate("notifications").exec(async function(err, user){
// // if(err){console.log(err);}
// // else{
// // // console.log(arrayUsernamesTimePlayed[i]);
// // // console.log("time played: ");
// // // console.log(arrayTimePlayed[i]);
// // console.log(i);
// // // user.totalTimePlayed = arrayTimePlayed[i];
// // // user.save();
// // }
// // });
// // }
// console.log("DONE: ");
// console.log(arrayUsernamesTimePlayed);
// console.log(arrayTimePlayed);
// nextTest(0);
// }
// });
// function nextTest(i){
// if(i === arrayUsernamesTimePlayed.length){
// return;
// }
// User.findOne({usernameLower: arrayUsernamesTimePlayed[i]}).populate("notifications").exec(async function(err, user){
// if(err){console.log(err);}
// else{
// console.log(arrayUsernamesTimePlayed[i]);
// console.log("time played: ");
// console.log(arrayTimePlayed[i]);
// console.log(i);
// user.totalTimePlayed = arrayTimePlayed[i];
// user.save();
// nextTest(i+1);
// }
// });
// }
//=====================================
//MIDDLEWARE
//=====================================
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next();
}
// console.log("User is not logged in");
res.redirect("/");
}
function escapeText(str) {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
.replace(/"/g, '"')
.replace(/(?:\r\n|\r|\n)/g, ' <br>');
};