Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkozhukharenko/eaaa996409c7a0b29c6f94a37b344bbc to your computer and use it in GitHub Desktop.
Save mkozhukharenko/eaaa996409c7a0b29c6f94a37b344bbc 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 next
}
).bind(this)(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