从jwt获取登录id,这样只有登录的用户才能看到nodejs中的特定数据

wko9yo5t  于 2021-08-09  发布在  Java
关注(0)|答案(0)|浏览(238)

我正在使用nodejs、jwt和mysql。
我想在当前登录的用户id soo,我可以显示相应的数据。
这是我编写sql逻辑的代码,我希望得到一个当前的用户id。

const pool = require('../../dbconfig/dbconfig');
module.exports = {
    getProfile : (callBack) => {
        var sql = 'SELECT name, shopStatus, phone, shopaddress.shopNo, shopaddress.complex, shopaddress.landmark, shopaddress.street, shopaddress.area, shopaddress.city FROM shop INNER JOIN shopaddress ON shop.id = shopaddress.shop_id WHERE shop.id = ?'

        var insertSql = [ /* how can i get ID here.. */ ]

        pool.query(sql, insertSql, (err, results, fields) => {
            if(err) {
               return callBack(err)
            }
            return callBack(null, results)
        })

    }
}

这恰好是jwt中间件代码

const jwt = require('jsonwebtoken')
const config = require('../../config')

module.exports = {
  isAuth: (req, res, next) => {
    let token = req.get("authorization");
    if (token) {
      // Remove Bearer from string
      token = token.slice(7);
      jwt.verify(token, config.secret, (err, decoded) => {
        if (err) {
          return res.json({
            status: 'error',
            message: "Invalid Token..."
          });
        } else {
          req.decoded = decoded;
          next();
        }
      });
    } else {
      return res.json({
        status: 'error',
        message: "Access Denied! Unauthorized User"
      });
    }
  }
};

这是控制器

const shopService = require('./shop.service')

module.exports = {
    shopProfile : (req, res) => {
        shopService.getProfile((err, results) => {
            if(err){
               return res.status(500).json({
                    status : 'error',
                    error : err,
                    message : 'Database connection error'
                })
            }
            return res.status(200).json({
                status:'success',
                data : results
            })
        })
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题