gpt4 book ai didi

javascript - 检查 `created_by` 属性后无法删除播放器对象

转载 作者:行者123 更新时间:2023-11-30 14:44:50 26 4
gpt4 key购买 nike

我有一个 DELETE 操作作为我构建的 NodeJS API 的一部分。此删除应执行以下操作:

  • 使用提供的 ID 删除播放器对象
  • 不应删除其他用户创建的播放器。

在测试中,如果播放器是由另一个用户创建的,它会通过,但在尝试删除对象时会失败。这是代码:

router.delete('/:id', validateBearerToken, function(req, res) {
let playerId = req.params.id;
//get player object
let player = Player.find({created_by: playerId
}, function(err) {
if (err) return res.status(409).send('There was a problem finding the players.');
});

if (player.created_by !== getUserFromBearerToken(req.token)) {
return res.status(404).send('The player not created by this user');
}
Player.findByIdAndRemove(playerId, function(err) {
if (err) {
return res.status(404).send('There was a problem deleting the player.');
}
res.status(200).send({
success: true
});
});
});

validateBearerToken 用于校验执行删除操作的用户是否有效

function validateBearerToken(req, res, next) {
let bearerToken;
let bearerHeader = req.headers.authorization;
if (typeof bearerHeader !== 'undefined') {
let bearer = bearerHeader.split('Bearer ');
bearerToken = bearer[1];
req.token = bearerToken;
next();
} else {
res.status(403).send();
}
}

gertUserFromBearerToken 用于获取登录用户的 id 以与测试中的 'created_by` id 进行比较:

function getUserFromBearerToken(token) {
const decodedtoken = jwt.decode(token, process.env.JWT_SECRET);
return decodedtoken.id;
}

最佳答案

你的验证中间件(validateBearerToken)应该是这样的

function validateBearerToken(req, res, next) {
var token = req.headers.authorization || req.headers['x-access-token'];
if (!token)
return res.status(403).send({ auth: false, message: 'No token provided.' });
jwt.verify(token, process.env.JWT_SECRET, function(err, decoded) {
if (err)
return res.status(500).send({ auth: false, message: 'Failed to authenticate token.' });
// if everything good, save to request for use in other routes
req.userId = decoded.id;
next();
});
}

然后在删除路由中检查这样的id

if (player.created_by !== req.userId) {
return res.status(404).send('The player not created by this user');
}

关于javascript - 检查 `created_by` 属性后无法删除播放器对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49102110/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com