Last active
June 9, 2016 23:00
-
-
Save moustacheful/f548495b6818d98191d70769dc35b76d to your computer and use it in GitHub Desktop.
Koa passport.authenticate wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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