Article Directory
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
express
Create a test project directly using the automated build tool.
Then enter the project directory to install dependencies.
Install the mongoose module
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
.
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.
Write the models module
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
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/www
startup items
Test the registration interface with postman
You can see that the password has been encrypted
Test login interface
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()方法