Quiz

  1. 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 in app.get and app.post.

    Here's our chain:

    1. parse body for POST requests, add info to the request object
    2. parse body for JSON requests, add info to the request object
    3. check for access to static files; if so, break the chain and handle those
    4. check for flash information in the cookies; parse and put in the flash object
    5. check for session information in the cookies; parse and put in the session object
    6. dispatch to the particular endpoint for this request, based on the URL
    7. 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:

    1. ...
    2. dispatch to the particular endpoint for this request, based on the URL
    3. Is the user logged in? If not, break the chain and go to the main endpoint.
    4. invoke the handler function with the request and response objects

    That penultimate step in the chain is done like this:

    
    function requiresLogin(req, res, next) {
      if (!req.session.loggedIn) {
        req.flash('error', 'This page requires you to be logged in - please do so.');
        return res.redirect("/");
      } else {
          next();
      }
    }
        
    app.get('/about', requiresLogin, (req,res) => {
      return res.render('about.ejs', {username: req.session.username});
    });
    
    
  2. 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