如何整合Koa,Passport和MongoDB?

时间:2018-04-12 07:33:19

标签: node.js mongoose passport.js koa koa-passport

*请不要忽视查看其长度的问题。它似乎很长,因为我已经附加了代码。实际的问题陈述非常小。

我已尝试整合过去两天的 Passport, Koa& MongoDB 。我一直在失败,我无法获得有关我一直面临的问题的任何参考。我主要关心的是让登录模块正常工作。

我的问题是在我的索引路由中处理登录请求的函数,与koa-passport相关联,并且ctx.body也作为响应发送,但是successRedirect和failureRedirect不工作。下面是我正在使用的文件。

auth.js 中,我在新的LocalStrategy中有控制台记录用户,就在 var user = 行之后。没有任何内容记录到控制台。

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

我无法从此处推断出任何内容。我已经广泛搜索并将代码更改为工作,直到此处。

0 个答案:

没有答案