当前位置: 首页 > article >正文

Express + MongoDB 实现新增用户密码加密

使用 bcryptjs 依赖实现用户加密。

1. 安装依赖

npm install bcryptjs

2. 定义用户模型

创建一个 `userModel.js` 文件,在其中定义用户模型,并在保存用户信息时对密码进行加密

const mongoose = require("mongoose");

const bcrypt = require("bcryptjs");

// 定义用户信息的 Schema

const userSchema = new mongoose.Schema({

  username: {

    type: String,

    required: true,

    unique: true,

  },

  password: {

    type: String,

    required: true,

  },

});

// 在保存用户信息前对密码进行加密

userSchema.pre("save", async function (next) {

  const user = this;

  // 只有当密码字段被修改时才进行加密操作

  if (!user.isModified("password")) return next();

  // 生成盐,盐的复杂度为 10

  const salt = await bcrypt.genSalt(10);

  // 使用盐对密码进行哈希处理

  const hash = await bcrypt.hash(user.password, salt);

  // 将加密后的密码赋值给用户的密码字段

  user.password = hash;

  next();

});

// 定义一个比较密码的方法

userSchema.methods.comparePassword = async function (candidatePassword) {

  return await bcrypt.compare(candidatePassword, this.password);

};

// 创建用户模型

module.exports = new mongoose.model("User", userSchema);


http://www.kler.cn/a/558648.html

相关文章:

  • C++单例模板类,继承及使用
  • http 协议在互联网中扮演着怎样的角色?
  • Python爬虫基础重要数据类型
  • 【亲测有效】百度Ueditor富文本编辑器添加插入视频、视频不显示、和插入视频后二次编辑视频标签不显示,显示成img标签,二次保存视频被替换问题,解决方案
  • 【2024 CSDN博客之星】大学四年,我如何在CSDN实现学业与事业的“双逆袭”?
  • 綫性與非綫性泛函分析與應用_3.例題-母本
  • 探秘路由表:网络世界的导航地图
  • 网络运维学习笔记 021 HCIA-Datacom新增知识点02 SDN与NFV概述
  • 计算机毕业设计SpringBoot+Vue.jst房屋租赁系统(源码+LW文档+PPT+讲解)
  • flutter: table calendar笔记
  • Spring Boot延迟执行实现
  • Spring MVC配置与自定义的深度解析
  • 计算机三级网络技术知识汇总【6】
  • ARM TCM(itcm和dtcm)
  • 网络安全之攻防笔记--通用安全漏洞SQL注入sqlmapOraclemongodbDB2
  • 算法系列之贪心算法
  • 分布式之Raft算法
  • Spring Boot定时任务原理
  • AI助力小微企业技术开发规范化管理 | 杂谈
  • 49 set与map的模拟实现