我是节点的新手,我正在尝试使用passport.js进行简单的本地登录和运行。在我看来,在调用authenticate函数时,我设置的策略没有运行。
module.exports = function(app) {
var mongo = require('./mongoose-db.js');
var brands = require('./app/brands.js');
// brand admin page //
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy( {//this is a strategy but why is it not being run?
usernameField: 'admin_username',
passwordField: 'admin_password'
},
function(username, password, done) {console.log('here 7');
process.nextTick(function () {
console.log('here 8');
// Find the user by username. If there is no user with the given
// username, or the password is not correct, set the user to `false` to
// indicate failure and set a flash message. Otherwise, return the
// authenticated `user`.
mongo.findAdminByUsername(username, function(err, user) { console.log('here 9');
if (err) { return done(err); }
if (!user) { return done(null, false, { message: 'Unknown Admin ' + username }); }
if (user.password != password) { return done(null, false, { message: 'Invalid password' }); }
return done(null, user);
})
});
}
));
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
findById(id, function (err, user) {
done(err, user);
});
});
app.get('/brand_admin', function(req, res){
console.log('here 1');
res.render('admin_login', { user: req.user, message: req.session.messages });
});
app.post('/brand_admin', function(req, res, next) {
console.log('USER: ');
console.log(req.user);
res.send('ok');
passport.authenticate('local', function(err, user, info) {
console.log(user);
if (err) { return next(err) }
if (!user) {console.log(req.session.messages);
req.session.messages = [info.message];
console.log('here 4');
console.log(req.session.messages);
return res.redirect('/brand_admin')
}
console.log('here 5');
req.logIn(user, function(err) {
if (err) { return next(err); console.log('here 6');}
return res.redirect('/');
});
})(req, res, next);
});
ejs是:
<body>
<head> Admin Login </head>
<form id="brand_edit" action="/brand_admin" method="post" >
<fieldset>
Login: <input type="text" name="admin_login" > <br>
Password: <input type="password" name="admin_password" >
<input type="submit" name="action" value="Login"/>
</fieldset>
<a href="">Forgotten your password?</a>
</form>
</body>
我从表单提交中获得的输出是:
Steve
agrgegerfe
{ id: 1,
username: 'Steve',
password: 'agrgegerfe',
email: 'bob@example.com' }
false
undefined
here 4
[ 'Missing credentials' ]
here 1
策略没有运行,但我无法弄清楚为什么?有人可以帮忙吗?可能影响到这一点的一件事是我在应用程序的另一部分使用护照登录Facebook ..
答案 0 :(得分:4)
我认为你没有正确地打电话给护照。它需要在路线链中。试试这个:
// configure passport with the correct fields passport.use(new LocalStrategy({ usernameField: 'admin_login', passwordField: 'admin_password' }, function (username, password, done) { ... }); app.post('/brand_admin', passport.authenticate('local'), function (req, res) { // req.user is now defined console.log(req.user); res.send('ok'); });