0 points

To set Passport session


dashboard

Mon Aug 17 2020 16:18:23 GMT+0000 (UTC)

Posted by @brainyworld #nodejs #javascript

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

passport.use(new LocalStrategy({
    usernameField: 'email'
}, async (email, password, done)=>{
    try{    
    const user = await User.findOne({ email })
        if (!user) return done(null, false, { message: 'User not exists' })
        if (!await user.checkPassword(password)) return done(null, false, { message: 'Incorrect Password' })
        return done(null, user)
    } catch (e) {
        
        return done(e)
    }
}
))

passport.serializeUser((user, done)=>{
    return done(null, user._id)
})

passport.deserializeUser(async (_id, done) => {
    try {
        const user = await User.findOne({ _id })
        return done(null, user)
    } catch (e) {
        return done(e)
    }
})





//place this one on the route
router.post('/login', (req, res, next) => {
  console.log(req.body.email)
  passport.authenticate('local', (err, user, info) => {
    if (err) {
      req.session.flashData = {
        message: {
          type: 'error',
          body: 'Login failed'
          }
      }
      return res.redirect('/user/login')
      }
    // Let check for user
    if (!user) {
      req.session.flashData = {
        message: {
          type: 'error',
          body: info.message
        }
      }
      return res.redirect('/user/login')
    }
    req.logIn(user, (err) => {
      if (err) {
        req.session.flashData = {
          message: {
            type: 'error',
            body: 'Login failed'
          }
        }
      }
      return res.redirect('/task/viewtask')
    })
  })(req, res, next)
})


//place this on index.js

// For Passport to work with session
app.use(passport.initialize());
app.use(passport.session());
content_copy Copy