NodeJS 在Express API设计中添加类别的管理员角色

cs7cruho  于 2023-06-05  发布在  Node.js
关注(0)|答案(2)|浏览(197)

嘿,我正在测试 Postman 作为一个管理员在我的项目中添加类别,我已经成功地创建了管理员用户和登录名,但当我试图添加类别时, Postman 说:TypeError:Cannot read properties of undefined(阅读'role')有人能帮忙吗?
以下是我的用户模型:

const mongoose = require("mongoose");
const bcrypt = require("bcrypt");

const userSchema = new mongoose.Schema(
  

{
    firstName: {
      type: String,
      required: true,
      trim: true,
    },
    lastName: {
      type: String,
      required: true,
      trim: true,
    },
    email: {
      type: String,
      required: true,
      trim: true,
      unique: true,
    },
    password: {
      type: String,
      required: true,
    },
    role: {
      type: String,
      enum: ["user", "admin"],
      default: "user",
    },
  },
  { timestamps: true }
);

module.exports = mongoose.model("User", userSchema);

下面是我认证中间件:

const jwt = require("jsonwebtoken");
const User = require("../models/user");
const { signupUser, loginUser } = require("../controller/adminauth");

exports.auth = (req, res, next) => {
  try {
    if (req.header.authorization) {
      const token = req.header.authorization.split("")[1];
      const isCustomAuth = token.length < 500;

      let decodeData;
      if (token && isCustomAuth) {
        decodeData = jwt.verify(token, process.env.JWT_SECRET);
        req.UserId = decodeData?.id;
      } else {
        decodeData = jwt.decode(token);
        req.UserId = decodeData?.sub;
      }
      
    }
  } catch (error) {
    console.log(error);
    // res.status(400).json({ message: "Authorization required" });
  } next ()
};

exports.adminMiddleware = (req, res, next) => {
  if (!req.userId.role === "admin") {
    return res.status(400).json({ message: "Access denied" });
  }
  next();
};

下面是我的admin auth控制器:

const User = require("../models/user");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");

exports.loginUser = async (req, res) => {
  const { email, password } = req.body;
  try {
    const existingUser = await User.findOne({ email });
    if (!existingUser) {
      return res.status(400).json({ message: "User does not exists." });
    }

    if (!existingUser.role === "admin") {
      return res.status(400).json({ message: "User is not admin." });
    }

    const isPasswordCorrect = await bcrypt.compare(
      password,
      existingUser.password
    );

    if (!isPasswordCorrect)
      return res.status(400).json({ message: "Invalid credentials." });

    const token = jwt.sign(
      {
        email: existingUser.email,
        id: existingUser._id,
        role: existingUser.role,
      },
      process.env.JWT_SECRET,
      { expiresIn: "3d" }
    );

    res.status(200).json({ result: existingUser, token });
  } catch (error) {
    console.log(error);
  }
};

exports.signupUser = async (req, res) => {
  const { firstName, lastName, email, password, confirmPassword } = req.body;
  try {
    const existingUser = await User.findOne({ email });
    if (existingUser)
      return res.status(400).json({ message: "Admin already exists." });
    if (!password == confirmPassword)
      return res.status(400).json({ message: "Password don't match" });

    const hashedPassword = await bcrypt.hash(password, 12);

    const result = await User.create({
      email,
      password: hashedPassword,
      firstName,
      lastName,
      role: "admin",
    });

    const token = jwt.sign(
      { email: result.email, id: result._id, role: result.role },
      process.env.JWT_SECRET,
      { expiresIn: "3d" }
    );

    res.status(200).json({ result, token });
  } catch (error) {
    console.log(error);
  }
};

以下是我的分类路线:

const express = require("express");
const { addCategory, getCategories } = require("../controller/category");
const { auth, adminMiddleware } = require("../middleware/auth");
const router = express.Router();

router.post("/category/create", auth, adminMiddleware, addCategory);

router.get("/category/getcategory", getCategories);

module.exports = router;
9udxz4iz

9udxz4iz1#

在您的auth中间件中,使用以下代码更改exports.auth:

exports.auth = (req, res, next) => {
  try {
    if (req.header.authorization) {
      const token = req.header.authorization.split("")[1];
      const isCustomAuth = token.length < 500;

      let decodeData;
      if (token && isCustomAuth) {
        decodeData = jwt.verify(token, process.env.JWT_SECRET);
        req.UserId = decodeData||{}; //change this line
      } else {
        decodeData = jwt.decode(token);
        req.UserId = decodeData?.sub;
      }
      
    }
  } catch (error) {
    console.log(error);
    res.status(400).json({ message: "Authorization required" });
  } next ()
};
tcbh2hod

tcbh2hod2#

修改userSchema(删除下面的enum: ["user", "admin"],)它对我很有效。

相关问题