So, I'll start by adding validation here to the added route as well and for that I'll
just highlight it and say also add validation here and I hope that GitHub Copilot takes
the other surrounding code into account and hence updates the code appropriately and that
looks good to me.
It's essentially the same checks as before when we created an event.
So that looks good and therefore as a next step we can move on and protect some of our
event routes.
Make sure that some of these routes can only be visited by authenticated users.
Now keep in mind for that we have this util folder with the auth.js file where we have
the verifyToken function and this function can be used to find out whether an incoming
token, a token that has been attached to an incoming request is valid or not.
Now actually we should also have another utility function here and actually it is the function
GitHub Copilot is suggesting to me here which is pretty nice.
So yeah, I want to have this function here really.
VerifyUtility function which receives an incoming request and which parses the token
from the request headers there specifically from an authorization header.
It extracts the token from that header like this because the header will actually be something
like bearer and then the token.
That's just a convention of adding the token to HTTP requests.
So this will just give us the token and then it uses verifyToken, this function here, which
we therefore technically wouldn't even need to export since we're using it in the same
file but it doesn't matter.
So we're using this function to decode and in the same step also verify the token because
this step here will fail if the token is invalid.
Verify will throw an error if it's an invalid token.
So we either return an error response here or we store the decoded token, the content
of the token therefore, which is that user data which we encode here, the ID and the
email.
That's the data we encode in the token and that's what we store in the request under
a user object.
And then next here is just a function that ensures that the next so-called middleware
in line, the next function that should handle the incoming request becomes active.
Otherwise an error is thrown or an error response is sent back.
So this authenticate function here can now be used as a so-called middleware before other
middleware functions.
For example, all these route functions are middleware functions so that before these
functions become active, we check whether we have a valid token.
If we don't, we send back an error response.
If we do, we activate the next function, the next middleware in line.