-
Notifications
You must be signed in to change notification settings - Fork 7
/
server.js
215 lines (186 loc) · 6.27 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
//include dependencies
var express = require('express');
var serveStatic = require('serve-static');
var bodyParser = require('body-parser')
var cookieParser = require('cookie-parser');
var mongo = require('mongodb').MongoClient;
var unless = require('express-unless');
var session = require('client-sessions');
var csurf = require('csurf');
//include config file
var config = require('./server.conf');
//create express server and register global middleware
var app = express();
app.use(bodyParser.json()); //to support json bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use(cookieParser());
app.use(serveStatic(__dirname + '/public')); //serve files in /public dir
//note: session stored in client-side cookie
app.use(session({
cookieName: 'session',
secret: config.sessionSecret,
duration: 60 * 60 * 1000 * 24, //internally, cookie valid for 24 hours
cookie: {
httpOnly: false,
maxAge: 1000 * 60 * 15, //cookie purged from browser after 15 minutes
}
}));
//bind to interface localhost:9080
app.listen(9080, function(){
if(process.env.NODE_ENV === undefined)
process.env.NODE_ENV = 'development';
console.log("Server running on localhost, port %d in %s mode.", this.address().port, process.env.NODE_ENV);
});
function authenticate(user, pass, req, res){
//connect to MongoDB - auth not enabled
//also, http interface enabled at http://localhost:28017/
//can bypass with query selector injection (i.e., user=admin&pass[$gt]=)
mongo.connect('mongodb://localhost:27017/users', function(err, db){
if(err){
console.log('MongoDB connection error...');
return err;
}
db.collection('collection').findOne({username: user, password: pass, isActive: true},function(err, result){
if(err){
console.log('Query error...');
return err;
}
if(result !== null){
req.session.authenticated = true;
res.redirect('/');
}
else
res.redirect('/login?user='+user);
});
});
}
var queryMongo = function(res, database, collectionName, field, value){
//connect to MongoDB - auth not enabled
//also, http interface enabled at http://localhost:28017/
mongo.connect('mongodb://localhost:27017/'+database, function(err, db){
if(err){
console.log('MongoDB connection error...');
return err;
}
//search query
var query = {}
//set key:value pair dynamically - user can define key!
query[field] = value;
//query db
db.collection(collectionName).find(query).toArray(function(err, result){
if(err){
console.log('Query error...');
return err;
}
//return array of objects matching query
res.send(result);
});
});
}
//If logged in, continue; else, redirect to index page
var isLoggedIn = function(req, res, next){
if(req.session.authenticated)
next();
else
res.redirect('/login');
}
//add express-unless to isLoggedIn
isLoggedIn.unless = unless;
//apply isLoggedIn to all routes beginning with /secure
//uses negative regex to exclude routes that don't begin with /secure
app.use(isLoggedIn.unless({path: /^(?!\/secure).*/}));
//routes
//isLoggedIn middleware applied directly to route
app.get('/', isLoggedIn, function(req, res){
res.sendFile('./index.html', {root: __dirname})
});
app.get('/about', function(req, res){
//the file ./about.html does not exist. Will return path to requested file in dev mode.
res.sendFile('./about.html', {root: __dirname})
});
app.get('/secure/invoices', function(req, res){
res.sendFile('./invoices.html', {root: __dirname}) //use vanilla HTML
});
app.get('/secure/manageInvoices', function(req, res){
res.sendFile('./manageInvoices.html', {root: __dirname}) //use vanilla HTML
});
app.get('/logout', function(req, res){
res.cookie('session', null); //tell browser to set session as null to 'invalidate' session
res.redirect('/login');
});
app.get('/login', function(req, res){
res.sendFile('./login.html', {root: __dirname})
});
app.post('/login', function(req, res){
authenticate(req.body.user, req.body.pass, req, res);
});
app.post('/secure/query', function(req, res){
queryMongo(res, 'billing', 'invoices', req.body.field, req.body.value);
});
//use csurf middleware to protect against csurf attacks - does not apply to GET requests unless ignoreMethods option is used
app.use(csurf({
cookie: true,
}));
//set XSRF-TOKEN cookie for each request
app.use(function(req, res, next){
res.cookie('XSRF-TOKEN', req.csrfToken());
next();
});
//error handler for csurf middleware
app.use(function (err, req, res, next) {
if (err.code !== 'EBADCSRFTOKEN') return next(err);
//handle CSRF token errors here
res.status(403)
res.send('form tampered with')
});
//remove invoice
app.get('/secure/removeInvoice', function(req, res){
//connect to MongoDB - auth not enabled
//also, http interface enabled at http://localhost:28017/
mongo.connect('mongodb://localhost:27017/billing', function(err, db){
if(err){
console.log(err);
res.status(500).send('Could not connect to database...');
return;
}
db.collection('invoices').remove({id: req.query.value}, function(err, record){
if(err){
console.log(err);
//XSS vector if not sanitized by $sce and used in html context via ng-bind-html
res.status(500).send('Could not remove invoice where id = ' + req.query.value);
return;
}
var numRemoved = JSON.parse(record).n;
if(numRemoved > 0)
//XSS vector if not sanitized by $sce and used in html context via ng-bind-html
res.send('Successfully removed ' + numRemoved + ' invoice where id = ' + req.query.value);
else
res.send('Unable to locate invoice where id = ' + req.query.value);
});
});
});
//add invoice
app.post('/secure/addInvoice', function(req, res){
//build invoice - inputs are not validated and invoice object is open to parameter pollution
var invoice = req.body;
//connect to MongoDB - auth not enabled
//also, http interface enabled at http://localhost:28017/
mongo.connect('mongodb://localhost:27017/billing', function(err, db){
if(err){
console.log(err);
res.status(500).send('Could not add invoice...');
return;
}
db.collection('invoices').insert(invoice, function(err, record){
if(err){
console.log(err);
res.status(500).send('Could not add invoice...');
return;
}
console.log('Added invoice: %s', JSON.stringify(record));
res.send('Invoice added successfully...');
});
});
});