javascript - Mongoose 自定义密码验证
问题描述
我正在尝试使用 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
});
推荐阅读
- reactjs - 在不是反应组件的函数中使用道具
- r - 向量中的 ifelse() 和 paste0()
- javascript - ES6 检测函数是否在类实例的原型链上
- c - 如果没有用 minicom 打开一次,则无法从串口读取
- javascript - 在 rxjs 中选择重复列表的最后一项
- python-3.x - Zabbix API 3.4 - 由于循环要求而无法创建主机
- bash - 子shell进程无法访问父shell中定义的变量和函数
- ember.js - 如何在使用 Ember.set 设置之前修剪数据
- javascript - Firebase storage.object().onChange 现在已弃用,
- runtime-error - 如何在 Perl 中导致“无法刷新标准输出:管道损坏”?