-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
330 lines (272 loc) · 9.23 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
// Requirements
var express = require('express');
var app = express();
var favicon = require('serve-favicon');
var path = require('path');
require('dotenv').config(); // Requires a .env file to be located in the root directory
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const passwordHash = require('password-hash');
const exphbs = require('express-handlebars');
const helpers = require('handlebars-helpers')();
const bcrypt = require('bcryptjs');
const moment = require('moment');
const passport = require('passport');
const flash = require('express-flash');
const session = require('express-session');
const inititalisePassport = require('./config/passport');
inititalisePassport(passport);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(flash());
app.use(session({ secret: "sneakret", resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());
app.engine('handlebars', exphbs({
// Custom helpers
helpers: {
'incrementByOne': (num) => { num++; return num },
'formatDate': (date) => { return moment(date).format('DD MMMM YYYY') },
'bestScore': (games) => {
let bestGame = games.reduce((min, game) => min.score < game.score ? min : game);
return { id: bestGame.id, score: bestGame.score };
},
'truncateUsername': (name) => {
const maxLen = 45;
return (name.length > maxLen) ? `<span title="${name}">${name.substring(0, maxLen)}...</span>` : name;
}
}
}));
app.set('view engine', 'handlebars');
// Model imports
Score = require('./models/Score');
Playlist = require('./models/Playlist');
Game = require('./models/Game');
Account = require('./models/Account');
// Connect to MongoDB via Mongoose
mongoose.connect(process.env.CONNECTION_STRING, {useNewUrlParser: true}, (err) => {
if (err) throw err;
console.log("Connected to MongoDB database!");
});
var db = mongoose.connection;
// Specify public directory (to serve static files)
app.use(express.static('public'));
// Use a favicon
app.use(favicon(path.join(__dirname, 'public', 'img/favicon.png')));
// Home/about route
app.get('/', (req, res) => {
res.render('home', getSessionInfo(req));
});
// The "game"
app.get('/play', (req, res) => {
let info = getSessionInfo(req);
res.render('game', { layout: "game-layout", username: info.username, isLoggedIn: info.isLoggedIn, id: info.id });
});
app.get('/login', (req, res) => {
if (req.isAuthenticated()) return res.redirect('/');
res.render('login');
});
app.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true,
successFlash: true
}));
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
app.get('/signup', (req, res) => {
if (req.isAuthenticated()) return res.redirect('/');
req.flash('messages.success', "Account created");
res.render('signup');
});
// Account - GET (view)
app.get('/players/:id', async (req, res) => {
let info = getSessionInfo(req);
try {
info.acc = await Account.findById(req.params.id).lean();
info.games = await Score.find({ account: info.acc._id }).sort({create_date: 'desc'}).lean();
info.recentGames = info.games.slice(0, 10);
// Determines whether or not the "settings" button should be displayed
// (user must be logged in as the correct account)
info.displaySettingsButton = (req.isAuthenticated() && req.user._id === req.params.id);
} catch(err) {
console.log(err);
return res.render('404', getSessionInfo(req));
}
// This object holds statistical information about the player, e.g. worst/best game, average score, etc.
info.stats = {}
// Calculate best/avg using ALL games
if (info.games.length > 0) {
info.stats.bestGame = info.games.reduce((min, game) => min.score > game.score ? min : game);
info.stats.worstGame = info.games.reduce((min, game) => min.score < game.score ? min : game);
info.stats.avgScore = Math.round(info.games.reduce((total, next) => total + next.score, 0) / info.games.length);
info.stats.numPerfectGames = info.games.filter(game => game.score >= 25000).length;
info.stats.numPerfectRounds = 0;
// TODO: rewrite - probably not very efficient
// Calculate number of perfect rounds
info.games.forEach((game) => {
info.stats.numPerfectRounds += game.roundScores.filter((rs) => rs.roundScore >= 5000).length;
});
}
res.render('account', info);
});
// The page from which a user can manage their account details
app.get('/players/:id/settings', async (req, res) => {
let info = getSessionInfo(req);
// User is either not logged in, or logged into the wrong account
if (req.isUnauthenticated() || req.user._id !== req.params.id) {
req.flash("danger", "You are not authorised to view this page");
return res.redirect('/login');
}
try {
info.acc = await Account.findById(req.params.id).lean();
return res.render('account-settings', info);
} catch (err) {
return res.render('404', info);
}
});
// This route is accessed when a user updates their details
app.post('/players/:id/settings', async (req, res) => {
// User is either not logged in, or logged into the wrong account
if (req.isUnauthenticated() || req.user._id !== req.params.id) {
req.flash("danger", "You are not authorised to view this page");
return res.redirect('/login');
}
try {
// Update account details
await Account.updateOne({ _id: req.params.id }, {
username: req.body.username,
email: req.body.email
});
req.user.username = req.body.username;
req.flash("success", "Account details updated");
res.redirect(`/players/${req.params.id}`);
} catch (err) {
req.flash(err);
return res.render('account-settings', info);
}
});
/**
* Permanently delete a user's account and redirect to homepage. How unfortunate.
*/
app.post('/players/:id/delete', async (req, res) => {
// User is either not logged in, or logged into the wrong account
if (req.isUnauthenticated() || req.user._id !== req.params.id) {
res.sendStatus(401);
}
try {
req.logout();
await Account.deleteOne({ _id: req.params.id });
res.sendStatus(200);
} catch (err) {
console.log(err);
res.sendStatus(500);
}
});
// Account - POST
app.post('/signup/', (req, res) => {
Account.addAccount(req.body, (err) => {
if (err) return res.json(err);
req.flash("success", "Account registered - please login");
res.redirect('/login');
});
});
// High scores route
app.get('/leaderboard', (req, res) => {
const n = 25; // Number of high scores to be retrieved
let info = getSessionInfo(req);
Score.find().sort([['score', -1]]).populate('account', 'username').limit(n).lean().sort('create_date').then((scores, err) => {
if (err) throw err;
info.scores = scores;
return res.render('leaderboard', info);
});
});
// Rules page route
app.get('/rules', (req, res) => {
res.render('rules', getSessionInfo(req));
})
// Score - POST
app.post('/api/score', (req, res) => {
Score.addScore(req, (scoreId) => {
res.status(200).send({ scoreId });
});
});
// Top scores - GET
app.get('/api/score', (req, res) => {
Score.getScores((err, scores) => {
if (err) throw err;
res.json(scores);
}, parseInt(req.query.n));
});
// Playlist - GET
app.get('/api/playlist', (req, res) => {
console.log()
Playlist.getPlaylist(req.query, 0).then((pl) => {
res.send(pl);
})
.catch((err) => {
res.send(err);
});
});
// Generate new game - GET
app.get('/api/game', async (req, res) => {
try {
let game = await Game.generateGame(req.body);
return res.send(game);
} catch (error) {
return res.status(500).json(error);
}
});
// View game - GET
app.get('/games/:gameID', async (req, res) => {
var gameData = await Score.findOne().where({ game: req.params.gameID }).populate('game').populate('username, account').lean();
try {
gameData = {time: moment(gameData.create_date).format('Do of MMMM, YYYY'), ...gameData};
let info = getSessionInfo(req);
res.render('game', {gameData: JSON.stringify(gameData), layout: "game-layout", isLoggedIn: info.isLoggedIn, id: info.id, username: info.username });
} catch(err) {
console.log(err);
return res.render('404', getSessionInfo(req));
}
});
// Game - POST
app.post('/api/game/', (req, res) => {
Game.addGame(req.body, (err) => {
if (err) throw err;
console.log("Game added!");
res.json(req.body);
});
});
app.get('/api/test', (req, res) => {
res.json({testMsg: "Test successful", req, sessionInfo: getSessionInfo(req)});
});
// Error catching
app.get('/*', (req, res) => {
// API endpoint not found (via AJAX)
if (req.xhr) {
res.status(404).json({error: "Endpoint not found"});
}
// Page not found
else {
res.render('404');
}
});
function getSessionInfo(req) {
if (!req.isAuthenticated()) {
return { isLoggedIn: false }
} else {
return {
isLoggedIn: req.isAuthenticated(),
username: req.user.username,
id: req.user._id
}
}
}
// Run the web server using Express
var port = process.env.PORT || 3000;
app.listen(port, () => console.log(`The application is running on localhost:${port}!`));
// var job = schedule.scheduleJob("* * * * *", function() {
// // Playlist.getPlaylist()
// });