Node.js+Express+Mysql 实现用户密码MD5加密及验证

发布时间:2024年01月06日

安装加密组件

npm install crypto-js 

加密算法

let password = CryptoJS.MD5('123456').toString();

创建用户代码

router.post('/api/user/add', async (req, res) => {

    let status = 1;
    let password = "123456";
    password = CryptoJS.MD5(password).toString();
    
    let sqlStr = 'INSERT into sys_user(id, username, realname, phone, password, status) VALUES (?,?,?,?,?,?);'
    let id = sysUtils.getNewId();
    let result = query(sqlStr, [id, req.body.username, req.body.realname, req.body.phone, password, status]);
    if (req.body.userRoles != null) {
        sqlStr = 'delete from sys_user_role where user_id = ?';
        await query(sqlStr, [id]);
        req.body.userRoles.forEach(async item => {
            let detailId = sysUtils.getNewId();
            sqlStr = 'insert into sys_user_role(id,user_id,role_id) values(?,?,?)';
            await query(sqlStr, [detailId,id,item]);        
        });
    }

    res.send({
        status: 200,
        success : true,
        message: "添加成功",
        data : result
    })

})

登录验证代码

router.get('/api/user/login', async (req, res) => {

    let username = req.query.username;
    let password = CryptoJS.MD5(req.query.password).toString();
    let sqlStr = `SELECT * FROM sys_user where username= ? and password=?`
    let result = await query(sqlStr, [username,password]);

    if (result.length > 0) {
        let data = result[0];
        sqlStr = 'select * from sys_menu order by index_id'
        data.menus =  await query(sqlStr);  ;   
        sqlStr = `select * from sys_menu where id in (select menu_id from sys_role_menu where role_id in (select role_id from sys_user_role where user_id=?)) order by index_id`;
        data.myMenus = await query(sqlStr, [data.id]);
        sqlStr = 'select * from sys_role'
        data.roles =  await query(sqlStr); 
        console.log(data);
        res.send({
            status: 200,
            success : true,
            message: '用户登录成功',
            data: data,
        })
    } else {
        console.log(result);
        res.send({
            success : false,
            status: 200,
            message: '用户名或密码错误',
        })
    }
})

代码中用到了数据库同步查询、防sql注入写法,其他章节有介绍,这里不过多赘述。

文章来源:https://blog.csdn.net/gdgztt/article/details/135416914
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。