passport.authenticate()返回未定义的用户

gxwragnw  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(289)

我想建立一个应用程序与登录和注册。注册工作正常,但登录不(它给我 501-not implemented 错误)。以下是我的代码片段:

const passport = require('passport')

router.post('/register', (req, res) => {
  knex
    .from('user')
    .insert({
      firstname: req.body.firstname,
      lastname: req.body.lastname,
      email: req.body.email,
      password: req.body.password,
    })
    .then(() => {
      res.json({ success: true, message: "Data successfully inserted." })
    })
    .catch(() => {
      res.json({ success: false, message: "Error in adding user. Please try again." })
    })
})

router.post('/login', function (req, res, next) {
  passport.authenticate('local', function (err, user, info) {
    console.log("1 err " + JSON.stringify(err))
    console.log("2 user " + JSON.stringify(user))
    console.log("3 info " + JSON.stringify(info))
    if (err) { return res.status(501).json(err); }
    if (!user) { return res.status(501).json(info); }
    req.logIn(user, function (err) {
      if (err) { return res.status(501).json(err); }
      return res.status(200).json({ message: 'Login Success' });
    });
  })(req, res, next);
});

当我尝试登录时,我得到: 1 err [{"id":1,"firstname":"john","lastname":"doe","email":"jdoe@example.com","password":"joe"}] 2 user undefined 3 info undefined 为什么是
user undefined ? 我本来想得到一个 true/false 价值观。还有为什么 err 有这个价值吗?正因为如此,它才会一直持续下去 if(err) .
我可以提供更多的代码,如果你要求。谢谢您!
编辑:localpassport

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const knex = require('./db.js');

passport.use('local', new LocalStrategy({
  usernameField: 'email',
  passwordField: 'password'
},
  function (username, password, done) {
    knex('user')
      .where('email', '=', username)
      .then((err, user) => {
        if (err) { return done(err); }
        if (!user) {
          return done(null, false, { message: 'Incorrect username.' });
        }
        if (!user.isValid(password)) {
          return done(null, false, { message: 'Incorrect password.' });
        }
        return done(null, user);
      })
  }
));

passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  knex.from('user').where('id', '=', id)
    .then((user) => { done(null, user); })
    .catch((err) => { done(err, null); });
});

module.exports = passport;
qzlgjiam

qzlgjiam1#

问题出在localpassport内部:

passport.use('local', new LocalStrategy({
  usernameField: 'email',
  passwordField: 'password'
},
  function (username, password, done) {
    knex('users')
      .where('email', '=', username)
      .then((user) => {
        if (!user) {
          return done(null, false, { message: 'Incorrect username.' });
        }
        if (password != user[0].password) {
          return done(null, false, { message: 'Incorrect password.' });
        }
        return done(null, user[0]);
      })
  }
));

没有这样的属性 err .

相关问题