forked from bdgio/msol-site
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.js
More file actions
200 lines (171 loc) · 4.89 KB
/
middleware.js
File metadata and controls
200 lines (171 loc) · 4.89 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
const _ = require('underscore');
const env = require('./lib/environment');
const util = require('./lib/util');
const log = require('./lib/logger');
const express = require('express');
const flash = require('connect-flash');
const mailMiddleware = require('./middlewares/mail');
exports.cookieParser = function () {
var secret = env.get('secret');
return express.cookieParser(secret);
};
exports.setLocals = function setLocals() {
return function (req, res, next) {
req.siteUrl = res.locals.siteUrl = env.fullUrl('/');
req.ga = res.locals.ga = env.ga();
return next();
}
};
exports.logger = function () {
return function (req, res, next) {
const startTime = new Date();
log.info({
req: req
}, util.format(
'Incoming Request: %s %s',
req.method, req.url));
// this method of hijacking res.end is inspired by connect.logger()
// see connect/lib/middleware/logger.js for details.
const end = res.end;
res.end = function(chunk, encoding){
const responseTime = new Date() - startTime;
res.end = end;
res.end(chunk, encoding);
log.info({
url: req.url,
responseTime: responseTime,
res: res,
}, util.format(
'Outgoing Response: HTTP %s %s (%s ms)',
res.statusCode, req.url, responseTime));
};
return next();
};
};
exports.noFrame = function noFrame() {
return function (req, res, next) {
res.setHeader('X-Frame-Options', 'DENY');
return next();
};
};
exports.strictTransport = function strictTransport() {
function setStrictTransport(req, res, next) {
res.setHeader('Strict-Transport-Security', 'max-age=31536000');
return next();
}
function doNothing(_, _, next) {
return next();
}
return env.isHttps() ? setStrictTransport : doNothing;
};
exports.getSessionStore = function getSessionStore(env) {
const redisOpts = env.get('redis');
const memcachedOpts = env.get('memcached');
if (memcachedOpts) {
const MemcachedStore = require('connect-memcached')(express);
return new MemcachedStore(memcachedOpts);
}
const RedisStore = require('connect-redis')(express);
redisOpts.db = env.get('redis_session_db');
var store = new RedisStore(redisOpts);
store.client.on('error', function(err) {
console.error("REDIS ERROR", err);
});
return store;
};
exports.session = function (sessionStore) {
return express.session({
key: 'openbadger.sid',
store: sessionStore,
secret: env.get('secret'),
});
};
exports.cors = function cors(options) {
options = options || {};
var whitelist = parseWhitelist(options.whitelist);
return function (req, res, next) {
if (isExempt(whitelist, req.url))
res.header("Access-Control-Allow-Origin", "*");
return next();
};
};
exports.noCache = function noCache(options) {
options = options || {};
var whitelist = parseWhitelist(options.whitelist);
return function (req, res, next) {
if (!isExempt(whitelist, req.url))
res.header("Cache-Control", "no-cache");
return next();
};
};
/** Adapted from connect/lib/middleware/csrf.js */
exports.csrf = function csrf(options) {
options = options || {}
var whitelist = parseWhitelist(options.whitelist);
function getToken(req) {
return (req.body && req.body.csrf)
|| (req.query && req.query.csrf)
|| (req.headers['x-csrf-token']);
}
return function(req, res, next){
var token, val, err;
if (isExempt(whitelist, req.url))
return next();
// generate CSRF token
token = req.session._csrf || (req.session._csrf = util.uid(24));
// ignore these methods
if ('GET' === req.method ||
'HEAD' === req.method ||
'OPTIONS' === req.method)
return next();
// determine value
val = getToken(req);
// check
if (val !== token) {
log.warn(util.format('CSRF failure at %s', req.url));
return res.send(403);
}
return next();
}
};
function isExempt(whitelist, path) {
var i = whitelist.length;
while (i--) {
if (whitelist[i].test(path))
return true;
}
return false;
}
function parseWhitelist(array) {
if (!array)
return [];
return array.map(function (entry) {
if (typeof entry === 'string') {
entry = entry.replace('*', '.*?');
return RegExp('^' + entry + '$');
}
return entry;
});
}
function makeGetFlashMessages(req) {
var cached = null;
return function() {
if (!cached) {
cached = [];
['error', 'success', 'info'].forEach(function(category) {
req.flash(category).forEach(function(info) {
cached.push(_.extend({category: category}, info));
});
});
}
return cached;
};
};
exports.flash = function flashWithMessages() {
var flashMiddleware = flash();
return function(req, res, next) {
res.locals.messages = makeGetFlashMessages(req);
return flashMiddleware(req, res, next);
};
};
exports.mailHandler = mailMiddleware.mailHandler;