Mongoose 自定义密码验证 [英] Mongoose custom validation for password

查看:46
本文介绍了Mongoose 自定义密码验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 mongoose 制作 Schema 并坚持如何对密码应用自定义验证,其中密码包含:

I am trying to make Schema using mongoose and stuck in a point on how to apply custom validation for the password, where password contains:

  • 一个特殊字符

  • one special character

密码应该有一个小写和一个大写字符

password should have one lowercase and one uppercase character

密码长度应大于 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,
    }
});

谢谢

推荐答案

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

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.

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

So you have to validate the password in client side. for this you can use joi npm package.

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

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

this is how you can implement it.

userModel.js//应该在模型文件夹中

userModel.js //should be in models folder

 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

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

这篇关于Mongoose 自定义密码验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆