Skip to content

Instantly share code, notes, and snippets.

@cabrel
Last active December 15, 2015 06:09
Show Gist options
  • Save cabrel/5213837 to your computer and use it in GitHub Desktop.
Save cabrel/5213837 to your computer and use it in GitHub Desktop.
Small auth check extension for Hapi + Travelogue
// `server` is the Hapi instance;
// boilerplate omitted for brevity sake
// prereq handler
function getSecret(request, next) {
return next(42);
}
// auth not required here, so we
// don't decorate it with any tags
server.addRoute({
method: 'GET',
path: '/',
handler: function(request) {
return request.reply.view('index', {});
}
});
// a route that requires authentication
// to have it checked by the server extension
// we decorate the route config with the tag 'auth'
server.addRoute({
method: 'GET',
path: '/important',
config: {
tags: ['auth'],
pre: [{method: getSecret, assign: 'secret'}],
handler: function(request) {
return request.reply(request.pre.secret);
}
}
});
// extension method to check and see if the
// `auth` tag exists on the route
function authenticateRequest(request, next) {
var path = request.path;
var tags = request.route.tags || [];
// I use lodash here, but any array search
// will suffice
if (_.contains(tags, 'auth')) {
if (!request.isAuthenticated()) {
return next(Hapi.Error.unauthorized(path));
}
}
return next();
}
// my biggest use case for this was due to the fact I heavily utilize
// prerequisites for collecting data, but that data, tends to be dependent
// on the current user.
//
// I wanted to avoid repeating sanity checks and I wanted to avoid spending
// the cycles collecting the data, only to have Travelogue.ensureAuthenticated
// reject the request due to the requestor being unauthenticated.
//
// So here we use the `onPreHandler` extension point to perform the check before
// continuing
server.ext('onPreHandler', authenticateRequest);
// and extend the check to the `onRequest` extension point as well
server.ext('onRequest', authenticateRequest);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment