【发布时间】: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/…