Quiz
- Could we talk more about login middleware?
Great question! I'd be glad to say more.
First, it's not necessary to use this middleware trick. The trick is nice and concise and modular — all good things — but it's okay to decide not to do this bit of cleverness in your apps. But first, let's figure out what it is.
When our app gets a request, the request goes through a chain of bits of software (functions). This is the middleware. Typically, middleware functions do something and pass the request onto the next function in the chain.
We manage the chain with the
app.use
function, as well as inapp.get
andapp.post
.Here's our chain:
- parse body for POST requests, add info to the
request
object - parse body for JSON requests, add info to the
request
object - check for access to static files; if so, break the chain and handle those
- check for flash information in the cookies; parse and put in the
flash
object - check for session information in the cookies; parse and put in
the
session
object - dispatch to the particular endpoint for this request, based on the URL
- invoke the handler function with the request and response objects
Consider the access to static files; that can break the chain and do something different. We want to do something similar for endpoints that require login. So, we insert a new step right before the end of the chain:
- ...
- dispatch to the particular endpoint for this request, based on the URL
- Is the user logged in? If not, break the chain and go to the main endpoint.
- invoke the handler function with the request and response objects
That penultimate step in the chain is done like this:
- parse body for POST requests, add info to the
- Would like examples of how to use hashing with bcrypt on our web applications.
Sure. We will review that code and make sure it's clear. Login Code