简体   繁体   English

Mongoose 自定义密码验证

[英]Mongoose custom validation for password

I am trying to make Schema using mongoose and stuck in a point on how to apply custom validation for the password, where the password contains:我正在尝试使用 mongoose 制作 Schema 并坚持如何对密码应用自定义验证,其中密码包含:

  • one special character一个特殊字符

  • password should have one lowercase and one uppercase character密码应该有一个小写和一个大写字符

  • password should have a length of more than 6密码长度应大于 6

Here is the Schema:这是架构:

const mongoose = require('../db/mongoose');
const validator = require('validator');

const UserSchema = new mongoose.Schema({
    email: {
        type: String,
        validate: {
            validator: validator.isEmail()
        }
    },
    password: {
        type: String,
        minlength: 6,
    }
});

Thanks谢谢

Since you are not supposed to save plain password in your database, it does not make sense to validate the password in the database.由于您不应该在数据库中保存普通密码,因此验证数据库中的密码是没有意义的。 Because you should hash the password first and then save it.因为您应该先对密码进行哈希处理,然后再保存。 hashed password will be a complex string that most likely will pass the validation to be saved in database.散列密码将是一个复杂的字符串,很可能会通过验证以保存在数据库中。

So you have to validate the password in client side.所以你必须在客户端验证密码。 for this you can use joi npm package.为此,您可以使用 joi npm 包。

https://www.npmjs.com/package/@hapi/joi https://www.npmjs.com/package/@hapi/joi

this is how you can implement it.这就是你可以实现它的方式。

userModel.js //should be in models folder userModel.js //应该在模型文件夹中

 const Joi = require('@hapi/joi');
 const mongoose = require("mongoose");

 //you defined your schema above, it should be **lowercase** 
 //here is the model, model should start capital letter 
 const User=mongoose.model("User",userSchema)

function validateUser(user) {
  const schema = Joi.object().keys({
    email: Joi.string()
      .min(8)
      .max(50)
      .required()
      .email(),
    password: Joi.string()
      .min(6)
      .required()
      .max(20)
      .regex(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9]).{8,1024}$/) //special/number/capital
  });
  return Joi.validate(user, schema);
}

module.exports.User = User;
module.exports.validate = validateUser;

i will demonstrate how to use this function inside a post router.我将演示如何在后路由器中使用此功能。

userRoute.js用户路由.js

//import model and validate func
const { User, validate } = require("/models/user"); 

router.post("/", async (req, res) => {
  //validating the request here
  const { error } = validate(req.body);
  if (error) res.status(400).send(error.details[0].message);

  //i used this code to show you how to use validate function
  //i am not sure what is your project about
  });

You need to pass password a validate property with a validator function您需要使用validate validator函数向password传递validate属性

password: {
  type: String,
  validate: {
    validator: isValidPassword,
    message: 'Password must be... '
  }
}

I have created this mongoose-custom-validators module with those requirements in mind.我在考虑这些要求的情况下创建了这个mongoose-custom-validators模块。 Check out the isValidPassword validator from this module.查看此模块中的isValidPassword验证器。 The documentation should be thorough on the usage.文档应该详尽地说明使用情况。

https://www.npmjs.com/package/mongoose-custom-validators https://www.npmjs.com/package/mongoose-custom-validators

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM