psvs
psvs

Reputation: 199

How to integrate Koa, Passport and MongoDB?

*Please don't ignore the question looking at its length. It might seem long because I've attached the code. The actual problem statement is really small.

I've tried integrating Passport, Koa & MongoDB from the last two days. I've been failing and am unable to get any references regarding the problem I've been facing. My primary concern is to just get the login module working.

My problem is that the function to handle post request for login in my index routes, associated with koa-passport is being called and ctx.body is also being sent as a response but successRedirect and failureRedirect aren't working. Down below are the files that I'm using.

In the auth.js, I have console logged user inside the new LocalStrategy, right after var user = line. Nothing is logged to the console.

auth.js

const passport = require('koa-passport')
const LocalStretegy = require('passport-local').Strategy
const mongoose = require('mongoose')

const User =  mongoose.model('User', mongoose.Schema({}, { strict: false }))

function *getUser(name) {
  let user = yield User.find({username: name})
  return user
}

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

passport.deserializeUser( async (id, done) => {
  done(null, user)
})

passport.use(new LocalStretegy( (username, password, done) => {
  co(function*() {
    try {
      var user = yield getUser(username)
      if (user.username === username && user.password === password) {
        return user
      } else {
        return null
      }
    } catch(e) {
      return null
    }
  }).then((user) => {
    done(null, user)
  })
}))

module.exports = passport

/routes/index.js

const router = require('koa-router')()
const sendfile = require('koa-sendfile')
const passport = require('koa-passport')
const mongoose = require('mongoose')

const Counter = mongoose.model('Counter', mongoose.Schema({}, { strict: false }))

router.post('/custom', (ctx, next) => {
  return passport.authenticate('local', function(user, info, status) {
    if (user === false) {
      ctx.status = 401
      ctx.body = { success: false }
      ctx.body = { success: true }
    } else {
      return ctx.login(user)
    }
  })(ctx, next)
})

router.post('/login', (ctx) => {
  passport.authenticate('local', {
    successRedirect: '/dash-board',
    failureRedirect: '/login'
  })
  ctx.body={status: 'okay'}
})

router.get('/logout', (ctx) => {
  ctx.logout()
  ctx.redirect('/')
})

module.exports = router

app.js

const Koa = require('koa')
const router = require('koa-router')()
const app = new Koa()

app.proxy = true

//Routes
const users = require('./routes/users')
const index = require('./routes/index')

//Error handler
const onerror = require('koa-onerror')
onerror(app)

//MongoDB connection
const mongoose = require('mongoose')
mongoose.Promise = global.Promise
try{
  mongoose.connect('mongodb://<user>:<pass>@<something>.mlab.com:<number>/<someDB>?poolSize=10&retries=5')
} catch(err) {
  console.log(err)
}

// Sessions
const convert = require('koa-convert')
const session = require('koa-generic-session')
const MongoStore = require('koa-generic-session-mongo')
app.keys = ['key1']
app.use(convert(session({
  store: new MongoStore()
})))

//body parser
const bodyparser = require('koa-bodyparser')
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))

//passport
require('./auth')
const passport = require('koa-passport')
app.use(passport.initialize())
app.use(passport.session())

app.use(index.routes(), index.allowedMethods(),                                     users.prefix('/index'))

app.use((ctx, next) => {
  if(ctx.isAuthenticated()) {
    return next()
  } else {
    ctx.redirect('/')
  }
})

app.use((ctx, next) => {
  return next().catch(function (err) {
    ctx.status = err.status || 500;
    if (err.expose) {
      ctx.body = err.message;
    }
  })
})

module.exports = app

I am unable to deduce anything from here on. I've searched extensively and changed the code to work until here.

Upvotes: 1

Views: 901

Answers (1)

Vincent Cantin
Vincent Cantin

Reputation: 17272

Maybe it has something to do with this code in which user does not seem to be declared.

passport.deserializeUser( async (id, done) => {
  done(null, user)
})

Upvotes: 0

Related Questions