gpt4 book ai didi

javascript - PassportJS 未进行身份验证

转载 作者:行者123 更新时间:2023-11-29 22:05:46 26 4
gpt4 key购买 nike

我做错了什么?它总是重定向到失败页面,但我无法调试。

// passport
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
User = require('./models/user.js').Model;

passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function(username, password, done) {
User.findOne({ username: username }, function(err, user) {
console.log('entrou');
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));


// login
app.get('/login', user.login);
app.post('/login',
passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login'
})
);

最佳答案

我也遇到了 passport.js 未进行身份验证的问题。所以这就是它对我的工作方式:

/**
* Local authentication strategy
*
*/
passport.use('local', new LocalStrategy(function(username, password, done) {
//async code waits until next()
process.nextTick(function() {
//searches the database for the user
//that matches the username|e-mail and password provided
models.User.checkCredentials(username, password, function(err, user) {
if (err) {
return done(err);
}

//user is not found
if (!user) {
return done(null, false, {message: 'Unknown user ' + username});
}

return done(null, user);
});
});
}));

登录一个用户

app.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
// if user is not found due to wrong username or password
if (!user) {
return res.render('login', {
//you can send a message to your view
message: 'Invalid username or password'
});
}
//passport.js has a logIn user method
req.logIn(user, function(err) {
if (err) { return next(err); }

return res.redirect('/');
});
})(req, res, next);
});

关于javascript - PassportJS 未进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21074491/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com