using @hapi/cookie, server.auth.strategy setting invalid. Validate function can't be called;
zhayes opened this issue · comments
zhayes commented
Runtime
nodejs v20.11.1
Runtime version
"@hapi/hapi": "^21.3.9"
Module version
"@hapi/cookie": "^12.0.1",
Used with
No response
Any other relevant information
"dependencies": {
"@hapi/cookie": "^12.0.1",
"@hapi/hapi": "^21.3.9",
"mysql2": "^3.9.7",
"sequelize": "^6.37.3",
"uuid": "^9.0.1"
}
How can we help?
'use strict';
const Hapi = require('@hapi/hapi');
const crypto = require('crypto');
const user_routes = require("./routes/users");
const products_routes = require("./routes/products");
//const users = {};
const all_routes = [user_routes, products_routes];
const init = async () => {
const server = Hapi.server({
port: 3000,
host: 'localhost'
});
await server.register(require('@hapi/cookie'));
server.auth.strategy('session', 'cookie', {
cookie: {
name: 'session',
password: crypto.randomBytes(32).toString('hex'),
isSecure: false
},
validate: async (request, session) => { //Validate function can't be called!!!
const isValid = !!session.user;
if(!isValid){
throw Boom.unauthorized('You are not authorized to access this resource');
}
return { isValid: true, credentials: session };
},
});
server.auth.default('session')
server.ext('onPreResponse', (request, h) => {
const response = request.response;
if (response) {
response.source = {
data: response.source,
code: response.statusCode,
message: response.isBoom ? (response.message||response.output.payload.message) : "success"
};
return h.continue;
}
return h.continue;
});
all_routes.forEach((item)=>{
server.route(item);
})
await server.start();
console.log('Server running on \x1b[36m%s\x1b[0m', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
exports.userLogin = async (request, h)=>{
try {
const {phone, password} = request.payload;
const user = await Users.findOne({
where:{
phone, password
}
});
if(user){
request.cookieAuth.set({ user:{name: user.name, phone: user.phone, userId: user.userId} });
return h.response(user);
}else{
return Boom.unauthorized('Invalid user account or password')
}
} catch (error) {
h.response({ error: `Internal server error:${error}` }).code(500);
}
}