forked from Vulnogram/Vulnogram
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
239 lines (197 loc) · 6.09 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
// Copyright (c) 2017 Chandan B N. All rights reserved.
const express = require('express');
const path = require('path');
const fs = require('fs');
const mongoose = require('mongoose');
const flash = require('connect-flash');
const https = require('https');
const pug = require('pug');
// TODO: don't use express-session for large-scale production use
const session = require('express-session');
const passport = require('passport');
const crypto = require('crypto');
const compress = require('compression');
const dotenv = require('dotenv').config()
if (dotenv.error) {
console.log(".env was not loaded.");
}
const conf = require('./config/conf');
const optSet = require('./models/set');
if(!process.env.NODE_ENV) {
process.env.NODE_ENV = "production";
}
mongoose.Promise = global.Promise;
mongoose.set('strictQuery', false);
mongoose.connect(conf.database, {
keepAlive: true,
}).catch(function(e){
console.log("Error"+e.message);
});
const db = mongoose.connection;
//Check connection
db.once('open', function () {
console.log('Connected to MongoDB');
});
//Check for db errors
db.on('error', function (err) {
console.error(err.message);
console.error('Check mongodb connection URL configuration. Ensure Mongodb server is running!');
});
const app = express();
var RateLimit = require('express-rate-limit');
var limiter = new RateLimit({
windowMs: 1*60*1000, // 1 minute
max: 200
});
// apply rate limiter to all requests
app.use(limiter);
app.disable('x-powered-by');
// enable compression
app.use(compress());
app.set('env', 'production');
// View engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// make conf available for pug
app.locals.conf = conf;
app.locals.pugLib = pug;
// parse urlencoded forms
app.use(express.urlencoded({
extended: true
}));
// parse application/json
app.use(express.json({limit:'16mb'}));
// serve files under public freely
app.use(express.static('public'));
// Express Session middleware
app.use(session({
secret: crypto.randomBytes(64).toString('hex'),
resave: true,
saveUninitialized: false,
cookie: {
secure: process.env.NODE_ENV == "production",
httpOnly: true
}
}));
// Passport config
require('./config/passport')(passport);
app.use(passport.initialize());
app.use(passport.session());
// Express Messages Middleware
// This shows error messages on the client
app.use(require('connect-flash')());
app.use(function (req, res, next) {
res.locals.user = req.user || null;
res.locals.startTime = Date.now();
res.locals.messages = require('express-messages')(req, res);
next();
});
// add this to route for authenticating before certain requests.
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
return next();
} else {
req.session.returnTo = req.originalUrl;
res.redirect('/users/login')
}
}
function ensureConnected(req, res, next) {
if (mongoose.connection.readyState == 1) {
return next();
} else {
req.session.returnTo = req.originalUrl;
req.flash('error', 'Database error! Ensure mongod is up and check the settings on the server.')
res.status(500);
res.render('splash', {
title: 'Vulnogram'
});
}
}
app.use(ensureConnected);
//delete return redirect path
app.use(function (req, res, next) {
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
res.setHeader('X-XSS-Protection', '1; mode=block');
res.setHeader("Access-Control-Allow-Origin", "*");// XXX investigate
res.setHeader("Access-Control-Request-Headers", "cve-api-cna,cve-api-secret,cve-api-submitter");
if (req.path != '/users/login' && req.session.returnTo) {
delete req.session.returnTo
}
next()
})
// set up routes
let users = require('./routes/users');
app.use('/users', users.public);
app.use('/users', ensureAuthenticated, users.protected);
let docs = require('./routes/doc');
app.locals.confOpts = {};
var sections = require('./models/sections.js')();
for(section of sections) {
var s = optSet(section, ['default', 'custom']);
//var s = conf.sections[section];
if(s.facet && s.facet.ID) {
app.locals.confOpts[section] = s;
let r = docs(section, app.locals.confOpts[section]);
app.use('/' + section, ensureAuthenticated, r.router);
}
}
app.use('/home/stats', ensureAuthenticated, async function(req, res, next){
var sections = [];
for(section of conf.sections){
var s = {};
try {
var s = await db.collection(section+'s').stats();
} catch (e){
};
if (s === {}) {
try {
var s = await db.collection(section).stats();
} catch (e){
};
};
sections.push({
name: section,
items: s.count,
size: s.size,
avgSize: s.avgObjSize
});
}
res.render('list',
{
docs: sections,
columns: ['name', 'items', 'size', 'avgSize'],
fields: {
'name': {
className: 'icn'
}
}
})
});
app.use(function (req, res, next) {
res.locals.confOpts = app.locals.confOpts;
next();
});
//Configuring a reviewToken in conf file allows sharing drafts with 'people who have a link containing the configurable token'
let review = require('./routes/review');
if (review.public) {
app.use('/review', express.static('public'));
app.use('/review', review.public);
}
app.use('/review', ensureAuthenticated, review.protected);
if(conf.customRoutes) {
for(r of conf.customRoutes) {
app.use(r.path, require(r.route));
}
}
app.get('/', function (req, res, next) {
res.redirect(conf.homepage? conf.homepage : '/home');
});
if(conf.httpsOptions) {
https.createServer(conf.httpsOptions, app).listen(conf.serverPort, conf.serverHost, function () {
console.log('Server started at https://' + conf.serverHost + ':' + conf.serverPort);
});
} else {
app.listen(conf.serverPort, conf.serverHost, function () {
console.log('Server started at http://' + conf.serverHost + ':' + conf.serverPort);
});
}