我正在尝试验证谁可以对文档执行PUT请求。
我有一个字段,指示创建文档的人。如果用户创建了它,则他/她可以对其进行编辑,并且该部分可以正常工作。
我还有一个用户ID数组,这些ID也应该可以编辑,但是我似乎无法检查当前用户是否在该数组中,因此我无法编辑文档。
这里是一个文件:
{
"teachers": ["5c740f96e0d6b10016801daa"],
"_id": "5cd552b179b1b30016c4c0e9",
"date": "2019-05-10T10:30:09.978Z",
"name": "prof",
"goal": "goal",
"activity": {
"affective_objectives": [],
"social_objectives": [],
"_id": "5cd552b179b1b30016c4c0ea",
"learning_objectives": [
{
"_id": "5cd552b179b1b30016c4c0eb",
"knowledge_category": "Factual",
"behaviour": "teste",
"subject_matter": "asdas",
"conditions": "",
"degree": ""
}
],
"description": "des",
"subject": "subj",
"delivery_mode": "teste",
"interaction": "teste",
"scope": "teste",
"age": 5,
"feedback_use": "High",
"interrelationship": "High",
"motivation": "High",
"participation": "High",
"performance": "None"
},
"project_manager": "5cb48f6a169a9b0016d34dac",
"__v": 0
}
还有我的PUT功能:
function edit(req, res) {
let query = {
_id : req.params.id
};
Projeto.findById(query)
.then(async (projeto) => {
if(!projeto) {
return res.status(404).json({error: 'not_found', message: 'This project doesn\'t exist.'});
}
if ( (projeto.project_manager != req.user._id) && (projeto.teachers.indexOf(req.user._id) != -1) ) {
return res.status(403).json({error: 'forbidden', message: 'You can\'t edit this project.'});
} else {
await Projeto.findOneAndUpdate(query, req.body, {new: true});
res.json({ message: 'Project successfully edited.'});
}
})
.catch(utils.handleError(req, res));
}
如果我尝试与project_manager用户进行PUT请求,则一切正常,但是与“教师”中的用户一起,我收到了我无法编辑的错误消息。
在这里验证的正确方法是什么?
答案 0 :(得分:0)
如果用户不在教师组中,则indexOf()
方法将返回-1。
因此,您需要检查是否适合您:
function edit(req, res) {
let query = {
_id : req.params.id
};
Projeto.findById(query)
.then(async (projeto) => {
if(!projeto) {
return res.status(404).json({error: 'not_found', message: 'This project doesn\'t exist.'});
}
if ( (projeto.project_manager != req.user._id) && (projeto.teachers.indexOf(req.user._id) === -1) ) {
return res.status(403).json({error: 'forbidden', message: 'You can\'t edit this project.'});
} else {
await Projeto.findOneAndUpdate(query, req.body, {new: true});
res.json({ message: 'Project successfully edited.'});
}
})
.catch(utils.handleError(req, res));
}
TLDR :
将projeto.teachers.indexOf(req.user._id) != -1
替换为projeto.teachers.indexOf(req.user._id) === -1