hapi-auth-cookie
hapi-auth-cookie is deceivingly simple to use.
Authenticate someone.
// do some logic to make sure we are who we say we are.
// then just set the auth session to some non-null object.
request.auth.session.set({must: 'be any old non-null object'});
Log them out.
request.auth.session.clear();
So you are logged in when there's a non-null object in auth session and you are logged out when there isn't. Simple.
Here's the setup.
var hapi = require('hapi');
var cookie = require('hapi-auth-cookie');
var server = new hapi.Server();
// register the cookie scheme.
server.register(cookie, function(err) {
// give our auth strategy a name 'any_name_will_do'
// hapi-auth-cookie's scheme is named 'cookie', so that needs to be
// the second param.
server.auth.strategy('any_name_will_do', 'cookie', {
password: 'G00b#rBuTz',
cookie: 'yo-cookie',
isSecure: false
});
});
// create a route that uses our auth strategy, and you won't
// be able to get to that route unless you are authenticated.
server.route({
method: 'GET',
path: '/private/{foo*}',
config: {
auth: 'any_name_will_do',
handler: {
directory: {
path: 'web/private'
}
}
}
});
Whatever you pass to request.auth.session.set()
will be available in request.auth.credentials
. But it will only be there on secured routes. That tripped me up a bit. I figured it should always be there for every route.
server.ext('onPostAuth', function(request, reply) {
console.log('request.auth.credentials', request.path, request.auth.credentials);
reply.continue();
});
onPostAuth always happens even if you aren't authenticated.
The output below shows that for the favicon request there was nothing in auth credentials even though I am authenticated. But the private request did have my creds.
request.auth.credentials /favicon.ico null
request.auth.credentials /private/ {must: 'be any old non-null object'}