【问题标题】:Validate PassportJS via Callback or Mongoose Model?通过回调或猫鼬模型验证 PassportJS?
【发布时间】:2014-08-21 12:47:46
【问题描述】:

我正在为注册和登录用户身份验证设置护照。现在我看到我可以通过回调验证信息,但是我也可以验证用户模型中的信息。例如,如果我想让电子邮件字段成为必填项,那么我可以执行以下操作:

护照验证

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

推荐其中哪些以及为什么?

【问题讨论】:

    标签: node.js validation mongoose passport.js


    【解决方案1】:

    为什么不两者兼而有之?如果你只使用第二个,将很难显示消息

    电子邮件地址已存在

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

    【讨论】:

    • 好点。在快速验证或身份验证方面,您知道任何最佳实践吗?
    • 我自己是 MEAN 堆栈的新手。但到目前为止,我一直在使用默认提供的中间件,如 auth.requiresLogin。要验证单个请求,您可以使用 req.isAuthenticated()。但我还没有创建我的自定义授权。也许您可以创建访问级别并将它们用作中间件来授权数据级别。我不确定这是标准做法。也许有更多经验的人会给我们更多的见解
    • 我有一点 Rails 背景,所以我习惯了Active Record Validations。我没有使用 MEAN 堆栈,但我为路由编写了一个 isLoggedIn 函数,以便检查用户是否经过身份验证。我更关心验证,例如最小字符、最大字符、正则表达式、唯一性、存在性等。在我看来,将它们写入护照回调文件非常麻烦,特别是如果用户想要更改他/她的信息。验证需要重写到控制器中,这不是 DRY
    • 我假设您使用的是猫鼬。您可以为本身充当中间件的模式类型定义custom validation。但请注意,使用.update() 时不会调用中间件(验证)。
    • 如果您认为我的回答解决了您的问题,请随时将其标记为已接受的答案。
    猜你喜欢
    • 2015-01-27
    • 1970-01-01
    • 2017-06-30
    • 2014-03-13
    • 2013-03-14
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 2018-10-24
    相关资源
    最近更新 更多