我不明白为什么我的验证中间件会这样
I don't understand why my verification middleware behaves this way
在最后一个比较块中,我比较的是user.rol_id是否不等于角色的id,奇怪的是按照逻辑应该是相反的,所以,我很感激对该比较中发生的事情的任何解释。
export function verifyRol(rol: string){
return async (req: Request, res: Response, next: NextFunction) => {
const id = res.locals.jwtPayload.id;
let user, rolModel;
try {
user = await User.findById(id);
if (!user) return res.status(404).json({message: 'No se encuentra el usuario'});
rolModel = await Rol.findOne({type_user: 1, name: rol});
if (!rolModel) return res.status(404).json({message: 'No se encuentra el rol'});
if (user.rol_id !== rolModel._id) {
console.log(':O');
next();
}else {
return res.status(401).json({message: 'No se encuentra autorizado'});
}
} catch (error) {
return res.status(401).json({message: 'No se encuentra autorizado'});
}
}
}
我将 TypeScript 与 NodeJS 一起使用,MongoDB
正如您所说,您所做的与您想要的相反。此外,MongoDB return 的 ID 为 ObjectId
而不是 string
,因此相等性检查将始终 return false
。如果两个对象都是 ObjectId
,您应该使用 .equals
method:
// If user has not the required role, throw a 401
if (!user.rol_id.equals(rolModel._id)) {
return res.status(401).json({message: 'No se encuentra autorizado'});
// Else, continue to the next middleware
} else {
console.log(':O');
next();
}
否则,您可以将 ObjectId
转换为字符串:
if (rolMode._id.toString() !== user.rol_id)
在最后一个比较块中,我比较的是user.rol_id是否不等于角色的id,奇怪的是按照逻辑应该是相反的,所以,我很感激对该比较中发生的事情的任何解释。
export function verifyRol(rol: string){
return async (req: Request, res: Response, next: NextFunction) => {
const id = res.locals.jwtPayload.id;
let user, rolModel;
try {
user = await User.findById(id);
if (!user) return res.status(404).json({message: 'No se encuentra el usuario'});
rolModel = await Rol.findOne({type_user: 1, name: rol});
if (!rolModel) return res.status(404).json({message: 'No se encuentra el rol'});
if (user.rol_id !== rolModel._id) {
console.log(':O');
next();
}else {
return res.status(401).json({message: 'No se encuentra autorizado'});
}
} catch (error) {
return res.status(401).json({message: 'No se encuentra autorizado'});
}
}
}
我将 TypeScript 与 NodeJS 一起使用,MongoDB
正如您所说,您所做的与您想要的相反。此外,MongoDB return 的 ID 为 ObjectId
而不是 string
,因此相等性检查将始终 return false
。如果两个对象都是 ObjectId
,您应该使用 .equals
method:
// If user has not the required role, throw a 401
if (!user.rol_id.equals(rolModel._id)) {
return res.status(401).json({message: 'No se encuentra autorizado'});
// Else, continue to the next middleware
} else {
console.log(':O');
next();
}
否则,您可以将 ObjectId
转换为字符串:
if (rolMode._id.toString() !== user.rol_id)