Skip to content
This repository was archived by the owner on Oct 5, 2020. It is now read-only.

Commit 59057f0

Browse files
authored
Merge pull request #483 from grtjn/master
Fixed #482: made sure authenticators are cleared properly at /user/logout, and code reformatting of all node-server files
2 parents 1d65631 + a847ab6 commit 59057f0

File tree

5 files changed

+100
-94
lines changed

5 files changed

+100
-94
lines changed

app/templates/node-server/node-app.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ console.log('About to crank up node');
5252
console.log('PORT=' + port);
5353
console.log('NODE_ENV=' + environment);
5454

55-
switch (environment){
55+
switch (environment) {
5656
case 'prod':
5757
case 'dev':
5858
console.log('** DIST **');
@@ -82,25 +82,25 @@ var server = null;
8282
if (options.nodeJsCertificate) {
8383
// Docs on how to create self signed certificates
8484
// https://devcenter.heroku.com/articles/ssl-certificate-self#prerequisites
85-
console.log("Starting the server in HTTPS");
86-
console.log("Node Certificate " + options.nodeJsCertificate);
87-
console.log("Node JS key " + options.nodeJsPrivateKey);
88-
var privateKey = fs.readFileSync(options.nodeJsPrivateKey, 'utf8');
85+
console.log('Starting the server in HTTPS');
86+
console.log('Node Certificate ' + options.nodeJsCertificate);
87+
console.log('Node JS key ' + options.nodeJsPrivateKey);
88+
var privateKey = fs.readFileSync(options.nodeJsPrivateKey, 'utf8');
8989
var certificate = fs.readFileSync(options.nodeJsCertificate, 'utf8');
9090
var credentials = {
9191
key: privateKey,
9292
cert: certificate
9393
};
9494
server = https.createServer(credentials, app);
9595
} else {
96-
console.log("Starting the server in HTTP");
96+
console.log('Starting the server in HTTP');
9797
server = http.createServer(app);
9898
}
9999

100100
server.listen(port, function() {
101101
console.log('Express server listening on port ' + port);
102102
console.log('env = ' + app.get('env') +
103-
'\n__dirname = ' + __dirname +
103+
'\n__dirname = ' + __dirname +
104104
'\nprocess.cwd = ' + process.cwd());
105105
});
106106

app/templates/node-server/proxy.js

Lines changed: 29 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,10 @@ var fs = require('fs');
1212

1313
var ca = null;
1414
if (options.mlCertificate) {
15-
console.log("Loading ML Certificate " + options.mlCertificate);
15+
console.log('Loading ML Certificate ' + options.mlCertificate);
1616
ca = fs.readFileSync(options.mlCertificate);
1717
} else {
18-
console.log("No ML SSL Certificate.");
18+
console.log('No ML SSL Certificate.');
1919
}
2020

2121
/************************************************/
@@ -24,41 +24,45 @@ if (options.mlCertificate) {
2424

2525
// TODO: configurable path?
2626
var target = url.format({
27-
protocol: options.mlCertificate?'https':'http',
27+
protocol: options.mlCertificate ? 'https' : 'http',
2828
hostname: options.mlHost,
2929
port: options.mlHttpPort,
3030
pathname: '/v1'
3131
});
3232

3333
var proxyServer = httpProxy.createProxyServer({
34-
target: target
35-
, ca : options.mlCertificate?ca:null
36-
//options.httpsStrict==="false" assumes that you are in dev mode
37-
, secure: options.httpsStrict==="true"?true:false
34+
target: target,
35+
ca: options.mlCertificate ? ca : null,
36+
secure: options.httpsStrict
37+
//options.httpsStrict === false assumes that you are in dev mode
3838
});
3939

4040
function getAuth(req) {
4141
var user = req.session.passport && req.session.passport.user &&
42-
req.session.passport.user.username;
42+
req.session.passport.user.username;
4343

4444
return authHelper.getAuthorization(req.session, req.method, req.path, {
4545
authUser: user
46-
})
46+
});
4747
}
4848

49-
function proxy (req, res) {
50-
getAuth(req).then(function (auth) {
49+
function proxy(req, res) {
50+
getAuth(req).then(function(auth) {
5151
// TODO: if no auth?
52-
var headers = { headers: { authorization: auth } };
52+
var headers = {
53+
headers: {
54+
authorization: auth
55+
}
56+
};
5357

5458
// TODO: filter www-header in response?
5559
// (currently prompts without authed middleware)
5660

57-
proxyServer.web(req, res, headers, function (e) {
61+
proxyServer.web(req, res, headers, function(e) {
5862
console.log(e);
5963
res.status(500).send('Error');
6064
});
61-
}, function (e) {
65+
}, function(e) {
6266
console.log('auth error:');
6367
console.log(e);
6468
return res.status(401).send('Unauthorized');
@@ -69,35 +73,35 @@ function proxy (req, res) {
6973
/********** create custom middleware **********/
7074
/************************************************/
7175

72-
function noCache (req, res, next) {
73-
res.append('Cache-Control', 'no-cache, must-revalidate'); // HTTP 1.1 - must-revalidate
74-
res.append('Pragma', 'no-cache'); // HTTP 1.0
75-
res.append('Expires', 'Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
76+
function noCache(req, res, next) {
77+
res.append('Cache-Control', 'no-cache, must-revalidate'); // HTTP 1.1 - must-revalidate
78+
res.append('Pragma', 'no-cache'); // HTTP 1.0
79+
res.append('Expires', 'Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
7680

7781
next();
7882
}
7983

80-
function authed (req, res, next) {
84+
function authed(req, res, next) {
8185
if (!(options.guestAccess || req.isAuthenticated())) {
8286
return res.status(401).send('Unauthorized');
8387
}
8488

8589
next();
8690
}
8791

88-
function update (req, res, next) {
92+
function update(req, res, next) {
8993
if (options.disallowUpdates) {
9094
return res.status(403).send('Forbidden');
9195
}
9296

9397
next();
9498
}
9599

96-
function profile (req, res, next) {
100+
function profile(req, res, next) {
97101
if ((req.path === '/documents') &&
98-
req.query.uri &&
99-
req.query.uri.match('/api/users/') &&
100-
!req.query.uri.match('/api/users/' + req.session.passport.user.username + '.json')) {
102+
req.query.uri &&
103+
req.query.uri.match('/api/users/') &&
104+
!req.query.uri.match('/api/users/' + req.session.passport.user.username + '.json')) {
101105
return res.status(403).send('Forbidden');
102106
}
103107

@@ -143,7 +147,7 @@ ext.get(proxy);
143147
ext.all(update, proxy);
144148

145149
// Explicitly reject all other routes
146-
router.all('*', function (req, res) {
150+
router.all('*', function(req, res) {
147151
res.status(401).send('Not proxied');
148152
});
149153

app/templates/node-server/routes.js

Lines changed: 21 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -12,18 +12,20 @@ var http = require('http');
1212
var https = require('https');
1313
var fs = require('fs');
1414

15-
var ca = "";
15+
var ca = '';
1616
var httpClient = null;
1717
if (options.mlCertificate) {
18-
console.log("Loading ML Certificate " + options.mlCertificate);
19-
ca = fs.readFileSync(options.mlCertificate);
20-
httpClient = https;
18+
console.log('Loading ML Certificate ' + options.mlCertificate);
19+
ca = fs.readFileSync(options.mlCertificate);
20+
httpClient = https;
2121
} else {
22-
httpClient = http;
22+
httpClient = http;
2323
}
2424

2525
// [GJo] (#31) Moved bodyParsing inside routing, otherwise it might try to parse uploaded binaries as json..
26-
router.use(bodyParser.urlencoded({extended: true}));
26+
router.use(bodyParser.urlencoded({
27+
extended: true
28+
}));
2729
router.use(bodyParser.json());
2830

2931
router.get('/user/status', function(req, res) {
@@ -33,8 +35,9 @@ router.get('/user/status', function(req, res) {
3335
if (options.guestAccess) {
3436
res.send(authStatus(
3537
true,
36-
options.defaultUser,
37-
{ fullname: 'Guest' }
38+
options.defaultUser, {
39+
fullname: 'Guest'
40+
}
3841
));
3942
} else {
4043
res.send(authStatus(
@@ -54,14 +57,12 @@ router.get('/user/status', function(req, res) {
5457
};
5558

5659
delete headers['content-length'];
57-
authHelper.getAuthorization(req.session, reqOptions.method, reqOptions.path,
58-
{
59-
authHost: reqOptions.hostname || options.mlHost,
60-
authPort: reqOptions.port || options.mlHttpPort,
61-
authUser: passportUser.username,
62-
authPassword: passportUser.password
63-
}
64-
).then(
60+
authHelper.getAuthorization(req.session, reqOptions.method, reqOptions.path, {
61+
authHost: reqOptions.hostname || options.mlHost,
62+
authPort: reqOptions.port || options.mlHttpPort,
63+
authUser: passportUser.username,
64+
authPassword: passportUser.password
65+
}).then(
6566
function(authorization) {
6667
delete headers['content-length'];
6768
if (authorization) {
@@ -100,7 +101,7 @@ router.get('/user/status', function(req, res) {
100101
}
101102
});
102103

103-
profile.on('socket', function (socket) {
104+
profile.on('socket', function(socket) {
104105
socket.on('timeout', function() {
105106
console.log('Timeout reached, aborting call to ML..');
106107
profile.abort();
@@ -135,19 +136,16 @@ router.post('/user/login', function(req, res, next) {
135136

136137
router.get('/user/logout', function(req, res) {
137138
noCache(res);
138-
if (req.session.authenticator) {
139-
authHelper.clearAuthenticator(req.session);
140-
delete req.session.authenticator;
141-
}
142139
req.logout();
140+
authHelper.clearAuthenticator(req.session);
143141
res.send();
144142
});
145143

146144
router.get('/*', four0four.notFoundMiddleware);
147145

148146
function noCache(response) {
149-
response.append('Cache-Control', 'no-cache, must-revalidate');//HTTP 1.1 - must-revalidate
150-
response.append('Pragma', 'no-cache');//HTTP 1.0
147+
response.append('Cache-Control', 'no-cache, must-revalidate'); //HTTP 1.1 - must-revalidate
148+
response.append('Pragma', 'no-cache'); //HTTP 1.0
151149
response.append('Expires', 'Sat, 26 Jul 1997 05:00:00 GMT'); // Date in the past
152150
}
153151

app/templates/node-server/utils/auth-helper.js

Lines changed: 33 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
'use strict';
44

55
var options = require('./options')();
6-
var https = require('https')
6+
var https = require('https');
77
var http = require('http');
88
var q = require('q');
99
var wwwAuthenticate = require('www-authenticate');
@@ -14,12 +14,12 @@ var LocalStrategy = require('passport-local').Strategy;
1414

1515
var httpClient = http;
1616
if (options.mlCertificate) {
17-
console.log("ML Certificate = '" + options.mlCertificate + "'")
18-
console.log("Will use https client.");
19-
httpClient = https;
17+
console.log('ML Certificate = "' + options.mlCertificate + '"');
18+
console.log('Will use https client.');
19+
httpClient = https;
2020
} else {
21-
console.log("ML Certificate = '" + options.mlCertificate + "'")
22-
console.log("Will use http client.");
21+
console.log('ML Certificate = "' + options.mlCertificate + '"');
22+
console.log('Will use http client.');
2323
}
2424

2525
var defaultOptions = {
@@ -39,8 +39,9 @@ function init() {
3939
done(null, obj);
4040
});
4141

42-
passport.use(new LocalStrategy(
43-
{ passReqToCallback: true },
42+
passport.use(new LocalStrategy({
43+
passReqToCallback: true
44+
},
4445
function(req, username, password, done) {
4546
var reqOptions = {
4647
hostname: options.mlHost,
@@ -49,24 +50,22 @@ function init() {
4950
headers: {}
5051
};
5152

52-
getAuthorization(req.session, reqOptions.method, reqOptions.path,
53-
{
54-
authHost: options.mlHost,
55-
authPort: options.mlHttpPort,
56-
authUser: username,
57-
authPassword: password
58-
}
59-
).then(function(authorization) {
53+
getAuthorization(req.session, reqOptions.method, reqOptions.path, {
54+
authHost: options.mlHost,
55+
authPort: options.mlHttpPort,
56+
authUser: username,
57+
authPassword: password
58+
}).then(function(authorization) {
6059
if (authorization) {
6160
reqOptions.headers.Authorization = authorization;
6261
}
6362

6463
var login = httpClient.get(reqOptions, function(response) {
6564

6665
var user = {
67-
authenticated:true,
68-
username:username
69-
};
66+
authenticated: true,
67+
username: username
68+
};
7069

7170
if (response.statusCode === 200) {
7271
response.on('data', function(chunk) {
@@ -83,9 +82,13 @@ function init() {
8382
//no user profile yet..
8483
done(null, user);
8584
} else if (response.statusCode === 401) {
86-
done(null, false, {message: 'Invalid credentials'});
85+
done(null, false, {
86+
message: 'Invalid credentials'
87+
});
8788
} else {
88-
done(null, false, {message: 'API error'});
89+
done(null, false, {
90+
message: 'API error'
91+
});
8992
}
9093
});
9194
login.on('error', function(e) {
@@ -100,7 +103,9 @@ function init() {
100103

101104
function handleLocalAuth(req, res, next) {
102105
passport.authenticate('local', function(err, user, info) {
103-
if (err) { return next(err); }
106+
if (err) {
107+
return next(err);
108+
}
104109
if (!user) {
105110
return res.json(401, {
106111
message: info.message
@@ -109,7 +114,9 @@ function handleLocalAuth(req, res, next) {
109114

110115
// Manually establish the session...
111116
req.login(user, function(err) {
112-
if (err) { return next(err); }
117+
if (err) {
118+
return next(err);
119+
}
113120
return res.json(user);
114121
});
115122

@@ -120,8 +127,7 @@ function isAuthenticated(req, res, next) {
120127

121128
if (req.isAuthenticated()) {
122129
return next();
123-
}
124-
else {
130+
} else {
125131
res.status(401).send('Unauthorized');
126132
}
127133
}
@@ -181,8 +187,7 @@ function timestampAuthenticator(authenticator) {
181187
var expirationTime = 1000 * 60 * 60 * 12;
182188

183189
function isExpired(authenticator) {
184-
return
185-
authenticator.lastAccessed &&
190+
return authenticator.lastAccessed &&
186191
((new Date()) - authenticator.lastAccessed) > expirationTime;
187192
}
188193

@@ -222,7 +227,7 @@ function getAuthorization(session, reqMethod, reqPath, authOptions) {
222227
}, function(response) {
223228
var statusCode = response.statusCode;
224229
var challenge = response.headers['www-authenticate'];
225-
var hasChallenge = (challenge != null);
230+
var hasChallenge = (challenge !== null);
226231
if (statusCode === 401 && hasChallenge) {
227232
authenticator = createAuthenticator(
228233
session,

0 commit comments

Comments
 (0)