簡體   English   中英

Mongoose 自定義密碼驗證

[英]Mongoose custom validation for password

我正在嘗試使用 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,
    }
});

謝謝

由於您不應該在數據庫中保存普通密碼,因此驗證數據庫中的密碼是沒有意義的。 因為您應該先對密碼進行哈希處理,然后再保存。 散列密碼將是一個復雜的字符串,很可能會通過驗證以保存在數據庫中。

所以你必須在客戶端驗證密碼。 為此,您可以使用 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
  });

您需要使用validate validator函數向password傳遞validate屬性

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

我在考慮這些要求的情況下創建了這個mongoose-custom-validators模塊。 查看此模塊中的isValidPassword驗證器。 文檔應該詳盡地說明使用情況。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM