-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
271 lines (229 loc) · 7.11 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
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
var express = require('express');
var events = require('events');
var http = require('http');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var rsvp = require('./routes/rsvp-routes');
var survey = require('./routes/survey');
var admin = require('./routes/admin');
var authRouter = require('./routes/auth');
var guests = require('./routes/guests');
var payments = require('./routes/payments');
var errors = require('./routes/lib/errors');
var settings = require('./routes/lib/settings');
var auth = require('./routes/lib/auth');
var sslServer = require('./routes/lib/https-server');
var stripe = require('./routes/lib/stripe');
var compression = require('compression');
var session = require('express-session');
var couchSessionStore = require('./routes/lib/couch-session-store.js');
var ee = new events.EventEmitter();
var isReady = false;
var app = express();
// config
app.set('port', process.env.PORT || 3000);
app.set('ssl-port', process.env.SSL_PORT || 4000);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// TODO: This fails if the first request to the
// server is not a domain backed by our cert.
app.use(canonicalDomain);
app.use(forceHttps);
app.use(compression());
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(auth.firstRun);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
function forceHttps(req, res, next) {
if (!sslServer.isRunning()) {
// Don't do anything if we can't do anything.
return next();
}
if(req.secure
|| req.headers['x-forwarded-proto'] === 'https'
|| req.host === "localhost") {
return next();
}
res.redirect('https://' + req.get('Host') + req.url);
};
function canonicalDomain(req, res, next) {
var settings = app.get('settings');
if (!settings) {
return next();
}
var domainName = undefined;
if (settings['domain-name'] && settings['domain-name'].value) {
domainName = settings['domain-name'].value.trim();
}
if (!domainName || req.hostname === domainName) {
return next();
}
var hostAndPort = req.get('Host');
var redirectToHost = domainName;
if (hostAndPort) {
redirectToHost = hostAndPort.replace(req.hostname, domainName);
}
var url = req.protocol + "://" + redirectToHost + req.originalUrl;
res.redirect(301, url);
};
var handleErrors = function () {
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
if (res.headersSent) {
errors.log(err);
}
else {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
}
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
if (res.headersSent) {
errors.log(err);
}
else {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
}
});
};
//-------------------------------------------------------
// Initialization
//
var appSettings = function (req, res, next) {
if (!app.get('settings')) {
settings.getAll(function (err, settingsData) {
if (err) {
errors.log(err);
return next();
}
app.set('settings', settingsData);
next();
});
}
else {
next();
}
};
var getCookieSettings = function () {
// TODO: Check settings to guess if https is running.
// Or actually figure out if https is running, and if so
// use secure cookies
var oneHour = 3600000;
var oneDay = 24 * oneHour;
var fourDays = 4 * oneDay;
var cookieSettings = {
path: '/',
httpOnly: true,
secure: false,
maxAge: fourDays
};
return cookieSettings;
};
var init = function () {
var appLocals = function (req, res, next) {
app.locals.host = req.get('Host');
app.locals.baseUrl = req.protocol + '://' + req.get('Host');
next();
};
var handleRoutes = function () {
app.use('/', routes);
app.use('/rsvp', rsvp.router(app));
app.use('/survey', survey.router(app));
app.use('/payments', payments);
app.use('/admin', admin.router(app));
app.use('/auth', authRouter);
app.use('/guests', guests.router(app))
};
var initSettingsOk = function (settings) {
var sessionSecret = settings['session-secret'].value;
var SessionStore = couchSessionStore(session);
var cookieSettings = getCookieSettings();
app.use(session({
store: new SessionStore(),
secret: sessionSecret,
cookie: cookieSettings
}));
// Stripe (Payments)
var stripeSecretKey = settings['stripe-secret-key'].value;
stripe.setApiKey(stripeSecretKey);
// Passport / Auth
if (settings["admin-access-list"]) {
auth.setAccessList(settings["admin-access-list"].value);
}
auth.attach(app);
// Load settings into app object
app.use(appSettings);
app.use(appLocals);
var gaId = settings['google-analytics'].value;
app.locals.analyticsId = gaId || 'UA-12425420-2';
handleRoutes();
handleErrors();
ready();
};
settings.init(function (err, settings) {
if (err) {
// Fatal
return errors.log(err);
}
initSettingsOk(settings);
});
}(); // <-- call now
var tryToCreateHttpsServer = function (callback) {
sslServer.create(app, callback);
};
//-------------------------------------------------------
// exports
//
var startServer = function () {
http.createServer(app).listen(app.get('port'), function () {
console.log("http server listening on port " + app.get('port'));
});
// Run an https server if we can.
sslServer.create(app, app.get('ssl-port'), function (err, message) {
if (err) {
return console.log(err);
}
console.log(message);
});
};
function ready() {
isReady = true;
ee.emit('circle-blvd-app-is-ready');
}
exports.whenReady = function (callback) {
if (isReady) {
return callback();
}
ee.once('circle-blvd-app-is-ready', function () {
callback();
});
};
exports.express = app;
exports.startServer = startServer;