I am building an app using node.js and I'm working on a user authentication module. In the function, I check if a user's cookie/session_id exists in the database. If it does, the function should return true. If it does not, the f unction should return false. However, my function keeps returning undefined
& i made a comment where it returns undefined.
exports.authenticate = function(rawCookie) {
if(rawCookie) {
var processedCookie = rawCookie.split('=');
var cookie = processedCookie[1];
var sessionIdArray = [];
var result;
knex.select('session_key')
.from('users')
.then(function(data) {
data.forEach(function(item) {
sessionIdArray.push(item.session_key);
})
if((sessionIdArray).indexOf(cookie) > -1) {
console.log('session id exists; can log in');
result = true;
} else {
console.log('session id does not exist; hacker alert')
result = false;
}
})
return result //this returns undefined
} else {
return false
console.log('no cookie');
}
}
Can someone help? I think the issue has something to do with asynchronization.
Thanks in advance!