forked from eloquence/lib.reviews
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
222 lines (183 loc) · 6.87 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
'use strict';
// External dependencies
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const serveIndex = require('serve-index');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const i18n = require('i18n');
const hbs = require('hbs'); // handlebars templating
const hbsutils = require('hbs-utils')(hbs);
const lessMiddleware = require('less-middleware');
const session = require('express-session');
const RDBStore = require('session-rethinkdb')(session);
const flash = require('express-flash');
const useragent = require('express-useragent');
const passport = require('passport');
const csrf = require('csurf'); // protect against request forgery using tokens
const config = require('config');
const compression = require('compression');
const WebHooks = require('node-webhooks');
// Internal dependencies
const languages = require('./locales/languages');
const reviews = require('./routes/reviews');
const actions = require('./routes/actions');
const users = require('./routes/users');
const teams = require('./routes/teams');
const pages = require('./routes/pages');
const processUploads = require('./routes/process-uploads');
const blogPosts = require('./routes/blog-posts');
const api = require('./routes/api');
const apiHelper = require('./routes/helpers/api');
const things = require('./routes/things');
const ErrorProvider = require('./routes/errors');
const debug = require('./util/debug');
// Initialize custom HBS helpers
require('./util/handlebars-helpers.js');
let initializedApp;
// Returns a promise that resolves once all asynchronous setup work has
// completed and the app object can be used.
// db is a reference to a database instance with an active connection pool.
// If not provided, we will attempt to acquire the current instance.
function getApp(db = require('./db')) {
return new Promise((resolve, reject) => {
if (initializedApp)
return resolve(initializedApp);
// Push promises into this array that need to resolve before the app itself
// is ready for use
let asyncJobs = [];
// Auth setup
require('./auth');
// i18n setup
i18n.configure({
locales: languages.getValidLanguages(),
cookie: 'locale',
autoReload: true,
updateFiles: false,
directory: "" + __dirname + "/locales"
});
// express setup
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
asyncJobs.push(new Promise(resolveJob =>
hbsutils.registerWatchedPartials(__dirname + '/views/partials', undefined, () => resolveJob())
));
app.set('view engine', 'hbs');
app.use(cookieParser());
app.use(i18n.init); // Requires cookie parser!
app.use(useragent.express()); // expose UA object to req.useragent
const store = new RDBStore(db.r, {
table: 'sessions'
});
// We do not get an error event from this module, so this is a potential
// cause of hangs during the initialization. Set DEBUG=session to debug.
asyncJobs.push(new Promise(resolve => {
debug.app('Awaiting session store initialization.');
store.on('connect', function() {
debug.app('Session store initialized.');
db.r
.table('sessions')
.wait({ timeout: 5 })
.then(resolve)
.catch(reject);
});
}));
app.use(session({
key: 'libreviews_session',
resave: true,
saveUninitialized: true,
secret: config.get('sessionSecret'),
cookie: {
maxAge: config.get('sessionCookieDuration') * 1000 * 60
},
store
}));
app.use(flash());
app.use(function(req, res, next) {
req.flashHas = (key) => {
if (!req.session || !req.session.flash || !req.session.flash[key])
return false;
else
return req.session.flash[key].length > 0;
};
next();
});
app.use(favicon(path.join(__dirname, 'static/img/favicon.ico'))); // not logged
if (config.get('logger'))
app.use(logger(config.get('logger')));
app.use('/static/downloads', serveIndex(path.join(__dirname, 'static/downloads'), {
'icons': true,
template: path.join(__dirname, 'views/downloads.html')
}));
let cssPath = path.join(__dirname, 'static', 'css');
app.use('/static/css', lessMiddleware(cssPath));
app.use('/static', express.static(path.join(__dirname, 'static')));
app.use('/robots.txt', (req, res) => {
res.type('text');
res.send('User-agent: *\nDisallow: /api/\n');
});
// Initialize Passport and restore authentication state, if any, from the
// session.
app.use(passport.initialize());
app.use(passport.session());
// API requests do not require CSRF protection (hence declared before CSRF
// middleware), but session-authenticated POST requests do require the
// X-Requested-With header to be set, which ensures they're subject to CORS
// rules. This middleware also sets req.isAPI to true for API requests.
app.use('/api', apiHelper.prepareRequest);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(compression());
let errorProvider = new ErrorProvider(app);
if (config.maintenanceMode) {
// Will not pass along control to any future routes but just render
// generic maintenance mode message instead
app.use('/', errorProvider.maintenanceMode);
}
// ?uselang=xx changes language temporarily if xx is a valid, different code
app.use('/', function(req, res, next) {
let locale = req.query.uselang || req.query.useLang;
if (locale && languages.isValid(locale) && locale !== req.locale) {
req.localeChange = { old: req.locale, new: locale };
i18n.setLocale(req, locale);
}
return next();
});
app.use('/api', api);
// Upload processing has to be done before CSRF middleware kicks in
app.use('/', processUploads);
app.use(csrf());
app.use('/', pages);
app.use('/', reviews);
app.use('/', actions);
app.use('/', things);
app.use('/', teams);
app.use('/', blogPosts);
app.use('/user', users);
// Catches 404s and serves "not found" page
app.use(errorProvider.notFound);
// Catches the following:
// - bad JSON data in POST bodies
// - errors explicitly passed along with next(error)
// - other unhandled errors
app.use(errorProvider.generic);
app.locals.webHooks = new WebHooks({
db: path.join(__dirname, 'config/webHooksDB.json')
});
Promise
.all(asyncJobs)
.then(() => {
let mode = app.get('env') == 'production' ? 'PRODUCTION' : 'DEVELOPMENT';
debug.app(`App is up and running in ${mode} mode.`);
initializedApp = app;
resolve(app);
})
.catch(error => reject(error));
});
}
module.exports = getApp;