如何从链接/子函数(子级到父级)返回布尔值? Nodejs的

时间:2018-12-12 03:58:51

标签: node.js express mongoose bcrypt

您好,SO'如何从NodeJ中的链接函数(子级到父级)返回布尔值?

我已经阅读了一些有关回调的内容,但总是以“回调不是函数”错误结尾。因此,我希望能获得一些新的帮助或更多的解释。

我的目的是为所有需要登录的路由提供一个可重用的功能,而不是复制整个auth bloc。

PS:不要看一堆“控制台日志”。 :D。我花了很多时间面对各种类型的错误,所以我决定调试所有步骤。

test.js

const app_port = 3456;
const bcrypt = require('bcrypt');
const User = require('./user.model.js');
const mongoose = require('mongoose');

const express = require('express');
var app = express();

const bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies


mongoose.connect('mongodb://localhost/jwtauth', { useNewUrlParser: true });



 function traitor (emailSubmitted, password){
    User.findOne({email: emailSubmitted}, async function(err, userInfo){
        if (err) {
            console.log(err);
        }
        else if (!userInfo) {
            console.log("user : " + emailSubmitted + " not found !" + '\n');
        }
        else {
            console.log(userInfo.password);
            await bcrypt.compare(password, userInfo.password, function (err, result) {
                if (result === true) {
                    console.log("user : " + emailSubmitted + " found !");
                    console.log("Password match and is " + userInfo.password) + '\n';
                    } else {
                    console.log("user : " + emailSubmitted + " found !");
                    console.log("Sorry, password missmatch !" + '\n');
                    }
                });
        }
    })
}

app.post('/api', function(req, res) {

 var email = req.body.email;
 var password = req.body.password;


 traitor(email, password); // <== Here I want to test a Boolean and execute some code accordingly. 

 console.log("req.body.email = " + req.body.email);
 console.log("req.body.password = " + req.body.password + '\n');
 res.send(req.body); 
});

app.listen(app_port);

user.model.js

const mongoose = require('mongoose');
Schema = mongoose.Schema;


const user = Schema({
   _id: Schema.Types.ObjectId,
   email: {type: String, required: true},
   password: {type: String, required: true}
});

module.exports = mongoose.model('User', user);

1 个答案:

答案 0 :(得分:0)

使用中间件。使叛徒充当中间件,进行身份验证,并将结果存储在req对象中,然后将其传递给中间件链中的下一个处理程序。

async function traitor(req, res, next) {
  emailSubmitted = req.body.email;
  password = req.body.email;

  let authenticated = await new Promise((resolve, reject) => {
    User.findOne({ email: emailSubmitted }, function(err, userInfo) {
      if (err) {
        console.log(err);
        resolve(false);
      } else if (!userInfo) {
        console.log('user : ' + emailSubmitted + ' not found !' + '\n');
        resolve(false);
      } else {
        console.log(userInfo.password);
        bcrypt.compare(password, userInfo.password, function(err, result) {
          if (result === true) {
            resolve(true);
            console.log('user : ' + emailSubmitted + ' found !');
            console.log('Password match and is ' + userInfo.password) + '\n';
          } else {
            resolve(false);
            console.log('user : ' + emailSubmitted + ' found !');
            console.log('Sorry, password missmatch !' + '\n');
          }
        });
      }
    });
  });

  req.locals.authenticated = authenticated; // <-- store the authentication result for next function in chain
  return next() // <-- pass on the req to next function in the chain
}

app.post('/api', traitor, function (req, res) {  // <-- middleware added here

  var email = req.body.email;
  var password = req.body.password;

  if (req.locals.authenticated) {
    // do yours stuff
  } else {
    // do yours stuff
  }

  console.log("req.body.email = " + req.body.email);
  console.log("req.body.password = " + req.body.password + '\n');
  res.send(req.body);
});