删除用户并从所有设备注销该用户



我想在我的应用程序中实现一个功能。管理员可以删除用户。所以基本上删除工作正常,但不知何故,我不能注销登录用户。让我解释更简单,假设有一个用户目前使用我的程序和管理决定从应用所以不能删除该用户不再访问应用程序的特性。删除用户,我可以叫一个API和删除用户,但如果我完全删除用户它失去了所有访问的API调用,因为用户与特定ID不再可用和app减免因为删除用户的API调用会失败。所以我想知道是否有在管理员删除用户后注销用户的方法。

前端是在ReactJs和后端是在NodeJs。我使用JWT进行身份验证。如果这个问题不是很清楚,请让我知道,这样我可以解释得更多。

在后端,在每个受保护的路由中,你应该验证令牌,令牌应该包含用户id或电子邮件,你将使用它来验证令牌。在删除用户抛出错误而没有找到用户之后,在前端确保如果存在没有用户找到的错误,那么它将删除JWT令牌。

我想到的是在请求和服务器之间放置一个中间件。通过这样做,而不是试图从所有设备注销,我们将不允许任何操作,如果用户不存在;在这个示例中,我们将阻止用户在前端删除位置和toast消息。我将分享一个例子,但是你需要根据你的需要调整代码。

Http错误模型

class HttpError extends Error {
constructor(message, errorCode) {
super(message);
this.code = errorCode;
}
}
module.exports = HttpError;

中间件

const HttpError = require('../models/http-error');
module.exports = (req, res, next) => {
try {
// Check user if exists
User.findById(req.userData.userId).exec(function (error, user) {
if (error) {
throw new Error('Authentication failed!');
}
else {
return next();
}
});
}
catch (error) {
return next(new HttpError('Authentication failed!', 403));
}
};

路线
const express = require('express');
const router = express.Router();
const checkAuth = require('../middleware/check-auth');
router.use(checkAuth);
// Put after any routes that you want the user to be logged in
router.delete('/:placeId', placesControllers.deletePlace); //e.x.
...
module.exports = router;

E.x。控制器(MongoDB)

const deletePlace = async (req, res, next) => {
const placeId = req.params.placeId;
let foundPlace;
try {
foundPlace = await Place.findById(placeId).populate('userId').exec();
}
catch (error) {
return next(new HttpError('Could not find the place, please try again', 500));
}
// Delete place
res.status(200).json({message: 'Deleted place'});
};

前端部件

import toastr from 'toastr';
....
try {
const response = await fetch(url, {method, body, headers});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message);
}
}
catch(error) {
// handle the error, user not found
console.log(error.message);
toastr.error(error.message, 'Error', {
closeButton: true,
positionClass: 'toast-top-right',
timeOut: 2000,
extendedTimeOut: 1,
});
}

最新更新