Closed daisycrego closed 3 years ago
/**
* Load event and append to req.
*/
const eventById = async (req, res, next, id) => {
try {
const userId = jwt.verify(
req.headers.authorization.split(" ")[1],
config.jwtSecret
);
let user = await User.findById(userId);
req.profile = user;
} catch (err) {
console.log(err);
return res.status("400").json({
error: "Could not retrieve user",
});
}
try {
let event = await Event.findById(id);
if (!event)
return res.status("400").json({
error: "event not found",
});
req.event = event;
next();
} catch (err) {
return res.status("400").json({
error: "Could not retrieve event",
});
}
};
req.profile
was previously only being set if a route has userId
as a parameter. Now, we're also defining req.profile
for event routes as well, specifically the update route so far. This code isn't exactly in the right place right now... but it will work for all the events routes, so let's keep moving forward.
Within the
api-event.js
(frontend wrappers aroundfetch
calls to the express server endpoints), we have anupdate
function which we will use to update the event status:PUT
operation is failing with the error that the user is not authorized to perform this action. The reason why we aren't identifying the user as logged in is because what's happening in the background:event.routes.js
:router.param("eventId", eventCtrl.eventById);
auth
routes, including thePUT
route, we protect the routes by running theauthCtrl.hasAuthorization
middleware when we are loading the routes. The middleware will prevent theupdate
andremove
routes from ever being reached unless the middleware passes.authCtrl.hasAuthorization
middleware:hasAuthorization
is called,req.auth
is defined, butreq.profile
is not defined. When isreq.profile
supposed to be set in the first place?req.profile
is set in theuserById
middleware:userById
middleware is currently only being used to protect/wrap/prepare the user routes, not the event routes. None of the event routes take auserId
param.Solutions
userId
parameter to the/events
route so that the incoming requests will havereq.profile
set correctly.req.profile
somewhere else based on the bearer token (e.g. the user shouldn't have to pass their ID in the route, we should be able to infer the ID from the cookies/token if present).