-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.js
227 lines (207 loc) · 6.44 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
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const session = require('express-session');
const uid = require("uid-safe");
const flash = require('express-flash');
const config = require('config');
const passport = require('passport');
const deasync = require("deasync");
const encryptionHandler = require(__dirname + '/util/encryption-handler.js');
const thinky = require(__dirname + '/util/thinky.js');
const r = thinky.r;
const databaseUtils = require(__dirname + '/util/database-utils.js');
const RDBStore = require('session-rethinkdb')(session);
const LocalStrategy = require('passport-local').Strategy;
const LocalAPIKeyStrategy = require('passport-localapikey').Strategy;
const RememberMeStrategy = require('passport-remember-me').Strategy;
const sessionHandler = require(__dirname + '/util/session-handler.js');
const HttpStatus = require('http-status-codes');
const sessionStore = new RDBStore(r, {
browserSessionsMaxAge: 5000,
table: 'sessions'
});
const routes = require(__dirname + '/routes/index');
const api = require(__dirname + '/routes/api');
const dashboard = require(__dirname + '/routes/dashboard');
const app = express();
let sessionSecret = null;
// setup
let setupStatus = require(__dirname + '/util/setup.js')();
deasync.loopWhile(() => {
return !setupStatus;
});
databaseUtils.getSetting('sessionSecret', (error, result) => {
if (error) {
console.err(error);
process.exit(1);
}
sessionSecret = result;
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(function (req, res, next) {
res.removeHeader("x-powered-by"); // GO AWAY USELESS HEADER! (╯°□°)╯︵ ┻━┻
next();
});
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(require('node-sass-middleware')({
src: path.join(__dirname, 'public'),
dest: path.join(__dirname, 'public'),
debug: false,
indentedSyntax: false,
outputStyle: 'compressed',
sourceMap: true
}));
app.use(require('express-minify')({
js_match: /javascript/,
css_match: /stylesheets/,
uglifyJS: undefined,
cssmin: undefined,
cache: __dirname + '/cache/',
onerror: undefined
}));
app.use(express.static(path.join(__dirname, 'public')));
deasync.loopWhile(function () {
// Wait until sessionSecret is set
return !sessionSecret
});
function sessionToggle(fn) {
return (req, res, next) => {
if (req.path === '/api/upload' && req.method === 'POST') {
next();
} else {
fn(req, res, next);
}
}
}
app.use(sessionToggle(session({
secret: sessionSecret,
name: 'yanius_sesssion',
cookie: {
maxAge: 3600 * 1000, // 1 Hour
secure: config.get('httpsSupport'),
},
store: sessionStore,
resave: true,
saveUninitialized: true
})));
app.use(sessionToggle(flash()));
app.use(passport.initialize());
app.use(passport.session());
app.use(passport.authenticate('remember-me'));
app.use('/api', api);
app.use('/dashboard', dashboard);
app.use('/', routes);
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
sessionHandler.findById(id, function (err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true
},
function (req, username, password, done) {
process.nextTick(function () {
sessionHandler.findByUsername(username, function (err, user) {
if (err) return done(err);
let errorMsg = 'Invalid username or password!';
if (!user) return done(null, false, {message: errorMsg, type: 'error'});
if (!user.enabled) return done(null, false, {message: 'This user account is disabled.', type: 'error'});
if (!encryptionHandler.check(password, user.password)) {
databaseUtils.logEvent('login_failed', user ? user.id : null, req.ip, {}, () => {});
return done(null, false, {
message: errorMsg,
type: 'error'
});
}
databaseUtils.logEvent('login_successful', user ? user.id : null, req.ip, {}, () => {});
return done(null, user);
})
});
}
));
passport.use(new RememberMeStrategy(
function (token, done) {
sessionHandler.consumeRememberMeToken(token, function (err, uid) {
if (err) return done(err);
if (!uid) return done(null, false);
sessionHandler.findById(uid, function (err, user) {
if (err) return done(err);
if (!user) return done(null, false);
if (!user.enabled) return done(null, false, {message: 'This user account is disabled.', type: 'error'});
return done(null, user);
});
});
},
sessionHandler.issueToken
));
passport.use(new LocalAPIKeyStrategy(
function (apikey, done) {
sessionHandler.findByAPIKey(apikey, function (err, user) {
if (err) return done(err);
if (!user) return done(null, false, {message: 'Invalid API Key', type: 'error'});
return done(null, user);
})
}
));
/*
* catch 404 and forward to error handler
*/
app.use(function (req, res, next) {
let err = new Error('Not Found');
err.status = 404;
next(err);
});
// Error handler
if (process.env.NODE_ENV === 'development') {
/*
* Development error handler (will print stacktrace)
*/
app.use(function (err, req, res, next) {
if (res._header) return;
if (err.message === 'Invalid token') {
res.clearCookie('remember_me');
return res.redirect(path.relative(req.path, '/dashboard'));
}
console.error(err);
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err,
status: err.status
});
});
} else {
/*
* Production error handler (no stacktraces leaked to user)
*/
app.use(function (err, req, res, next) {
if (res._header) return;
if (err.message === 'Invalid token') {
res.clearCookie('remember_me');
return res.redirect(path.relative(req.path, '/dashboard'));
}
res.status(err.status || 500);
res.render('error', {
message: HttpStatus.getStatusText(res.statusCode),
error: {},
status: err.status,
title: HttpStatus.getStatusText(res.statusCode)
});
});
}
module.exports = app;