0

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!

Trung Tran
  • 13,141
  • 42
  • 113
  • 200
  • The **A** in Ajax. And just return the value of the `indexOf` comparison. – Dave Newton Jan 11 '16 at 15:58
  • The answer above references ajax - which i am not using here... @MinusFour and so I'm still unclear of how to return the result i want... – Trung Tran Jan 11 '16 at 16:13
  • @user1547174, you are using an asynchronous function, it's the `A` in AJAX. Keep reading that question. Basically, the function supplied in `then` isn't being called just there (before returning result). – MinusFour Jan 11 '16 at 16:36

0 Answers0