I'm building small app with usage of HapiJS and Hapi-auth-cookie strategy but can't get it to work properly. I have defined routes like this:
/ - for serving front-end part of application
/login - performs mongodb check for user, then compare passwords and finally trying to set cookie
/restaurants - which i tried to secure with auth: 'session', but can't make it work
I've defined strategy (almost copy past from hapi-auth-cookie github page), but as i noticed but using console.log, validateFunc passed in strategy options is not being called even once. Why? Is it my main problem Or my other parts of code are broken?
Some code samples:
Session auth strategy definition:
exports.register = function(server, options, next) {
const cache = server.cache({ segment: 'sessions', expiresIn: 3 * 24 * 60 * 60 * 1000 });
server.app.cache = cache;
server.auth.strategy('session', 'cookie', false, {
password: 'password-should-be-32-characters',
cookie: 'lun-cookie',
redirectTo: false,
isSecure: false,
ttl: 20 * 1000,
validateFunc: function (request, session, callback) {
cache.get(session.sid, (err, cached) => {
if (err) {
return callback(err, false);
}
if (!cached) {
return callback(null, false);
}
return callback(null, true, cached.account);
});
}
});
return next();
};
Login method responsible for setting cookie:
login: (request, reply) => {
const dbQuery = {
email: request.payload.email
};
UserSchema.findOne(dbQuery, (err, user) => {
if (err) {
return console.log(err);
}
if (!user) {
return reply(Boom.unauthorized());
}
Bcrypt.compare(request.payload.password, user.password, (err, res) => {
if (err) {
return console.log(err);
}
if (!res) {
return reply(Boom.unauthorized());
}
const sid = String(123);
request.server.app.cache.set(sid, { account: user }, 0, (err) => {
if (err) {
reply(err);
}
request.cookieAuth.set({ sid: sid });
return reply("ok");
});
})
});
}
Route definition secured by strategy:
{
method: 'GET',
path: '/restaurants',
handler: controller.getRestaurants,
config: {
validate: {
query: {
list: Joi.string().allow('full').optional(),
type: Joi.string().valid(restaurantTypeEnum).optional(),
}
},
auth: 'session',
}
}
Any ideas? I've spent already two days trying to figure it out.
via Patrick
No comments:
Post a Comment