Node.js 自定义验证程序无法检查空密码

Node.js 自定义验证程序无法检查空密码,node.js,express,mongoose,bcrypt,Node.js,Express,Mongoose,Bcrypt,我正在使用bcrypt散列用户的密码。因此,我有以下界面: app.post("/user", function(req, res, next) { // hash the password asynchronously bcrypt.hash(req.body.password, null, null, function(err, hash) { var newUser = new User({ username: req.body.us

我正在使用bcrypt散列用户的密码。因此,我有以下界面:

app.post("/user", function(req, res, next) {
    // hash the password asynchronously
    bcrypt.hash(req.body.password, null, null, function(err, hash) {
        var newUser = new User({
            username: req.body.username,
            password: hash,
            email: req.body.email
        });
        newUser.validate(function (err) {
            if (err) {
                logger.info("User registration aborted: " + err.toString());
                return res.status(400).json(err);
            } else {
                newUser.save(function (err, user) {
                    if (err) {
                        return res.status(500).json(err);
                    } else {
                        console.log(user.username + " saved succesfully.");
                        logger.info("User " + user._id + " registered.");
                        return res.json(user);
                    }
                });
            }
        });
    });
});
用户可以输入一个空密码(“”),该密码也将被散列。我不希望用户能够创建比x短、比y长的密码。因此,我想使用自定义验证器中止:

UserSchema.path("password").validate(function (value) {
    bcrypt.compare("", value, function(err, equal) {
        console.log(this.username + ": " + value + ", " + equal);
        return !equal;
    });
}, "password empty");

这不起作用,空密码将被散列而不会出错。当然,这并不能解决密码太长或太短的问题。

您没有将明文密码存储在mongoDB中,因此您不能在
UserSchema
验证中强制执行密码长度策略。你需要在进入散列/猫鼬方面之前做这件事。比如说:

app.post("/user", function(req, res, next) {
    var pw = req.body.password;
    if (!pw || pw.length > max || pw.length < min) {
        return res.status(400).send('Password is required and must be > x and < y...');
    }

    // hash the password asynchronously
    // ...
});
app.post(“/user”),函数(req、res、next){
var pw=req.body.password;
如果(!pw | | pw.length>max | | pw.length
然而,你似乎正在重新发明轮子。用户名/密码登录已多次完成。依赖现有的广泛依赖的实现可能比尝试自己的实现更好。例如:

app.post("/user", function(req, res, next) {
    var pw = req.body.password;
    if (!pw || pw.length > max || pw.length < min) {
        return res.status(400).send('Password is required and must be > x and < y...');
    }

    // hash the password asynchronously
    // ...
});

我正在使用oauth2服务器作为插件,无法使用passport local,因为我正在构建一个rest api而不提供页面服务。我也做了同样的快速修复,问题是,错误不会与其他验证错误一起发送。我希望将此验证错误与模型中其他属性的所有可能的其他验证错误发送到同一消息中。如果您的目标是在同一位置执行所有验证,则可以通过为
req.body
定义JSON模式,很好地提前加载验证。在我自己的代码中,我使用了我编写的这个简单的中间件,它使用了
tv4
:您仍然可以在mongoose验证器中执行任何您喜欢的操作,但是请记住我所说的,您谈论的是两种不同的模式,因此是两种不同的验证方法。另外,passport对于RESTAPI也可以很好地工作