首页 > 解决方案 > Mongoose 自定义密码验证

问题描述

我正在尝试使用 mongoose 制作 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,
    }
});

谢谢

标签: javascriptnode.jsdatabasemongodbmongoose

解决方案


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

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

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

这就是你可以实现它的方式。

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;

我将演示如何在后路由器中使用此功能。

用户路由.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
  });

推荐阅读