Node.js: express + MySQL implements password modification

        To change the password, this article only considers the following aspects when changing the password:

        (1), get the old password

        (2), get a new password

        (3), compare the obtained old password with the password in the database (to avoid modifying the wrong user)

        (4), compare the new password with the incoming password, the new password and the old password cannot be the same

        (5), encrypt and store the new password in the database

        Other points are not considered.

        In my blog ( Node.js: express + MySQL to achieve registration and login, identity authentication_express connect to mysql database registration and login_hair loss type player's blog-CSDN blog ), the bcryptjs package is used for registration Encrypt the password, so when changing the password, you also need to use the package to compare the password and encrypt the new password.

        The values ​​received from the front end, id (judging which user's password to modify), oldPwd (old password), newPwd (new password), will be stored in req.

        What is written in the file is the function of changing the password. For the path, please refer to my previous article about registration, and write the path separately from its execution function. Easy to manage.

// 修改密码
exports.updatePassword = (req, res) => {
    console.log(req);
}

        (1), obtain the password that needs to be modified in the database according to the id value

exports.updatePassword = (req, res) => {
    console.log(req);
    // 根据id查询用户信息
    const sql = 'select * from ev_users where id=?'
    // 执行sql语句
    db.query(sql, req.user.id, (err, results) => {
        // 查询出错
        if (err) return res.cc(err)
        // 查询成功 但条数不等于1
        if (results.length !== 1) return res.cc('用户不存在')
        console.log(results[0].password);
    })
}

        Query the data that needs to be modified according to the id. If the query is wrong or the user does not exist, do some processing. If the query is successful, results[0].password is the encrypted password stored in the database.

        (2), then compare the password obtained from req with the password stored in the database to see if they are consistent. You can use a method in the bcryptjs package (bcryptjs is a package used to encrypt passwords when storing passwords), compareSync method .

exports.updatePassword = (req, res) => {
    console.log(req);
    // 根据id查询用户信息
    const sql = 'select * from ev_users where id=?'
    // 执行sql语句
    db.query(sql, req.user.id, (err, results) => {
        // 查询出错
        if (err) return res.cc(err)
        // 查询成功 但条数不等于1
        if (results.length !== 1) return res.cc('用户不存在')
        // 判断用户输入的旧密码是否正确
        // 不能直接判断  数据库中存加密后的密码
        const compareResult = bcryptjs.compareSync(req.body.oldPwd, results[0].password)
        if (!compareResult) return res.cc('旧密码错误!')
    })
}

        Use bcryptjs.compareSync(req.body.oldPwd, results[0].password) to compare the obtained old password with the password stored in the database. If they are the same, true will be returned, and if they are different, false will be returned.

        (3) Compare the new password with the password in the database, the new password cannot be the same as the original password.

The first method of judgment

const sameCompare = bcryptjs.compareSync(req.body.newPwd, results[0].password)
if (sameCompare) return res.cc('新密码不能和原密码相同!')

The second judgment method

        In the article on registration and login, it is written that there are two packages, @escook/express-joi (automatically verify form data), joi (field rules), and these two packages can also be used to judge new and old passwords.

// 导入定义验证规则的包
const joi = require('joi')

// 字符串类型,匹配正则,必输
const password = joi.string().pattern(/^[\S]{6,12}$/).required()

exports.update_password_schema = {
    body: {
        // 旧密码使用 password 这个规则
        oldPwd: password,
        // 新密码不能等于旧密码,但也得符合密码的规则
        // joi.ref('')  与括号中的值保持一致
        newPwd: joi.not(joi.ref('oldPwd')).concat(password),
    }
}

        Then use it in the router.

// 导入验证数据的中间件
const expressJoi = require('@escook/express-joi')
const { update_password_schema } = require('../schema/user')

// 重置密码
router.post('/updatePwd', expressJoi(update_password_schema), userInfo_handler.updatePassword)

        If the input is consistent, it will return:

        (4) After that, the new password can be encrypted and stored in the database.

        Encrypt the new password before using the update statement to store the password in the database. All the code of this interface:

// 重置密码
exports.updatePassword = (req, res) => {
    // console.log(req);
    // 根据id查询用户信息
    const sql = 'select * from users where id=?'
    // 执行sql语句
    db.query(sql, req.user.id, (err, results) => {
        // 查询出错
        if (err) return res.cc(err)
        // 查询成功 但条数不等于1
        if (results.length !== 1) return res.cc('用户不存在')
        // 判断用户输入的旧密码是否正确
        // 不能直接判断  数据库中存加密后的密码
        const compareResult = bcryptjs.compareSync(req.body.oldPwd, results[0].password)
        if (!compareResult) return res.cc('旧密码错误!')
        // 将新密码更新到数据库中
        // 更新密码sql语句
        const sql = 'update users set password=? where id=?'
        // 对新密码进行加密处理
        const newPwd = bcryptjs.hashSync(req.body.newPwd, 10)
        db.query(sql, [newPwd, req.user.id], (err, results) => {
            // 执行sql语句失败
            if (err) return res.cc(err)
            // 执行成功 但修改的条数不为1,没有修改
            if (results.affectedRows !== 1) return res.cc('修改密码失败')
            // 修改密码成功
            res.cc('修改密码成功', 0)
        })
    })
}

        You can go to the link below to get the code in the article.

        Link: https://pan.baidu.com/s/1t7bX0Nv3kggyf7IFzEffcA Extraction code: 0000

おすすめ

転載: blog.csdn.net/h360583690/article/details/131840206