Skip to content

Passport

rvdegroen edited this page Jun 22, 2022 · 5 revisions

Table of Contents

In our project we have a log in and a registration so the user can log in and see the dishes they have entered. In this function we are using passport and session. But what is passport?

What is passport?

Passport is authentication middleware for Node.js. It's Extremely flexible and modular, Passport can be unobtrusively dropped in to any Express-based web application.

What's the use of passport?

By using passport you can verify the user. Of course, if a user does not exist, he/she cannot log in. But also random internet users cannot just go into the application without being logged in. You can only enter the application if you are logged in and not otherwise

Configuration

To make the passport work you need a configuration. Here you basically explain what you want the passport to do for you. In this file I compare the emails from the user with the entered email and the entered password with the hashed password in the database. If the data is not equal then the user gets the error message that can help him / her further on the road.

const LocalStrategy = require("passport-local").Strategy;
const bcrypt = require("bcrypt");

const { ObjectId } = require("mongodb");

async function initialize(passport) {

  const authenticateUser = async (email, password, done) => {

    const user = await userCollection.findOne({email : email});


    if (user == null) {
      return done(null, false, { message: "No user with that email" });
    }

    try {
      if (await bcrypt.compare(password, user.password)) {
        return done(null, user);
      } else {
        return done(null, false, { message: "Password incorrect" });
      }

    } catch (e) {
      return done(e);
    }
  };

  passport.use(new LocalStrategy({ usernameField: "email" }, authenticateUser));
  passport.serializeUser((user, done) => done(null, user._id));
  passport.deserializeUser((id, done) => {
    return done( null, userCollection.findOne({_id: ObjectId(id)}) );
  });
}

module.exports = initialize;

It is important that you give feedback to the customer because otherwise the customer does not know what he/she has done wrong.

After passport is set you can go to the login rout and add the local to the passport. The local also has an error check.

app.post(
  "/",
  passport.authenticate("local", {
    successRedirect: "/dishes-overview",
    failureRedirect: "/login",
    failureFlash: true,
  })
);

Because if something has gone wrong then the user will be redirected to another page that if all goes well. If something goes wrong the user is sent back to the login page. This means that :

  1. The password does not match the email address
  2. The user cannot be found in the database
  3. What rarely occurs is a possible system error.

And if it goes right the user is sent to the home screen because then everything is entered correctly.

Clone this wiki locally