MongoDB: How to implement Passport + Express+ MongoDB

MongoDB: How to implement Passport + Express+ MongoDB
0

I initially had passport setup to where I lets users register and login, but everything was saved in an array. But I am wanting to replace the array and save it to a database. At the moment my server.js is set up like this, which allows me to register users.

I have the database setup and connected already. I just don’t know how to properly merge it with pass port. Right now I have everything set up in my server.js like

const mongoose = require('mongoose');
  const User = require('./models/users')

 const initializePassport = require('./passport-config')
  initializePassport(
    passport,
    email => User.find({email: email}),
    id => User.find({id: id})
  )

  
  app.post('/register', checkNotAuthenticated, async (req, res) => {
    try {
      const hashedPassword = await bcrypt.hash(req.body.password, 10)
      const newUser = new User({
        id: Date.now().toString(),
        name: req.body.name,
        email: req.body.email,
        password: hashedPassword
      })
      res.redirect('/login')
      console.log(newUser)
    } catch {
      res.redirect('/register')
    }

And my Passport-Config.js file like this `

const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt');
const User = require('./models/users')

function initialize(passport, getUserByEmail, getUserById) {
  const authenticateUser = async (email, password, done) => {
    const user = getUserByEmail(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, User.findById({user: id}))
  })
}

`

I already had that installed

Examples

For a complete example implementing a registration, login and logout see the login example.

source