我想用登录和注册来构建一个应用程序。注册可以正常工作,但不能登录(这给我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;
答案 0 :(得分:0)
问题出在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
这样的属性。