Express+mongoose database storage password for encryption and verification

brief description

IMPORTANT: The passwords stored in the database in the project must be encrypted!! and must be encrypted using an irreversible algorithm!!

Step 1: Create a project

expressCreate a test project directly using the automated build tool.
insert image description here
Then enter the project directory to install dependencies.
insert image description here
Install the mongoose module
insert image description here

Key point: install the bcryptjs module

bcryptjs模块It is one of nodejs 字符串加盐(slat)加密模块, although ordinary md5 encryption is irreversible, but md5 can use dictionary attack to obtain encrypted information, so it needs to be added to the original information, the 盐(slat)essence is also a string 字符串, it will be needed 加密的信息和盐进行拼接, and then md5 encryption, It can prevent dictionary attacks, but these operations do not require us to implement them. The bcryptjs module has already implemented them for us, and we only need to use a few of them.

Install the bcryptjs module using npm i bcryptjs.
insert image description here

Step 2: Write model objects and interfaces

Create files in the root directory of the project models.js, the location is not important and can be created casually.
insert image description here

Write the models module

insert image description here
Main code (code above)

const mongoose = require('mongoose')
const bcryptjs = require('bcryptjs')
// 连接数据库
mongoose.connect('mongodb://127.0.0.1/bcrypt', err => {
    
    
    if (!err) {
    
    
        console.log('数据库连接成功');
    }
})
// 定义schema
const userSchema = mongoose.Schema({
    
    
    username: String,
    password: {
    
    
        type: String,
        set(val) {
    
       // 每次对数据库进行修改或插入时都会执行set
            return bcryptjs.hashSync(val) // 对入库的密码进行加密
        }
    }
})
// 定义model
const userModel = mongoose.model('user', userSchema)
// 暴露model
module.exports = {
    
    
    userModel
}

Write the registration login interface

insert image description here
Main code (code above)

var {
    
     userModel } = require('./models')  // 引入userModel
var bcryptjs = require('bcryptjs')  // 引入bcryptjs模块

app.post('/register', async (req, res) => {
    
    
  // 假设已经对数据进行过验证, 因为在model中定义了set方法所以这里直接入库
  await userModel.create(req.body)
  res.send('ok')
})

app.post('/login', async (req, res) => {
    
    
  let username = req.body.username
  let password = req.body.password
  let user = await userModel.findOne({
    
     username })
  if (!user) {
    
    
    return res.send('没有这个用户!')
  }
  // 使用bcryptjs.compareSync方法进行验证,第一个参数是要验证的字符串,第二个参数是加密过的字符串
  if (!bcryptjs.compareSync(password, user.password)) {
    
    
    return res.send('密码错误!')
  }
  res.send('登录成功!')
})

Step 3: Test the effect

Enter node ./bin/wwwstartup items
insert image description here

Test the registration interface with postman

insert image description here
You can see that the password has been encrypted
insert image description here

Test login interface

insert image description here
insert image description here
You can see that there is no problem with the login interface.

Summarize

The two methods are mainly used bcryptjs模块:
bcryptjs.hashSync(val)generate an encrypted string
bcryptjs.compareSync(val, hasval)and verify whether parameter 2 is encrypted from parameter 1.
If you want to understand the principles of these two methods, you can Baidu

Schema对象Field objects can be modified at definition timeset()方法

Guess you like

Origin blog.csdn.net/qq_45458749/article/details/125759337