我正在通过node.js和passport.js使用jwt。如果我使用电子邮件作为用户名,则可以使身份验证有效。但是,如果我使用实际的用户名,则无法使用它。它给我一个错误“电子邮件未注册。下面是我的实现方式:
passport.js
passport.use(
new localStrategy({ usernameField: 'email' },
(username, password, done) => {
User.findOne({ email: username },
(err, user) => {
if (err)
return done(err);
// unknown user
else if (!user)
return done(null, false, { message: 'Email is not registered' });
// wrong password
else if (!user.verifyPassword(password))
return done(null, false, { message: 'Wrong password.' });
// authentication succeeded
else
return done(null, user);
});
})
);
user.model.js
var userSchema = new mongoose.Schema({
firstName: {
type: String,
required: 'First name can\'t be empty'
},
middleName: {
type: String,
},
lastName: {
type: String,
required: 'Last name can\'t be empty'
},
userName: {
type: String,
required: 'Username can\'t be empty'
},
email: {
type: String,
required: 'Email can\'t be empty',
unique: true
},
password: {
type: String,
required: 'Password can\'t be empty',
minlength : [4,'Password must be atleast 4 character long']
},
saltSecret: String,
isActivated: {
type: Boolean,
},
dateAdded: {
type: Date
}
});
user.controller.js
module.exports.authenticate = (req, res, next) => {
// call for passport authentication
passport.authenticate('local', (err, user, info) => {
// error from passport middleware
if (err) return res.status(404).json(err);
// registered user
if (user) return res.status(200).json({ "token": user.generateJwt() });
// unknown user or wrong password
else return res.status(401).json(info);
})(req, res);
}
我需要使用“ userName”和“ password”字段进行身份验证,而不是电子邮件。我正在使用该电子邮件,因为它是我正在遵循的教程中使用的电子邮件。谢谢。
下面是我尝试实现所需功能的方法,但是它不起作用:
passport.use(
new localStrategy({ usernameField: 'userName' },
(username, password, done) => {
User.findOne({ userName: username },
(err, user) => {
if (err)
return done(err);
// unknown user
else if (!user)
return done(null, false, { message: 'Useris not registered' });
// wrong password
else if (!user.verifyPassword(password))
return done(null, false, { message: 'Wrong password.' });
// authentication succeeded
else
return done(null, user);
});
})
);
答案 0 :(得分:1)
尝试一下
passport.use(
new localStrategy({ usernameField: 'userName' },
(username, password, done) => {
User.findOne({ userName: username},
(err, user) => {
if (err)
return done(err);
// unknown user
else if (!user)
return done(null, false, { message: 'Email is not registered' });
// wrong password
else if (!user.verifyPassword(password))
return done(null, false, { message: 'Wrong password.' });
// authentication succeeded
else
return done(null, user);
});
})
)