gpt4 book ai didi

Attach a property to the global req object in the middleware and use it in a controller with concurrent client requests(将属性附加到中间件中全局请求对象,并在具有并发客户端请求的控制器中使用它)

转载 作者:bug小助手 更新时间:2023-10-25 11:18:51 24 4
gpt4 key购买 nike



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属性(从而获得错误的结果)?


更多回答
优秀答案推荐
更多回答

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