Basic Auth with Express & Mongoose

GOAL1: allow users to create an account GOAL2: validation GOAL3: functionality to login

Step 0: User Model

Step 1: display a form to create an account

  • Route (GET /signup) (inside auth.routes.js)
  • Create a view (auth/signup.hbs)
  • We've also updated layout.hbs and style.css

Step 2: process the form and create an account

  • Route (POST /signup)
  • Generate the hash/digest
  • Query DB (User.create())
  • Redirect to /userProfile (we created the view users/user-profile.hbs and a route GET /userProfile )

Step 3: validation

  • Basic Client-side validation (HTML required)
  • Some examples of Server-side validation

Step 4: functionality to login

  • Add link to login (layout.hbs)

  • Route (GET /login)

  • View (views/auth/login.hbs)

  • Route (POST /login)

    • Query DB (User.findOne())
    • Check credentials (bcryptjs.compareSync)
    • If sucessful, redirect to /userProfile
  • Send information to the view and display it (ex. the username) res.render('users/user-profile', { user });

Step 5: sesion persistance

  • Session persistance with express-session and connect-mongo

Step 6: logout

  • Route (POST /logout)
  • Add button to nav menu

Step 7: authorization & custom middleware

  • Step 7.a: boilerplate code for authorization

    • Added mock routes & links to nav
  • Step 7.b: custom roles

    • Add role to the User model
    • Drop users collection, create 3 users, change the roles directly in the DB
    • Display role info in the profile page
  • Step 7.c: authorization with custom middleware

    • isAdmin middleware (check if the user is admin) + protect the orders route
    • isStaff middleware (check if the user is admin or shopManager) + protect all routes to create a new product (GET & POST routes)