通过回调或猫鼬模型验证PassportJS



我正在为注册和登录用户身份验证设置护照。现在我看到我可以通过回调验证信息,但是我也可以在User模型中验证信息。例如,如果我想将email字段设置为必填,那么我可以这样做:

护照验证

// 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
        },
    }
});

推荐哪一个,为什么?

为什么不同时使用呢?如果只使用第二个,则很难显示

消息。

电子邮件地址已经存在

,因为您需要捕获duplicate key error index,然后在注册时显示错误消息。相反,你可以检查,如果电子邮件地址已经存在,这是更明确的,并在注册时显示相应的错误信息,同时使用唯一索引将确保没有重复条目的电子邮件地址。

最新更新