I have this middleware
我有一个中间件
const isAuthenticated = (req, res, next) => {
const token = req.cookies.token;
if (token) {
//Se il token esiste devo comunque verificare che sia valido
try {
const payload = jwt.verify(token, process.env.JWT_SECRET);
req.user = { userId: payload.userId, name: payload.name };
next();
} catch (error) {
throw new UnauthenticatedError(
"You have to login to access protected area"
);
//next(error);
}
} else {
//token non esiste
throw new UnauthenticatedError(
"You have to login to access protected area"
);
}
};
export { isAuthenticated };
and this controller:
和这个控制器:
const createJob = async (req, res) => {
//res.send(req.user);
const jobCreated = await jobModel.create(
[{ ...req.body, createdBy: req.user.userId }],
{
sanitizeFilter: true,
}
);
res.status(StatusCodes.CREATED).send(jobCreated[0]);
};
In my routes I have
在我的道路上,我有
router.route("/").post(isAuthenticated , createJob)
I'm using the middleware before the controller to check if the user can access the protected route (with a jwt token inside a cookie)
我在控制器之前使用中间件来检查用户是否可以访问受保护的路由(在Cookie中使用JWT令牌)
My question is:
Is sure attach user in req.user in the middleware isAuthenticated? req is a global object shared by all requests. If another request comes (another client) (before JobModel.create()
is called) can overwrite the user property on the req of the previous request before await jobModel.create
is executed (thus obtaining erroneous results)?
我的问题是:中间件中req.user中的Attach User是否已通过身份验证?Req是由所有请求共享的全局对象。如果另一个请求到来(另一个客户端)(在调用JobModel.create()之前),是否可以在等待jobModel.create执行之前覆盖前一个请求请求的User属性(从而获得错误的结果)?
更多回答
优秀答案推荐
我是一名优秀的程序员,十分优秀!