【问题标题】:finding user with admin role as true查找具有管理员角色的用户为 true
【发布时间】:2022-01-29 23:59:28
【问题描述】:

我正在做一个电子商务项目,我只想让管理员为 true 的用户能够在产品集合(MongoDB 数据库)中创建和更新产品,但不知何故我弄错了,因为当我在授权中使用具有 admin true 令牌的用户作为不记名令牌我收到 catch 错误

这是我的用户模型代码

import mongoose from "mongoose";
import bcrypt from 'bcrypt'
import dotenv from 'dotenv'
dotenv.config()

const userSchema = new mongoose.Schema({
    username:{
        required:true,
        type:String
    },

    email:{
         type:String,
         unique:true,
         required:true,
    },
    password:{
        type:String,
        required:String
    },
    profilePic:{
        type:String,
        required:true,
        default:'https://t3.ftcdn.net/jpg/03/46/83/96/360_F_346839683_6nAPzbhpSkIpb8pmAwufkC7c5eD7wYws.jpg'
    },
    admin:{
        type:Boolean,
        required:true,
        default:false
    }
    
}, {
    timestamps: true
});

用于保护产品创建的中间件代码

import jwt from 'jsonwebtoken'
import asyncHandler from 'express-async-handler'
import userModel from '../models/user.model.js'


export const productCreationProtection = asyncHandler(async(req, res, next) => {

    let authorizationToken;

    if(req.headers.authorization && req.headers.authorization.startsWith('Bearer')){
        try {
            authorizationToken = req.headers.authorization.split(" ")[1]

            // decode user id
            const decode = jwt.verify(authorizationToken, process.env.PRIVATE_KEY)
            // Find the userModel and we use select to exclude password for find
            req.user = await userModel.findOne(decode.id).select('admin')
            next();

        } catch (error) {
            res.sendStatus(401)
            throw new Error("You're not authorized to performe this function")
        }

 
    }

    if(!authorizationToken){
        res.sendStatus(401)
        throw new Error("Not Authourized to performe this action")
    }
   
});

【问题讨论】:

  • error 打印到catch 块中的控制台
  • 错误>>您无权执行此功能。我该如何验证,只有拥有 admin: true 的用户才能创建产品
  • 你能在console.log(error)之前res.sendStatus(401)行并分享截图吗?
  • ObjectParameterError: findOne() 的参数“filter”必须是一个对象,得到 61f4f62338ff80c4103d3bba
  • @Dharmaraj 请帮忙解决这个问题stackoverflow.com/questions/70927598/…

标签: node.js mongodb mongoose


【解决方案1】:

findOne 方法将对象作为参数,但您传递的是字符串。如果您正在尝试查找具有给定 ID 的用户,请尝试重构您的代码,如下所示:

req.user = await userModel.findOne({ _id: decode.id }).select('admin')

// Check if admin field is true
if (!req.user.admin) {
  return "Forbidden"
} 
next()

这将返回_id 等于decode.id 的文档。如果您基于任何其他字段进行查询,请替换 _id


或者,您也可以在查询本身中添加管理字段:

const user = await userModel.findOne({ _id: decode.id, admin: true })
if (!user) {
  // User with given ID not found or is not an admin
  return "Forbidden"
}
next();

【讨论】:

  • 但是我如何验证如果用户 admin: true 是负责产品创建和更新的人,因为无论哪种方式,如果使用管理员为 false 的用户的令牌,请求仍会发送到数据库
  • @MAXWELOCHIENG 我认为您可能会在代码的后期进行任何验证。但是请检查我的更新答案。
  • 是的,第一个代码工作得很好,只有具有管理员权限的用户:true 才能向服务器发送请求
  • 对不起,我会在另一个问题中标记你,因为我正在尝试运行 app.get() 方法来获取数据库中所有产品的列表,但我得到一个空对象
  • 其实,不用我想出来,它工作得很好。谢谢,布鲁夫
猜你喜欢
  • 2016-12-17
  • 2018-04-29
  • 1970-01-01
  • 2012-06-14
  • 2012-10-09
  • 2020-02-16
  • 1970-01-01
  • 1970-01-01
  • 2017-02-15
相关资源
最近更新 更多