mongodb - How do I authenticate with Node.js + Mongoose? -


with following code i'm not able authenticate mongodb database, has users schema , users associated , wondering how make sure auth returned isauth?:

exports.auth = function(username, password, session) {     user.findone({username: username}, function(err, data) {         if (err) {             console.log(err);         }          var isauth = username === data['username'] & password === data['password'];           if (isauth) {              session.isauthenticated = isauth;              session.user = {username: username};          }           return isauth;     }); }; 

first of all, others have pointed out in comments, shouldn't implement own authentication logic if don't know you're doing. can use passport that.

now, code provided. there several problems here.

the first thing comes mind use:

var isauth = username === data['username'] & password === data['password']; 

instead of:

var isauth = username === data['username'] && password === data['password']; 

but typo. now, more fundamental stuff.

you cannot return isauth variable because going return to? if think returned caller of exports.auth you're wrong - exports.auth() return long before return isauth; ever run.

also, if yu check error if (err) put code should run in case of success in else block o otherwise run on error undefined variables may crash program.

you need either add additional argument function callback:

exports.auth = function(username, password, session, callback) {     user.findone({username: username}, function(err, data) {         if (err) {             console.log(err);             callback(err);         } else {             var isauth = username === data.username && password === data.password;             if (isauth) {                 session.isauthenticated = isauth;                 session.user = {username: username};             }             callback(null, isauth);         }     }); }; 

or return promise exports.auth function (but directly exports.auth function, not other callback inside).

using above version can call with:

auth(username, password, session, function (isauth) {   // have isauth here }); 

the other option use promises. can see other answers explain difference between callbacks , promises , how use them in more detail, may helpful in case:

but first need comfortable callbacks.

also, never store passwords in cleartext in database. seriously, use other solution works passport. wrote answer explain process of using callbacks, not endorse idea of using authentication in particular way. have been warned.


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -