我正在设置用于注册和登录用户身份验证的 Passport 。现在我看到我可以通过回调验证信息,但是我也可以验证用户模型中的信息。例如,如果我想将电子邮件字段设为必填,那么我可以执行以下操作:
Passport 验证
// Create the local sign up with Passport
passport.use('local-signup', new LocalStrategy({
usernameField : 'userEmail', // Email Field
passwordField : 'userPassword', // Password Field
passReqToCallback : true
},
function(req, email, password, done) {
// Find a user with this email
User.findOne({ "local.email": email }, function(err, user) {
if (err) throw err;
// If a user with this email already exists, continue with failureRedirect
if (user) {
return done(null);
} else {
// Otherwise create a new user with the email and generate a hashed password
User.create({
local: {
email: email
}
}, function(err, user) {
if (err) throw err;
user.local.password = user.generateHash(password);
// Return the user and finish! :)
return done(null, user);
});
}
});
};
}));
使用用户模型
var userSchema = new Schema({
local: {
email: {
type: String,
unique: true // Make it unique! Handles entire validation
},
password: {
type: String
},
}
});
推荐其中哪一个,为什么?
最佳答案
为什么不两者都做呢?如果只使用第二个,将很难显示该消息
email address already exists
因为您需要捕获重复键错误索引
,然后在注册时显示错误消息。相反,您可以检查电子邮件地址是否已存在(这是更明确的),并在注册时同时使用唯一索引显示相应的错误消息,以确保电子邮件地址没有重复的条目。
关于node.js - 通过回调或 Mongoose 模型验证 PassportJS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24502129/