-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
200 lines (171 loc) · 5.78 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
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const { json: jsonParser, urlencoded: urlEncodedParser } = require('body-parser');
const flash = require('express-flash');
const session = require('express-session');
const config = require('config');
const _ = require('underscore');
const moment = require('moment');
const methodOverride = require('method-override');
const redis = require('redis');
const passport = require('passport');
const { URL } = require('url');
const OAuth2Strategy = require('passport-oauth2').Strategy;
const models = require('./lib/models');
const Intercode = require('./lib/intercode');
const permission = require('./lib/permission');
const database = require('./lib/database');
const furnitureHelper = require('./lib/furniture-helper');
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const requestsRouter = require('./routes/requests');
const furnitureRouter = require('./routes/furniture');
const reportsRouter = require('./routes/reports');
const textRouter = require('./routes/text');
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(jsonParser());
app.use(urlEncodedParser({ extended: true }));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(methodOverride(function(req){
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
// look in urlencoded POST bodies and delete it
const method = req.body._method;
delete req.body._method;
return method;
}
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
const sessionConfig = {
secret: config.get('app.sessionSecret'),
rolling: true,
saveUninitialized: true,
resave: false,
};
switch (config.get('app.sessionType')){
case 'redis': {
const RedisStore = require('connect-redis')(session);
let redisClient = null;
if (config.get('app.redisURL')){
const redisToGo = new URL(config.get('app.redisURL'));
redisClient = redis.createClient(redisToGo.port, redisToGo.hostname);
redisClient.auth(redisToGo.password);
} else {
redisClient = redis.createClient();
}
sessionConfig.store = new RedisStore({ client: redisClient });
sessionConfig.resave = true;
break;
}
case 'postgresql': {
const pgSession = require('connect-pg-simple')(session);
sessionConfig.store = new pgSession({
pool: database.pool,
tableName: 'session'
});
break;
}
}
app.use(session(sessionConfig));
app.use(flash());
app.use(function(req, res, next){
req.models = models;
next();
});
app.use(permission());
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, cb) {
cb(null, user.id);
});
passport.deserializeUser(async function(id, cb) {
try {
const user = await models.user.get(id);
cb(null, user);
} catch (err) {
cb(err);
}
});
const passportClient = new OAuth2Strategy(config.get('auth'),
async function(req, accessToken, refreshToken, profile, cb) {
try {
const user = await models.user.findOrCreate({
name: profile.name,
intercode_id: profile.id,
email: profile.email
});
req.session.accessToken = accessToken;
cb(null, user);
} catch (err) {
cb(err);
}
}
);
// as far as I can tell, passport doesn't support promise style calls, so we'll have to call
// their callback the old fashioned way
passportClient.userProfile = async function (token, cb) {
const intercode = new Intercode(token);
try {
const data = await intercode.getUser();
cb(null, data.currentUser);
} catch (err) {
cb(err);
}
};
passport.use(passportClient);
// Setup intercode connection for routes
app.use(async function(req, res, next){
if (req.session.accessToken && req.user && !req.originalUrl.match(/^\/log(in|out)/) ){
req.intercode = new Intercode(req.session.accessToken);
}
next();
});
// Set common helpers for the view
app.use(async function(req, res, next){
res.locals.config = config;
res.locals.session = req.session;
res.locals.title = config.get('app.name');
res.locals._ = _;
res.locals.moment = moment;
res.locals.humanize = furnitureHelper.humanize;
res.locals.teamMembers = furnitureHelper.teamMembers;
res.locals.activeUser = req.user;
next();
});
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/requests', requestsRouter);
app.use('/furniture', furnitureRouter);
app.use('/reports', reportsRouter);
app.use('/text', textRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
// Disabling no-unused-vars because Express cares about the arity of error handlers, so we need to
// accept the next param even though we don't use it
// eslint-disable-next-line no-unused-vars
app.use(function(err, req, res, next) {
if (err instanceof Intercode.InvalidTokenError) {
req.logout();
console.log('deleting token');
delete req.session.accessToken;
return res.redirect(req.originalUrl);
}
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;