我已经在authateUser.js中创建了authenticateUser
个中间件,
async function authenticateUser(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).json({ message: 'Unauthorized access!' });
}
try {
const accessToken = await authHeader.split(' ')[1];
// Check if the user exists and has the same access token
// Verify the JWT access token and extract the payload
const payload = jwt.verify(accessToken, process.env.ACCESS_TOKEN_SECRET);
// const role = payload.role;
const {email,uid, role} = payload;
const user = await UserClient.findOne({ email });
if (!user || user.accessToken !== accessToken) {
return res.status(401).json({ message: 'Unauthorized access!' });
}
// expose the user role , client Id from the payload object for further processing
req.role = role;
req.email = email;
req.uid = uid;
// Call the next middleware to continue with the request processing
next();
} catch (error) {
return res.status(401).json({ message: 'Unauthorized access!' });
}
}
在这里,当我需要在另一个路由中使用EMAIL值时,比方说router.get("/user",authenticateUser,async(req,res)=>{})
,我可以使用const email= req.email; console.log(email)
在users.js模块中使用EMAIL值.一百零二
我需要使用email
值的函数如下(在sites.js文件中);
async function addSitesToUser() {
try {
<-------Need to use email value here-------->
const userData = await UserClient.findOne({email});
if(!userData.siteList || userData.siteList.length === 0){
const updatedSites = await UserClient.findOneAndUpdate(
{ email },
{ $push: { siteList: { $each: sites } } },
{ upsert: true,new: true }
);
} else{
const existingSiteIds = userData.siteList.map(site => site.siteId);
// console.log("**exist: "+existingSiteIds)
const newSites = sites.filter(site => !existingSiteIds.includes(site.siteId));
// console.log("**newsit: "+newSites)
userData.siteList.push(...newSites);
await userData.save();
}
} catch (error) {
console.error('Error adding sites');
}
}
我从index.js await addSitesToUser();
中调用了上面的函数