-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
212 lines (192 loc) · 6.29 KB
/
index.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
'use strict';
const _isEmpty = require('lodash/isEmpty'),
_includes = require('lodash/includes'),
passport = require('passport'),
flash = require('express-flash'),
{ compileLoginPage } = require('./services/login'),
{
getAuthUrl,
getPathOrBase,
serializeUser,
deserializeUser,
getProviders
} = require('./utils'),
createSessionStore = require('./services/session-store'),
strategyService = require('./strategies'),
{ AUTH_LEVELS } = require('./constants'),
{ withAuthLevel } = require('./services/auth'),
{ setDb } = require('./services/storage'),
{ setBus } = require('./controllers/users');
/**
* determine if a route is protected
* protected routes are ?edit=true and any method other than GET or HEAD
* @param {object} req
* @returns {boolean}
*/
function isProtectedRoute(req) {
return (
!!req.query.edit
|| !_includes(req.originalUrl, '/_auth')
&& !_includes(['GET', 'HEAD'], req.method)
);
}
/**
* protect routes
* @param {object} site
* @returns {Function}
*/
function isAuthenticated(site) {
return function (req, res, next) {
if (req.isAuthenticated()) {
next(); // already logged in
} else if (req.get('Authorization')) {
// try to authenticate with api key
passport.authenticate('apikey', { session: false })(req, res, next);
} else {
req.session.returnTo = req.originalUrl; // redirect to this page after logging in
// otherwise redirect to login
res.redirect(`${getAuthUrl(site)}/login`);
}
};
}
passport.serializeUser(serializeUser);
passport.deserializeUser(deserializeUser);
/**
* the actual middleware that protects our routes, plz no hax
* @param {object} site
* @returns {function}
*/
function protectRoutes(site) {
return function (req, res, next) {
if (req.method !== 'OPTIONS' && module.exports.isProtectedRoute(req)) { // allow mocking of these for testing
module.exports.isAuthenticated(site)(req, res, next);
} else {
next();
}
};
}
/**
* middleware to show login page
* @param {object} site
* @param {array} currentProviders
* @returns {function}
*/
function onLogin(site, currentProviders) {
return function (req, res) {
const template = compileLoginPage(),
authUrl = getAuthUrl(site),
flash = req.flash();
if (flash && _includes(flash.error, 'Invalid username/password')) {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="Incorrect Credentials"');
res.end('Access denied');
// this will prompt users one more time for the correct password,
// then display the login page WITHOUT saving the basic auth credentials.
// if they hit login, it'll show the auth form again, but won't show it a
// second time if they enter the wrong info.
// note: if the user enters the correct info on the second form,
// it'll show the login page but they'll have to click login again
// (and it'll automatically log them in without having to re-enter credentials)
// note: all of the above is the default behavior in amphora, but we're
// going to use varnish to automatically redirect them back to the ldap auth
} else {
res.send(template({
path: getPathOrBase(site),
flash: flash,
currentProviders: currentProviders,
user: req.user,
logoutLink: `${authUrl}/logout`,
localAuthPath: `${authUrl}/local`
}));
}
};
}
/**
* middleware to log out. redirects to login page
* note: it goes to login page because usually users are navigating from edit mode,
* and they can't be redirected back into edit mode without logging in
* @param {object} site
* @returns {function}
*/
function onLogout(site) {
return function (req, res) {
req.logout();
res.redirect(`${getAuthUrl(site)}/login`);
};
}
/**
* There exists a case in which a user has an active session and
* is then removed as a user from a Clay instance. We must handle
* the error by re-directing the user to the login page and logging
* them out of their current session
*
* @param {Object} site
* @returns {Function}
*/
function checkAuthentication(site) {
return function (err, req, res, next) {
if (err) {
onLogout(site)(req, res);
} else {
next();
}
};
}
/**
* add current user to locals
* @param {req} req
* @param {res} res
* @param {function} next
*/
function addUser(req, res, next) {
res.locals.user = req.user;
next();
}
/**
* Initialize authentication
* @param {object} params
* @param {express.Router} params.router
* @param {object[]} params.providers (may be empty array)
* @param {object} params.site //config for the site
* @param {object} params.storage
* @returns {object[]}
*/
function init({ router, providers, store, site, storage, bus }) {
if (_isEmpty(providers)) {
return []; // exit early if no providers are passed in
}
setDb(storage);
setBus(bus);
const currentProviders = getProviders(providers, site);
strategyService.createStrategy(providers, site); // allow mocking this in tests
// init session authentication
router.use(createSessionStore(store));
router.use(passport.initialize());
router.use(passport.session());
router.use(flash());
// protect routes
router.use(protectRoutes(site));
// add authorization routes
// note: these (and the provider routes) are added here,
// rather than as route controllers in lib/routes/
router.get('/_auth/login', onLogin(site, currentProviders));
router.get('/_auth/logout', onLogout(site));
strategyService.addAuthRoutes(providers, router, site); // allow mocking this in tests
// handle de-authentication errors. This occurs when a user is logged in
// and someone removes them as a user. We need to catch the error
router.use(checkAuthentication(site));
router.use(addUser);
return currentProviders; // for testing/verification
}
module.exports = init;
module.exports.withAuthLevel = withAuthLevel;
module.exports.authLevels = AUTH_LEVELS;
module.exports.addRoutes = require('./routes/_users');
// for testing
module.exports.isProtectedRoute = isProtectedRoute;
module.exports.isAuthenticated = isAuthenticated;
module.exports.protectRoutes = protectRoutes;
module.exports.checkAuthentication = checkAuthentication;
module.exports.onLogin = onLogin;
module.exports.onLogout = onLogout;
module.exports.addUser = addUser;