- [Instructor] The account route that we want to change
is in server, routes, users, index.js
and way down we see here this get route for account.
We learned about middlewares before
and we know that the middleware
can call the next one in the chain or end the request.
So I'm going to add a middleware to the route
before the page is rendered.
For that I add request, response, next,
let's do the comma here already
and in this middleware function I will now simple check
if request user means this is a logged in user, return, next
and in any other case we will return res.status401
and then we will end the request.
So this is a quite hard error, we could of course also
redirect the user then to the login form.
Let's restart application and see if this works as intended.
I reload the page with the error from before
and we see that we now get an ERROR 401.
This is a good example on how we can chain middlewares
to enforce rules that need to apply
before we call the next middleware.
Let's add a little enhancement for the sake
of consistency real quick.
What if a user by accident ends up on the registration
or login page despite being logged in?
We should redirect them to their account page.
As we need this functionality on two routes,
I will now simply create a function
and I create that outside of this module export.
Add a function, redirect if logged in,
it takes request, response, next.
And here I will simple check if request user is set,
so the user is logged in
and in this case I want to redirect to /users/account.
In any other case we will simply pass the control
on to the next middleware in the chain,
which is most probably the one that renders the page done.
To apply this middleware we now simply have to
copy it into the get route for /login
and the one for /registration.
Let's restart the application,
let's head back to the page.
And on this page I will now log in with my credentials
and now I will navigate to /users/registration
and this leads me back to account.
and let's try the same for /login
and this works as well.
With that we are done with implementing
authenticating authorization for our project.
In the next chapters we will learn how to upload files
and manipulate images in Express.