I am creating REST api and want to authenticate user by token. I've found tutorial and wrote function based on it. But it's on callbacks and I want to return Promise from mongoose model and in route use then rather than do callbacks. Here is my function:
UserSchema.statics.authenticate = function(login, password, fn) {
var token;
this.findOne({login: login}, function(err, user) {
var _token;
if (err)
token = ( false);
if (!user){
token = ( false);
}
else if (user)
{
if (user.password != password)
token = ( false);
else
{
token = jwt.sign(user, secret);
user.update(
{ $set: {
token: token ,
lastActive: new Date()
}}
);
}
}
fn(token);
});
};
module.exports = mongoose.model('User', UserSchema);
I know that to return promise from find function i have to usee exec() but what I want to achive is to return token do I have to var q = new Promise in function and return this q object?
This is my route
router.post('/authenticate', function(req, res, next) {
User.authenticate( req.body.login,req.body.password, function(response){
if(response)
res.status(200)
.send({'success': true, token: response, msg: "Successfuly authenticated"});
else
res.status(200)
.send({'success': false, token: null, msg: "Wrong username or password"});
})
});
.theni mean instead offn(token)do Promise.resolve(token) and in my route just receive token