What your middleware is doing is basically redirecting your user to /login in case they aren't logged in (is_logged_in == false) and not trying to access /login to begin with (which would cause an endless loop where your server responds to a request for /login with "yes, you can access /login, but first visit /login to authenticate yourself").
So
is pretty much working like a normal function with an early return where you respond to your client with a http response with status code 302, without ever entering the handler for the route the user was trying to access.
The workflow is basically like this:
- Your client asks your server to access
/some_route - Your server calls your login middleware
- Your middleware sees the user is not logged in and therefore is not allowed to call this route. We respond to the client with a redirection to
/login(that's what is happening in theifstatement of your middleware) - Your client (probably a web browser like Chrome or Firefox) sees the redirect. It looks where it should redirect to (the
locationheader of the http response) - Your client makes a new http request to
/login. This new request is completely independent of the first request we made. Your middleware will be called anew and this time it will not enter theifstatement, because the user—even though they are still not signed in—is trying to access/loginthis time. - Your middleware adds the
Msgas an extension to the request - Your middleware continues by passing the request to your
/loginhandler (let res = self.service.call(request); - Your
/loginhandler extractsMsg, does something with it and returns some http response to the client
Hope that helps you in understanding what your middleware is doing there.