这是我使用的代码
auth.js
const passport = require('koa-passport')
const options = {
server: {
...
}
};
passport.serializeUser(function(user, done) {
done(null, user)
})
passport.deserializeUser(function(user, done) {
done(null, user)
})
const ldapStrategy = require('passport-ldapauth').Strategy
passport.use(new ldapStrategy(options, function(user, done, error) {
done(null, user)
}))
index.js
const Koa = require('koa')
const app = new Koa()
// trust proxy
app.proxy = true
// sessions
const convert = require('koa-convert')
const session = require('koa-generic-session')
app.keys = ['your-session-secret']
app.use(convert(session()))
// body parser
const bodyParser = require('koa-bodyparser')
app.use(bodyParser())
// authentication
require('./auth')
const passport = require('koa-passport')
app.use(passport.initialize())
app.use(passport.session())
// routes
const fs = require('fs')
const route = require('koa-route')
app.use(route.get('/', function(ctx) {
ctx.type = 'html'
ctx.body = fs.createReadStream('views/login.html')
}))
app.use(route.post('/login', (ctx, next) => {
passport.authenticate('ldapauth', { session: false }, (err, user, info, status) => {
if (user === false) {
ctx.body = { success: false }
throw new TypeError('cannot construct abstract class')
} else {
// ctx.body = { success: true }
ctx.login(user.cn)
ctx.redirect('/app')
}
})(ctx, next)
}))
app.use(route.get('/logout', function(ctx) {
ctx.logout()
ctx.redirect('/')
}))
// Require authentication for now
app.use(function(ctx, next) {
if (ctx.isAuthenticated()) {
return next()
} else {
ctx.redirect('/')
}
})
app.use(route.get('/app', function(ctx) {
ctx.type = 'html'
ctx.body = fs.createReadStream('views/app.html')
}))
// start server
const port = process.env.PORT || 3000
app.listen(port, () => console.log('Server listening on', port))
错误信息
./../../koa-passport-example/server.js:53 throw new TypeError('error test') ^ TypeError: 错误测试
我需要如何修改中间件来修复它?有更好的方法来完成此认证吗?