-
-
Save mkozhukharenko/eaaa996409c7a0b29c6f94a37b344bbc to your computer and use it in GitHub Desktop.
Koa passport.authenticate wrapper
This file contains hidden or 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 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