我目前在后端nodejs express上的poster POST请求中读取role
时遇到问题。我在想我该怎么解决这个问题?
下面是在我的中间件/auth.js 中进行身份验证的路径
exports.isAuthenticatedUser = catchAsyncErrors(async (req, res, next) => {
const { token } = req.cookies
if (!token) {
return next(new ErrorHandler('Login first to access this resource.', 401))
}
const decoded = jwt.verify(token, process.env.JWT_SECRET)
req.user = await User.findById(decoded.id);
next()
})
// Handling users roles
exports.authorizeRoles = (...roles) => {
return (req, res, next) => {
if (!roles.includes(req.user.role)) {
return next(
new ErrorHandler(`Role (${req.user.role}) is not allowed to acccess this resource`, 403))
}
next()
}
}
我添加了额外的信息。希望这有助于澄清一些缺失的背景信息。但这些想法是向您展示"decoded.id"来自哪里(getJwtToken(。顺便说一句,它被用于用户帐户的注册过程中。我也分享在底部。
添加到models/users.js:
const mongoose = require('mongoose');
const validator = require('validator');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken')
const crypto = require('crypto')
const userSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Please enter your name'],
maxLength: [30, 'Your name cannot exceed 30 characters']
},
email: {
type: String,
required: [true, 'Please enter your email'],
unique: true,
validate: [validator.isEmail, 'Please enter valid email address']
},
password: {
type: String,
required: [true, 'Please enter your password'],
minlength: [6, 'Your password must be longer than 6 characters'],
select: false
},
avatar: {
public_id: {
type: String,
required: true
},
url: {
type: String,
required: true
}
},
role: {
type: String,
default: 'user'
},
createdAt: {
type: Date,
default: Date.now
},
resetPasswordToken: String,
resetPasswordExpire: Date
})
userSchema.methods.getJwtToken = function () {
return jwt.sign({ id: this._id }, process.env.JWT_SECRET, {
expiresIn: process.env.JWT_EXPIRES_TIME
});
}
controller/authController.js
exports.registerUser = catchAsyncErrors(async (req, res, next) => {
const result = await cloudinary.v2.uploader.upload(req.body.avatar, {
folder: 'avatars',
width: 150,
crop: "scale"
})
const { name, email, password } = req.body;
const user = await User.create({
name,
email,
password,
avatar: {
public_id: result.public_id,
url: result.secure_url
}
})
sendToken(user, 200, res)
})
和您的utils/jwtToken.js
const sendToken = (user, statusCode, res) => {
// Create Jwt token
const token = user.getJwtToken();
// Options for cookie
const options = {
expires: new Date(
Date.now() + process.env.COOKIE_EXPIRES_TIME * 24 * 60 * 60 * 1000
),
httpOnly: true
}
res.status(statusCode).cookie('token', token, options).json({
success: true,
token,
user
})
}
module.exports = sendToken;
错误是由于您的用户未定义。你应该处理这种情况,但如果你出于任何原因不想,你可以使用req.user?.role
:检查它是否为空
exports.authorizeRoles = (...roles) => {
return (req, res, next) => {
if (!roles.includes(req.user?.role)) {
return next(
new ErrorHandler(`Role (${req.user?.role}) is not allowed to acccess this resource`, 403))
}
next()
}
}
在这种情况下,如果未定义用户,则角色也将未定义(返回Role (${req.user.role}) is not allowed to acccess this resource
的相同错误(
空检查用户
exports.authorizeRoles = (...roles) => {
if (!req.user) //throw error (user doesn't exist in db)
return (req, res, next) => {
if (!roles.includes(req.user.role)) {
return next(
new ErrorHandler(`Role (${req.user.role}) is not allowed to acccess this resource`, 403))
}
next()
}
}