This repository was archived by the owner on Apr 19, 2021. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
213 lines (166 loc) · 5.89 KB
/
Copy pathapp.js
File metadata and controls
213 lines (166 loc) · 5.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
201
202
203
204
205
206
207
208
209
210
211
212
213
const express = require('express');
const bodyParser = require('body-parser');
const logger = require('morgan');
const path = require('path');
const session = require('express-session');
const csurf = require('csurf');
const cors = require('express-cors');
const url = require('url');
const helmet = require('helmet');
const flash = require('connect-flash');
const passport = require('./passport');
const mongoose = require('./mongoose');
const MongoStore = require('connect-mongo')(session);
// Create a new ExpressJS server.
const app = express();
//==============================================================================
// APP CONFIG
//==============================================================================
app.use(logger('dev'));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// If we are currently trusting the proxy, then trust the first proxy.
if (process.env.CORAL_AUTH_TRUST_PROXY === 'TRUE') {
app.set('trust proxy', 1);
}
//==============================================================================
// STATIC FILES
//==============================================================================
// Serve up static files as a last resort.
app.use(express.static(path.join(__dirname, 'public')));
//==============================================================================
// APP MIDDLEWARE
//==============================================================================
const helmet_opts = {
// Only disable the frameguard in the event that the environment variable
// `CORAL_AUTH_DISABLE_FRAMEGUARD` is `TRUE`.
frameguard: !(process.env.CORAL_AUTH_DISABLE_FRAMEGUARD === 'TRUE')
}
app.use(helmet(helmet_opts));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
//==============================================================================
// SESSION MIDDLEWARE
//==============================================================================
let session_opts = {
secret: process.env.CORAL_AUTH_SESSION_SECRET,
resave: true,
httpOnly: true,
rolling: true,
saveUninitialized: true,
cookie: {
// 10 minutes for expiry.
maxAge: 600000,
// True when the root url is also SSL enabled.
secure: process.env.CORAL_AUTH_ROOT_URL.indexOf('https') === 0
},
store: new MongoStore({
// Use the already existing mongoose connection.
mongooseConnection: mongoose.connection
})
};
app.use(session(session_opts));
// Ensure that the session exists on the request.
app.use((req, res, next) => {
if (!req.session) {
return next(new Error('session not available'));
}
// Add the session expiry time onto the response locals.
res.locals.sessionExpiry = req.session.cookie.maxAge;
console.log(res.locals.sessionExpiry);
next();
});
// Add flash in after the session has been verified.
app.use(flash());
// Add CSRF validation.
app.use(csurf());
//==============================================================================
// PASSPORT MIDDLEWARE
//==============================================================================
// Setup the PassportJS Middleware.
app.use(passport.initialize());
app.use(passport.session());
//==============================================================================
// STRATEGIES
//==============================================================================
// Walk over the allowed clients and only allow the XHR from those
// hosts/schemes.
const allowedOrigins = process.env.CORAL_AUTH_ALLOWED_CLIENTS.split(' ').filter((client, i) => {
return i % 2 == 1;
}).map((client) => {
let u = url.parse(client);
u.pathname = '';
return url.format(u);
});
// Allow CORS on only the well known route.
app.use('/connect/.well-known', cors({
allowedOrigins: allowedOrigins,
methods: ['GET']
}));
// CONNECT
const connect = require('./routes/connect');
app.use('/connect', connect);
// DEMO
if (process.env.CORAL_AUTH_ENABLE_DEMO === 'TRUE') {
app.get('/demo', (req, res) => {
res.render('demo', {
env: process.env
});
});
}
//==============================================================================
// ERROR HANDLING
//==============================================================================
const ErrNotFound = new Error('Not Found');
ErrNotFound.status = 404;
// Catch 404 and forward to error handler.
app.use((req, res, next) => next(ErrNotFound));
// In the event an error has been triggered, and a session is active, kill the
// session immediatly.
app.use((err, req, res, next) => {
// If the error coming through is a not found error, then we shouldn't kill
// the session as it could just be a static asset error.
if (err === ErrNotFound) {
return next(err);
}
// At this point, we have gotten to this handler because there was an error
// in the application code that is unrelated to a not found error, so we
// should take the skiddish approach and log out the user and remove their
// session just to be sure.
if (req.session) {
// Log the user out if there is a user still on the session.
if (req.user) {
req.logout();
}
// Destroy the session if there is one.
return req.session.destroy((sessionErr) => {
if (sessionErr) {
return next(sessionErr)
}
// Forward the error onto the next handler.
return next(err);
});
}
// There was no session, so just forward the error onto the next handler.
next(err);
});
// General error handler. Respond with the message and error if we have it while
// returning a status code that makes sense.
if (app.get('env') === 'development') {
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// Production error handler no stacktraces leaked to user.
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;