【问题标题】:I don't understand why my verification middleware behaves this way我不明白为什么我的验证中间件会这样
【发布时间】:2019-09-18 15:16:25
【问题描述】:

在最后一个比较块中,我比较的是 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 一起使用

【问题讨论】:

  • 当两个 id 值匹配或不匹配时应该发生什么?
  • 请不要只是发布和消失。您获得帮助的最佳机会来自第一批参与的人,如果您不在身边,人们会继续做其他事情,而其他人则认为缺乏参与。

标签: node.js mongodb typescript mongoose middleware


【解决方案1】:

正如你所说的那样,你正在做与你想要的相反的事情。此外,MongoDB 将 ids 返回为ObjectId 而不是string,因此相等性检查将始终返回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)

【讨论】:

  • 只有当rolModel._id不同时才通过比较块,如果不相等则不起作用。
  • 好的,我明白了,我们在这里比较 MongoDB ObjectId。我已经更新了我的答案。
  • 感谢您的通俗易懂的回答,现在我对 mongodb 的工作原理有了更深入的了解。
  • 很高兴为您提供帮助!您可以接受并投票赞成答案,以便未来的读者知道它是正确的。
猜你喜欢
  • 2020-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-17
  • 1970-01-01
  • 2016-02-03
  • 2021-04-10
相关资源
最近更新 更多