This repository was archived by the owner on May 7, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
223 lines (173 loc) · 5.74 KB
/
app.js
File metadata and controls
223 lines (173 loc) · 5.74 KB
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
'use-strict';
var cookieParser = require('cookie-parser');
var csrf = require('csurf');
var express = require('express');
var session = require('express-session');
var expressValidator = require('express-validator');
var flash = require('express-flash');
var favicon = require('serve-favicon');
var path = require('path');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var passport = require('passport');
var fs = require('fs');
var methodOverride = require('method-override');
var helmet = require('helmet');
var errorHandler = require('errorhandler');
var debug = require('debug')('http');
//Load ENV vars from .env
if ((process.env.NODE_ENV || 'development') === 'development') {
require('dotenv').config();
}
var utils = require('./config/utils'),
chalk = require('chalk'),
config = require('./config/config');
// Bootstrap db connection
mongoose.connect(config.db.uri);
var db = mongoose.connection;
// Globbing model files
utils.getGlobbedFiles('./models/**/*.js').forEach(function(modelPath) {
require(path.resolve(modelPath));
});
require('./config/passport')();
var app = express();
//Load ENV vars from .env
if ((process.env.NODE_ENV || 'development') === 'development') {
app.use(morgan('dev'));
// Turn off caching in development
// This sets the Cache-Control HTTP header to no-store, no-cache,
// which tells browsers not to cache anything.
app.use(helmet.noCache());
// Jade options: Don't minify html, debug intrumentation
app.locals.pretty=true;
app.locals.compileDebug=true;
}
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.set('etag', true);
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
// If you want to simulate DELETE and PUT
// in your app you need methodOverride.
app.use(methodOverride());
app.use(session(
config.session
));
// use passport session
app.use(passport.initialize());
app.use(passport.session());
app.use(cookieParser());
// Security Settings
app.disable('x-powered-by'); // Don't advertise our server type
app.use(csrf({cookie: true})); // Prevent Cross-Site Request Forgery
app.use(helmet()); // frameguard, hide powered by, ienoopen, nosniff, xssfilter
app.use(bodyParser.json());
// Keep user, csrf token
app.use(function (req, res, next) {
res.locals.user = req.user;
res.locals._csrf = req.csrfToken();
next();
});
app.use(flash());
// Dynamically include routes (via controllers)
fs.readdirSync('./controllers').forEach(function (file) {
if (file.substr(-3) === '.js') {
var route = require('./controllers/' + file);
route.controller(app);
}
});
// Body parsing middleware supporting
// JSON, urlencoded, and multipart requests.
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// Easy form validation!
// This line must be immediately after bodyParser!
app.use(expressValidator());
app.locals.application = config.app.title;
app.locals.moment = require('moment');
/**
* Error Handling
*/
// If nothing responded above we will assume a 404
// (since no routes responded or static assets found)
// Tests:
// $ curl http://localhost:3000/notfound
// $ curl http://localhost:3000/notfound -H "Accept: application/json"
// $ curl http://localhost:3000/notfound -H "Accept: text/plain"
// Handle 404 Errors
app.use(function (req, res, next) {
res.status(404);
debug('404 Warning. URL: ' + req.url);
// Respond with html page
if (req.accepts('html')) {
res.render('error/404', { url: req.url });
return;
}
// Respond with json
if (req.accepts('json')) {
res.send({ error: 'Not found!' });
return;
}
// Default to plain-text. send()
res.type('txt').send('Error: Not found!');
});
// True error-handling middleware requires an arity of 4,
// aka the signature (err, req, res, next).
// Handle 403 Errors
app.use(function (err, req, res, next) {
if (err.status === 403) {
res.status(err.status);
debug('403 Not Allowed. URL: ' + req.url + ' Err: ' + err);
// Respond with HTML
if (req.accepts('html')) {
res.render('error/403', {
error: err,
url: req.url
});
return;
}
// Respond with json
if (req.accepts('json')) {
res.send({ error: 'Not Allowed!' });
return;
}
// Default to plain-text. send()
res.type('txt').send('Error: Not Allowed!');
} else {
// Since the error is not a 403 pass it along
return next(err);
}
});
// Production 500 error handler (no stacktraces leaked to public!)
if (app.get('env') === 'production') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
debug('Error: ' + (err.status || 500).toString().red.bold + ' ' + err);
res.render('error/500', {
error: {} // don't leak information
});
});
}
// Development 500 error handler
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
debug('Error: ' + (err.status || 500).toString().red.bold + ' ' + err);
res.render('error/500', {
error: err
});
});
// Final error catch-all just in case...
app.use(errorHandler());
}
module.exports = app;
// Logging initialization
console.log('--');
console.log(chalk.green('Environment:\t\t\t' + process.env.NODE_ENV));
console.log(chalk.green('Port:\t\t\t\t' + config.port));
console.log(chalk.green('Database:\t\t\t' + config.db.uri));
console.log('--');