NodeJS 这个令牌验证码会有什么错误?

06odsfpq  于 2022-11-04  发布在  Node.js
关注(0)|答案(1)|浏览(128)

在我的route中进行中间件请求时,总是会陷入“verifyAdmin”的else(错误403),最大的问题是我无法发送该错误的throw或catch,它只是在终端不返回任何错误,但在postman中测试时总是会转到else

const jwt = require('jsonwebtoken');

const verifyToken = (req, res, next) => {
    const { authorization } = req.headers;

    if (!authorization) {
        return res.status(401).json('Invalid Authorization')
    };

    const token = authorization.replace('Bearer', ' ').trim();

    try {
        const secret = process.env.JWT_SECRET;
        const data = jwt.verify(token, secret);
        req.users = data;

        const { id } = data;

        req.userId = id;  

        return next();
    } catch (err) {
        return res.status(400).json(err);
    }
  };

  const verifyAdmin = (req, res, next) => {
        if (req.users.isAdmin === true) {
            next();
        } else {
            return res.status(403).json("You are not alowed to do that!");
        }
  };

module.exports = {
  verifyToken,
  verifyAdmin,
};

在航线上

const { verifyToken, verifyAdmin } = require('../middlewares/verifyToken');

router.get('/', verifyToken, verifyAdmin, FindAllUsersController.index);

建构记号

const db = require('../../models/index');

const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');

exports.store = async (req, res) => {
    const { email, password } = req.body;
    const secret = process.env.JWT_SECRET;

    try {
        const user = await db.User.findOne({ where: { email } });

        if (!user) {
            return res.status(401).json('User does not exist');
        }

        const isValidPassword = await bcrypt.compare(password, user.password);

        if (!isValidPassword) {
            return res.status(401).json('Password is not valid');
        }

        const token = jwt.sign({ id: user.id }, secret, {
            expiresIn: process.env.EXPIRES_TOKEN,
        })

        return res.status(200).json({
            user,
            token,
        });

    } catch (err) {
        console.log(err);
    }
}
bpzcxfmw

bpzcxfmw1#

isAdmin标志不包含在您的token中,因为在构造它时您只包含了id

const token = jwt.sign({ id: user.id }, ...)

您需要(至少):

const token = jwt.sign({ id: user.id, isAdmin: user.isAdmin }, ...)

相关问题