Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add custom error raising. #183

Merged
merged 1 commit into from
Aug 21, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,12 @@ signature `function(decoded, callback)` where:
- `responseFunc` - (***optional***) function called to decorate the response with authentication headers before the response headers or payload is written where:
- `request` - the request object.
- `reply(err, response)`- is called if an error occurred
- `errorFunc` - (***optional*** *defaults to raising the error requested*) function called when an error has been raised. It provides an extension point to allow the host the ability to customise the error messages returned. Passed in object follows the following schema:
- `errorContext.errorType` - ***required*** the `Boom` method to call (eg. unauthorized)
- `errorContext.message` - ***required*** the `message` passed into the `Boom` method call
- `errorContext.schema` - the `schema` passed into the `Boom` method call
- `errorContext.attributes` - the `attributes` passed into the `Boom` method call
- The function is expected to return the modified `errorContext` with all above fields defined.
- `urlKey` - (***optional*** *defaults to* `'token'`) - if you prefer to pass your token via url, simply add a `token` url parameter to your request or use a custom parameter by setting `urlKey`. To disable the url parameter set urlKey to `false` or ''.
- `cookieKey` - (***optional*** *defaults to* `'token'`) - if you prefer to set your own cookie key or your project has a cookie called `'token'` for another purpose, you can set a custom key for your cookie by setting `options.cookieKey='yourkeyhere'`. To disable cookies set cookieKey to `false` or ''.
- `headerKey` - (***optional*** *defaults to* `'authorization'`) - if you want to set a custom key for your header token use the `headerKey` option. To disable header token set headerKey to `false` or ''.
Expand Down
39 changes: 29 additions & 10 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,36 @@ internals.implementation = function (server, options) {
assert(options, 'options are required for jwt auth scheme'); // pre-auth checks
assert(options.validateFunc || options.verifyFunc, 'validateFunc OR verifyFunc function is required!')

var raiseError = function(errorType, message, scheme, attributes) {
if (options.errorFunc && internals.isFunction(options.errorFunc)) {
var errorContext = {
errorType: errorType,
message: message,
scheme: scheme,
attributes: attributes,
};
errorContext = options.errorFunc(errorContext);
if (errorContext) {
errorType = errorContext.errorType;
message = errorContext.message;
scheme = errorContext.scheme;
attributes = errorContext.attributes;
}
}
return Boom[errorType](message, scheme, attributes);
};

return {
authenticate: function (request, reply) {

var token = extract(request, options); // extract token from Header, Cookie or Query param

if (!token) {
return reply(Boom.unauthorized(null, 'Token'));
return reply(raiseError('unauthorized', null, 'Token'));
}

if (!extract.isValid(token)) { // quick check for validity of token format
return reply(Boom.unauthorized('Invalid token format', 'Token'));
return reply(raiseError('unauthorized', 'Invalid token format', 'Token'));
} // verification is done later, but we want to avoid decoding if malformed
request.auth.token = token; // keep encoded JWT available in the request lifecycle
// otherwise use the same key (String) to validate all JWTs
Expand All @@ -42,7 +61,7 @@ internals.implementation = function (server, options) {
decoded = JWT.decode(token, { complete: options.complete || false });
}
catch(e) { // request should still FAIL if the token does not decode.
return reply(Boom.unauthorized('Invalid token format', 'Token'));
return reply(raiseError('unauthorized', 'Invalid token format', 'Token'));
}

if(options.key && typeof options.validateFunc === 'function') {
Expand All @@ -51,23 +70,23 @@ internals.implementation = function (server, options) {

keyFunc(decoded, function (err, key, extraInfo) {
if (err) {
return reply(Boom.wrap(err));
return reply(raiseError('wrap', err));
}
if (extraInfo) {
request.plugins[pkg.name] = { extraInfo: extraInfo };
}
var verifyOptions = options.verifyOptions || {};
JWT.verify(token, key, verifyOptions, function (err, decoded) {
if (err) {
return reply(Boom.unauthorized('Invalid token', 'Token'), null, { credentials: null });
return reply(raiseError('unauthorized', 'Invalid token', 'Token'), null, { credentials: null });
}
else { // see: http://hapijs.com/tutorials/auth for validateFunc signature
options.validateFunc(decoded, request, function (err, valid, credentials) { // bring your own checks
if (err) {
return reply(Boom.wrap(err));
return reply(raiseError('wrap', err));
}
else if (!valid) {
return reply(Boom.unauthorized('Invalid credentials', 'Token'), null, { credentials: credentials || decoded });
return reply(raiseError('unauthorized', 'Invalid credentials', 'Token'), null, { credentials: credentials || decoded });
}
else {
return reply.continue({ credentials: credentials || decoded, artifacts: token });
Expand All @@ -80,10 +99,10 @@ internals.implementation = function (server, options) {
else { // see: https://github.com/dwyl/hapi-auth-jwt2/issues/130
options.verifyFunc(decoded, request, function(err, valid, credentials) {
if (err) {
return reply(Boom.wrap(err));
return reply(raiseError('wrap', err));
}
else if (!valid) {
return reply(Boom.unauthorized('Invalid credentials', 'Token'), null, { credentials: decoded });
return reply(raiseError('unauthorized', 'Invalid credentials', 'Token'), null, { credentials: decoded });
} else {
return reply.continue({ credentials: credentials, artifacts: token });
}
Expand All @@ -97,7 +116,7 @@ internals.implementation = function (server, options) {
if(options.responseFunc && typeof options.responseFunc === 'function') {
options.responseFunc(request, reply, function(err) {
if (err) {
return reply(Boom.wrap(err));
return reply(raiseError('wrap', err));
}
else {
reply.continue();
Expand Down
4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,10 @@
{
"name": "Benjamin Lees",
"email": "@benjaminlees <benji.man.lees@gmail.com>"
},
{
"name": "Jason Nah",
"email": "@jyn <jason.@gmail.com>"
}
],
"license": "ISC",
Expand Down
62 changes: 62 additions & 0 deletions test/error_func_server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
var Hapi = require('hapi');
var secret = 'NeverShareYourSecret';

// for debug options see: http://hapijs.com/tutorials/logging
var debug;
// debug = { debug: { 'request': ['error', 'uncaught'] } };
debug = { debug: false };
var server = new Hapi.Server(debug);
server.connection();

var sendToken = function(req, reply) {
return reply(req.auth.token);
};

var privado = function(req, reply) {
return reply(req.auth.credentials);
};

// defining our own validate function lets us do something
// useful/custom with the decodedToken before reply(ing)
var customVerifyFunc = function (decoded, request, callback) {
if(decoded.error) {
return callback(new Error('customVerify fails!'));
}
else if (decoded.custom_error) {
return callback(new Error(decoded.custom_error));
}
else if (decoded.some_property) {
return callback(null, true, decoded);
}
else {
return callback(null, false, decoded);
}
};

var customErrorFunc = function (errorContext) {
var result = errorContext;
if (errorContext.message.toString().search(/ignore/) >= 0) {
result = null;
} else if (errorContext.errorType === 'unauthorized') {
result.message = "Invalid credentials mate";
}
return result;
};

server.register(require('../'), function () {

server.auth.strategy('jwt', 'jwt', {
verifyFunc: customVerifyFunc, // no validateFunc or key required.
errorFunc: customErrorFunc
});

server.route([
{ method: 'GET', path: '/', handler: sendToken, config: { auth: false } },
{ method: 'GET', path: '/required', handler: privado, config: { auth: { mode: 'required', strategy: 'jwt' } } },
{ method: 'GET', path: '/optional', handler: privado, config: { auth: { mode: 'optional', strategy: 'jwt' } } },
{ method: 'GET', path: '/try', handler: privado, config: { auth: { mode: 'try', strategy: 'jwt' } } }
]);

});

module.exports = server;
116 changes: 116 additions & 0 deletions test/error_func_test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
var test = require('tape');
var JWT = require('jsonwebtoken');
// var secret = 'NeverShareYourSecret';

var server = require('./error_func_server'); // test server which in turn loads our module

test("Access a route that has no auth strategy", function(t) {
var options = {
method: "GET",
url: "/"
};
// server.inject lets us simulate an http request
server.inject(options, function(response) {
t.equal(response.statusCode, 200, "GET / still works without token.");
t.end();
});
});

test("customVerify simulate error condition", function(t) {
var payload = { id: 123, "name": "Charlie", error: true }
var token = JWT.sign(payload, 'SecretDoesNOTGetVerified');
var options = {
method: "GET",
url: "/required",
headers: { authorization: "Bearer " + token }
};
// server.inject lets us simulate an http request
server.inject(options, function(response) {
t.equal(response.statusCode, 500, "customVerify force error");
t.equal(response.result.message, "An internal server error occurred", "GET /required with forced error that has not been customised");
t.end();
});
});

test("customVerify simulate error condition but is safely not customised", function(t) {
var payload = { id: 123, "name": "Charlie", custom_error: 'ignore'}
var token = JWT.sign(payload, 'SecretDoesNOTGetVerified');
var options = {
method: "GET",
url: "/required",
headers: { authorization: "Bearer " + token }
};
// server.inject lets us simulate an http request
server.inject(options, function(response) {
t.equal(response.statusCode, 500, "customVerify force error");
t.equal(response.result.message, "An internal server error occurred", "GET /required with forced error that has not been customised");
t.end();
});
});

test("customVerify with fail condition", function(t) {
var payload = { id: 123, "name": "Charlie", some_property: false }
var token = JWT.sign(payload, 'SecretDoesNOTGetVerified');
var options = {
method: "GET",
url: "/required",
headers: { authorization: "Bearer " + token }
};
// server.inject lets us simulate an http request
server.inject(options, function(response) {
t.equal(response.statusCode, 401, "GET /required with customVerify rejected");
t.equal(response.result.message, "Invalid credentials mate", "GET /required with customVerify rejected and customised error message");
t.end();
});
});

test("Custom Verification in 'try' mode ", function(t) {
var payload = { id: 123, "name": "Charlie", some_property: true }
var token = JWT.sign(payload, 'SecretDoesNOTGetVerified');
var options = {
method: "GET",
url: "/try",
headers: { authorization: "Bearer " + token }
};
// server.inject lets us simulate an http request
server.inject(options, function(response) {
t.equal(response.result.id, payload.id, 'Decoded JWT returned by handler');
t.equal(response.statusCode, 200, "GET /try bypasses verification");
t.end();
});
});

test("Custom Verification in 'optional' mode ", function(t) {
var payload = { id: 234, "name": "Oscar", some_property: true }
var token = JWT.sign(payload, 'SecretDoesNOTGetVerified');
var options = {
method: "GET",
url: "/optional",
headers: { authorization: "Bearer " + token }
};
// server.inject lets us simulate an http request
server.inject(options, function(response) {
t.equal(response.result.id, payload.id, 'Decoded JWT returned by handler');
t.equal(response.statusCode, 200, "GET /optional bypasses verification");
t.end();
});
});

test("Custom Verification in 'required' mode ", function(t) {
var payload = { id: 345, "name": "Romeo", some_property: true }
var token = JWT.sign(payload, 'AnyStringWillDo');
var options = {
method: "GET",
url: "/required",
headers: { authorization: "Bearer " + token }
};
// server.inject lets us simulate an http request
server.inject(options, function(response) {
// console.log(response.result);
var credentials = JSON.parse(JSON.stringify(response.result));
t.equal(credentials.id, payload.id, 'Decoded JWT is available in handler');
t.equal(response.statusCode, 200, "GET /required bypasses verification");
t.end();
});
});