Prevent User from logging again in passportjs if they are authenticated once? Prevent User from logging again in passportjs if they are authenticated once? mongoose mongoose

Prevent User from logging again in passportjs if they are authenticated once?


You have not created any sort of access control, but don't worry we will first go through how Passport works and use this to address the problem.

  1. When the user submits a login form, a POST request to our specified path is made resulting in the execution of the passport.authenticate.
  2. The authenticate middleware for that route is configured to handle the local strategy, passport will invoke your implementation of the local strategy.
  3. If an error occurs while interacting with our database, we invoke done(err). Otherwise if the user is not found or the passwords do not match, we invoke done(null, false). If successful we invoke done(null, user).

Calling done will return us to the passport.authenticate and the corresponding redirect will be executed.

At this point, if the sign-in was successful, the user object (from done(null, user)) is attached to the request and you can access the user object through req.user.

The main idea is if the user object is not attached to the request it means the user is not logged in, so we can control our application behaviour for logged in users with req.user. For example:

// If the user object does not exist it means the user is not logged in    if (!req.user) {        res.render('signin');    } else {// If the user object exists, the user is logged in and if they try to log in we redirect them to the home page        return res.redirect('/');    }

I hope this helps.