Skip to content

Instantly share code, notes, and snippets.

@moustacheful
Last active June 9, 2016 23:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save moustacheful/f548495b6818d98191d70769dc35b76d to your computer and use it in GitHub Desktop.
Save moustacheful/f548495b6818d98191d70769dc35b76d to your computer and use it in GitHub Desktop.
Koa passport.authenticate wrapper
// koa-passport-authenticate.js
'use strict'
const _ = require('lodash')
const passport = require('koa-passport')
'use strict'
// Middleware wrapper for koa passport to have proper error handling on authenticate.
const _ = require('lodash')
const passport = require('koa-passport')
module.exports = function (strategyName){
return function *(next){
let self = this
yield passport.authenticate(strategyName,
function *(err,user,reason){
if(err){
throw new Error(err)
}
_.set(self.state,`passport.${strategyName}`,{
user: user,
reason: reason
});
yield self.login(user)
}
).bind(this)(next);
yield next
}
}
// routes.js
'use strict'
const koaPassportAuth = require('koa-passport-authenticate');
router.post('/login', koaPassportAuth('local'), function *(next){
// You can get the results from passport's middleware from context.state
// under this.state.passport.${yourStrategyName} - In this case, 'local'
if(this.state.passport.local.user){
this.redirect('/success');
}else{
this.flash.error = this.state.passport.local.reason;
this.redirect('/login');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment