From 5554db713a12e0798c610fb1f12e5c943c7b689d Mon Sep 17 00:00:00 2001 From: Zhi Xiang Lin Date: Thu, 19 Dec 2019 15:57:26 -0500 Subject: [PATCH] Fix #88 - Pass errors to `next` in express --- lib/samlp.js | 14 +++++++++++--- test/fixture/server.js | 10 +++++++--- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/lib/samlp.js b/lib/samlp.js index e568f16..b81b270 100644 --- a/lib/samlp.js +++ b/lib/samlp.js @@ -136,7 +136,11 @@ module.exports.auth = function(options) { function execute (postUrl, audience, req, res, next) { var user = opts.getUserFromRequest(req); - if (!user) return res.send(401); + if (!user) { + const err = new Error('SAML unauthorized'); + err.status = 401; + return next(err); + } opts.audience = audience; opts.postUrl = postUrl; @@ -176,8 +180,12 @@ module.exports.auth = function(options) { } opts.getPostURL(audience, samlRequestDom, req, function (err, postUrl) { - if (err) { return res.send(500, err); } - if (!postUrl) { return res.send(401); } + if (err) { return next(err); } + if (!postUrl) { + const error = new Error('SAML unauthorized error, postUrl not received'); + error.status = 401; + return next(error); + } execute(postUrl, audience, req, res, next); }); diff --git a/test/fixture/server.js b/test/fixture/server.js index 47e30d4..6d7f46e 100644 --- a/test/fixture/server.js +++ b/test/fixture/server.js @@ -63,7 +63,7 @@ module.exports.start = function(options, callback){ key: credentials.key }, module.exports.options))(req, res, function(err){ if (err) { - return res.send(400, err.message); + return res.send(err.status || 400, err.message); } next(); }); @@ -85,7 +85,7 @@ module.exports.start = function(options, callback){ key: credentials.key }, module.exports.options))(req, res, function (err) { if (err) { - return res.send(400, err.message); + return res.send(err.status || 400, err.message); } next(); }); @@ -99,12 +99,16 @@ module.exports.start = function(options, callback){ key: credentials.key }, module.exports.options))(req, res, function (err) { if (err) { - return res.send(400, err.message); + return res.send(err.status || 400, err.message); } next(); }); }); + app.use(function (error, req, res, next) { + return res.status(error.status || 500).send(error.message); + }); + var server = http.createServer(app).listen(5050, callback); module.exports.close = server.close.bind(server); };