猫鼬自定义密码验证

时间:2018-08-09 12:14:19

标签: mongodb mongoose

我正在尝试使用猫鼬制作Schema,并停留在如何对密码应用自定义验证的问题上,其中密码包含:

  • 一个特殊字符

  • 密码应包含一个小写字母和一个大写字母

  • 密码的长度应大于6

以下是架构:

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

谢谢

2 个答案:

答案 0 :(得分:1)

由于您不应该在数据库中保存纯密码,因此在数据库中验证密码没有意义。因为您应该先对密码进行哈希处理,然后再保存。哈希密码是一个复杂的字符串,很可能会通过验证并保存到数据库中。

因此,您必须在客户端验证密码。为此,您可以使用joi npm软件包。

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

这是实现它的方法。

userModel.js //应位于models文件夹中

return this.$store.dispatch(RETRIEVE_DOCTORS).then().catch()

我将演示如何在邮政路由器内部使用此功能。

userRoute.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;

答案 1 :(得分:0)

您需要通过password函数将validate的{​​{1}}属性传递给

validator

我已经在牢记这些要求的情况下创建了此password: { type: String, validate: { validator: isValidPassword, message: 'Password must be... ' } } 模块。从该模块中检出mongoose-custom-validators验证器。该文档应详尽说明用法。

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

相关问题