-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
263 lines (191 loc) · 6.59 KB
/
index.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
/* The express module is used to look at the address of the request and send it to the correct function */
var express = require('express');
var bodyParser = require('body-parser');
/* The http module is used to listen for requests from a web browser */
var http = require('http');
/* The path module is used to transform relative paths to absolute paths */
var path = require('path');
var mongoose = require('mongoose');
var usermodel = require('./user.js').getModel();
var crypto = require('crypto');
var Io = require('socket.io');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var session = require('express-session');
var fs = require('fs');
var dbAddress = process.env.MONGODB_URI || 'mongodb://127.0.0.1/fullstack';
/* Creates an express application */
var app = express();
/* Creates the web server */
var server = http.createServer(app);
var io = Io(server);
/* Defines what port to use to listen to web requests */
var port = process.env.PORT
? parseInt(process.env.PORT):
8080;
function addSockets() {
var players = {};
io.on('connection', (socket) => {
var user = socket.handshake.query.user;
if(players[user]) return;
players[user] = {
x: 0, y: 0
}
io.emit('playerUpdate', players);
io.emit('newMessage', {user: user, message: 'Entered the game'});
socket.on('disconnect', () => {
delete players[user];
io.emit('playerUpdate', players);
io.emit('newMessage', {user: user, message: 'Left the game'});
});
socket.on('message', (message) => {
io.emit('newMessage', message);
});
socket.on('playerUpdate', (player) => {
player[user] = player;
io.emit('playerUpdate', players);
});
});
}
function startServer() {
function verifyUser(username, password, callback) {
if(!username) return callback('No username given');
if(!password) return callback('No password given');
usermodel.findOne({username: username}, (err, user) => {
if(err) return callback('Error connecting to database');
if(!user) return callback('No user found.');
crypto.pbkdf2(password, user.salt, 10000, 256, 'sha256', (err, resp) => {
if(err) return callback('Error handling password');
if(resp.toString('base64') === user.password) return callback(null, user);
callback('Incorrect password');
});
});
}
addSockets();
app.use(bodyParser.json({ limit: '16mb' }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({ secret: 'rawr'}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(
{usernameField: 'username',
passwordField: 'password'},
verifyUser));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
usermodel.findById(id, function (err, user) {
done(err, user);
});
});
/* Defines what function to call when a request comes from the path '/' in http://localhost:8080 */
app.get('/form', (req, res, next) => {
/* Get the absolute path of the html file */
var filePath = path.join(__dirname, './index.html')
/* Sends the html file back to the browser */
res.sendFile(filePath);
});
app.post('/form', (req, res, next) => {
// Converting the request in an user object
var newuser = new usermodel(req.body);
// Grabbing the password from the request
var password = req.body.password;
// Adding a random string to salt the password with
var salt = crypto.randomBytes(128).toString('base64');
newuser.salt = salt;
// Winding up the crypto hashing lock 10000 times
var iterations = 10000;
crypto.pbkdf2(password, salt, iterations, 256, 'sha256', function(err, hash) {
if(err) {
return res.send({error: err});
}
newuser.password = hash.toString('base64');
// Saving the user object to the database
newuser.save(function(err) {
// Handling the duplicate key errors from database
if(err && err.message.includes('duplicate key error') && err.message.includes('userName')) {
return res.send({error: 'Username, ' + req.body.userName + 'already taken'});
}
if(err) {
return res.send({error: err.message});
}
res.send({error: null});
});
});
});
app.get('/app', (req, res, next) => {
var filePath = path.join(__dirname, './app.html');
res.sendFile(filePath);
})
app.post('/app', (req, res, next) => {
console.log(req.body);
res.send('OK');
})
app.get('/game', (req, res, next) => {
if(!req.user) return res.redirect('/login');
var filePath = path.join(__dirname, './game.html');
var fileContents = fs.readFileSync(filePath, 'utf8');
fileContents = fileContents.replace('{{USER}}', req.user.username);
res.send(fileContents);
})
app.post('/game', (req, res, next) => {
console.log(req.body);
res.send('OK');
})
app.get('/login', (req, res, next) => {
var filePath = path.join(__dirname, './login.html');
res.sendFile(filePath);
})
app.post('/login', (req, res, next) => {
passport.authenticate('local', function(err, user) {
if(err) return res.send({error: err});
req.logIn(user, (err) => {
if (err) return res.send({error: err});
return res.send({error: null});
});
})(req, res, next);
});
app.get('/space.jpg', (req, res, next) => {
var filePath = path.join(__dirname, './space.jpg');
res.sendFile(filePath);
});
app.get('/js/game.js', (req, res, next) => {
var filePath = path.join(__dirname, './js/game.js');
res.sendFile(filePath);
})
app.get('/logout', (req, res, next) => {
req.logOut();
res.redirect('/login');
});
app.get('/picture/:username', (req, res, next) => {
if (!req.user) return res.send('NOT LOGGED IN!!!');
usermodel.findOne({username: req.params.username}, function(err, user) {
if (err) return res.send(err);
try {
var imageType = user.picture.match(/^data:image\/([a-zA-Z0-9]*);/)[1];
var base64Data = user.picture.split(',')[1];
var binaryData = new Buffer(base64Data, 'base64');
res.contentType('image/' + imageType);
res.end(binaryData, 'binary');
} catch(ex) {
console.log(ex);
res.send(ex);
}
});
});
/* Defines what function to all when the server recieves any request from http://localhost:8080 */
server.on('listening', () => {
/* Determining what the server is listening for */
var addr = server.address()
, bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port
;
/* Outputs to the console that the webserver is ready to start listenting to requests */
console.log('Listening on ' + bind);
});
/* Tells the server to start listening to requests from defined port */
server.listen(port);
}
mongoose.connect(dbAddress, startServer);