I tried the following code.
function authenticate( accesskey ) {
var res = someModel.findOne( {'uid': accesskey}, function ( err , user) {
if(err){
console.error("Can't Find.!! Error");
}
if(user===null){
return false;
}
else{
console.log(user);
return true;
}
});
console.log(res);
return res;
}
but res
here returns a mongoose data type.
I wish to call the authentication function like this -
if(authenticate(req.params.accesskey)){
//do something
}
else{
//do something else
}
UPDATE after implementing SOLUTION from Mustafa Genç
After getting comfortable with callbacks I ended up with the following code.
function authenticate( req, result, accesskey, callback ) {
var auth = null;
someModel.findOne( {'uid': accesskey}, function ( err , user) {
console.log("try authenticate");
if(err){
console.error(err);
}
if(user===null)
auth = false;
else
auth = true;
callback(auth);
});
}
And I use it like this -
routeHandler( req, reply ) {
authenticate( req, reply, req.params.accesskey , function (auth) {
if(auth) {
//"primary code"
}
else {
//fallback
}
});
}
You need a callback function since this is an async request:
function authenticate(accesskey, callback) {
var auth = null;
userModel.findOne({'uid': accesskey}, function(err, user) {
console.log("TRY AUTHENTICATE");
if (err) {
console.error("Can't Find.!! Error");
}
//None Found
if (user === null) {
console.error("ACCESS ERROR : %s Doesn't Exist", accesskey);
auth = false;
} else {
console.log(user);
auth = true;
}
callback(auth);
});
}
And call this function like :
authenticate("key", function (authResult) {
//do whatever
});
You can also try with promises.
function authenticate( accesskey ) {
var promise = someModel.findOne({'uid': accesskey}).exec();
}
routeHandler( req, reply ) {
authenticate(req.params.accesskey)
.then(function (auth) {
if(auth) {
//"primary code"
}
else {
//fallback
}
})
.catch(console.error);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With