You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

帖子授权逻辑失效:编辑操作致作者变更,疑与save方法有关?

问题分析与解决方案

哦,我一眼就揪出问题所在了——你在权限判断的地方犯了一个超级容易踩的语法坑,这直接导致了权限失效和作者被篡改的问题!

核心错误:赋值运算符代替了比较运算符

你代码里的这行判断:

if (post.author = req.user._id) {

这里的=是赋值运算符,不是比较用的==或===!这行代码会直接把当前登录用户的_id赋值给post.author,然后因为赋值表达式的结果就是被赋的值(只要不是null/undefined这类假值),所以这个条件永远为真。

这就造成了两个问题:

  • 不管原帖子的作者是谁,权限判断都会通过,完全起不到限制作用
  • 你每次点击编辑时,都会把帖子的作者改成当前登录用户,这就是你看到的“更改帖子作者”的原因

正确的实现方式

首先要把判断改成比较操作,另外还要注意:MongoDB中post.author是ObjectId类型,而req.user._id可能是字符串或者另一个ObjectId实例,直接用===可能会因为类型不匹配导致比较失败,所以更稳妥的是用mongoose提供的equals()方法来比较ObjectId。

下面是修正后的完整代码:

router.put('/posts/:id', passport.authenticate('jwt'), (req, res) => {
  Post.findOne({ _id: req.params.id }, (err, post) => {
    if (err) throw err;
    // 先判断帖子是否存在
    if (!post) {
      return res.json({ success: false, message: 'Post not found.' });
    }
    // 用equals方法比较ObjectId,确保权限判断正确
    if (post.author.equals(req.user._id)) {
      // 更新帖子内容,修正原代码里的逗号分隔错误
      post.title = req.body.title;
      post.content = req.body.content;
      post.postImageUrl = req.body.postImageUrl;
      
      post.save((err, updatedPost) => {
        if (err) throw err;
        res.json({ message: 'You have successfully updated your post', success: true });
      });
    } else {
      res.json({ success: false, message: 'You are not allowed to do this.' });
    }
  });
});

额外优化建议

你当前的代码用了嵌套回调,可读性较差,建议改用async/await语法让代码更清晰:

router.put('/posts/:id', passport.authenticate('jwt'), async (req, res) => {
  try {
    const post = await Post.findOne({ _id: req.params.id });
    if (!post) {
      return res.json({ success: false, message: 'Post not found.' });
    }
    if (!post.author.equals(req.user._id)) {
      return res.json({ success: false, message: 'You are not allowed to do this.' });
    }
    post.title = req.body.title;
    post.content = req.body.content;
    post.postImageUrl = req.body.postImageUrl;
    await post.save();
    res.json({ message: 'You have successfully updated your post', success: true });
  } catch (err) {
    res.status(500).json({ success: false, message: err.message });
  }
});

内容的提问来源于stack exchange,提问作者Merim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:26:30