【问题标题】:Only Owner (creator) can edit/delete Entry expressJS只有所有者(创建者)可以编辑/删除条目 expressJS
【发布时间】:2018-06-22 09:11:51
【问题描述】:

我如何编写一个中间件来批准条目的唯一所有者来编辑/删除/?

我尝试搜索每个条目(在每个条目中都有 userId),然后将当前用户的 UserId 与条目中的 userId 进行比较。 但这不是好方法

【问题讨论】:

    标签: express authentication


    【解决方案1】:

    为了能够验证这一点,你需要知道两件事:

    • 当前用户是谁
    • 元素的所有者是谁

    从我可以推断出你的问题,你有 userId,我假设它在请求中。

    现在,条目怎么样。您希望删除的条目很可能在数据库中,因此您必须查询数据库以查找元素并查看所有者是否是当前用户。记住永远不要相信来自 REST 客户端的任何东西

    下面是一个可以为您完成此任务的中间件的概要:

    const validateOwner = (req, res, next) => {
      const entryId = req.params.entryId || req.body.entryId;
      if (entryId === undefined) {
        return res.status(400).send('missing entryid);
      }
      const userId = req.user.userId;
    
      Database.findEntryWithId(entryId).then(entry => {
        if (entry.ownerId === userId) {
          next();
        } else {
          return res.status(403).send('Forbidden Action');
        }
      }).catch(() => {
        return res.status(500).send('Internal Server Error');
      };
    };
    

    使用中间件进行删除

    app.delete('/api/entries/:entryId', validateOwner, (req, res) => {
      //Delete logic
      res.send('Element was deleted');
    });
    

    使用中间件进行更新

    app.put('/api/entries/', validateOwner, (req, res) => {
      //Delete logic
      res.send('Element was deleted');
    });
    

    由于用户可以在客户端更改entryId并将其发送回服务器,因此我们必须从数据库中验证entryId,而不是信任body中的id。

    【讨论】:

      猜你喜欢
      • 2015-05-23
      • 2019-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-11
      • 1970-01-01
      • 2016-10-31
      相关资源
      最近更新 更多