javascript - 检索验证用户的订单
问题描述
- 获取方法
- 使用
accessToken
经过身份验证的用户。 - 只有非管理员帐户才能继续。
- 用户应该只能检索他的订单。
路由器
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
});
}
我得到了一切。有人可以帮我编写代码如何过滤令牌所属的用户并检索他的订单并且无法获取其他用户的订单吗?
解决方案
通过在您的方法中传递一个空对象.find
,您是在告诉 mongodb 查找所有内容。我假设body
您有一些数据可以找到特定用户,如果是这样,您会使用它。例如。如果body
包含用户名,你会写...
module.exports.getMyOrders = (body) => {
return User.find({username: body.username});
}
这是有关 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});
}
推荐阅读
- node.js - 如何使用 Joi 验证我的 request.body 中存在的某些特定字段?
- arrays - 有没有办法从Scala中的给定数组创建n个元素的子数组块?
- java - 找不到符号,符号:方法
- react-native - 世博会开始永远显示“在港口启动 Metro Bundler”
- python-3.x - Python 多处理似乎正在影响程序的结果
- python - 数据帧的平均值
- javascript - How to validate form based on values and submit call out to another page accordingly?
- c++ - 如何在 C++ 中输出分栏符
- bash - 查找内部管道内的 awk 命令
- node.js - 在一个响应中流式传输多个文件 - Node.js