【问题标题】:Retrieve Authenticate User's Orders检索验证用户的订单
【发布时间】:2021-06-10 16:25:31
【问题描述】:
  1. GET 方法
  2. 使用经过身份验证的用户的accessToken
  3. 只有非管理员帐户才能继续。
  4. 用户应该只能检索他的订单。

路由器

router.get("/my-orders", auth.verify, (req, res) => {

    const user = auth.decode(req.headers.authorization);

    if (!user.isAdmin) {

        UserController.getMyOrders(req.body).then(getMine => res.send(getMine));


    } else {

        return res.status(403).send("Access denied.");
    }

});```

控制器

module.exports.getMyOrders = (body) => {

    return User.find({}, {
        "isAdmin": 0,
        "_id": 0,
        "password": 0
    });
}

我得到了一切。有人可以帮我编写代码如何过滤令牌所属的用户并检索他的订单并且无法获取其他用户的订单吗?

【问题讨论】:

    标签: javascript object mongoose


    【解决方案1】:

    通过在 .find 方法中传递一个空对象,您是在告诉 mongodb 查找所有内容。我假设在body 您有一些数据可以找到特定用户,如果是这样,您会使用它。例如。如果body 包含用户名,你会写...

    module.exports.getMyOrders = (body) => {
        return User.find({username: body.username});
    }
    

    Here is some more info on db.collection.find()

    编辑 - 通过 JWT 查找用户:

    router.get("/my-orders", auth.verify, (req, res) => {
        //Here you have decoded your JWT and saved it as user
        const user = auth.decode(req.headers.authorization);
    
        if (!user.isAdmin) {
            //here you are passing user instead of req.body
            UserController.getMyOrders(user).then(getMine => res.send(getMine));
    
    
        } else {
    
            return res.status(403).send("Access denied.");
        }
    
    });
    

    module.exports.getMyOrders = (user) => {
        //now you are using 'username' from the decoded jwt to look up the user
        return User.find({username: user.username});
    }
    

    【讨论】:

    • 如何声明订单属于JWT?
    • 看起来您将解码后的 JWT 保存在 user 变量中,因此您需要将 user 传递给您的 getMyOrders 函数,然后使用解码后的 JWT 中的信息来查看向上用户。我添加了一个编辑来证明这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-26
    • 1970-01-01
    • 2022-06-27
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多