简体   繁体   中英

koa-router and passport chaining results into callback

Alright , so I recently migrated from express to koa and my main question here is regarding koa-router and passport authentication.

Back in express i was able to do something like

router.route('/someroute')
      .post(passport.authenticate('local' , {session:false}) , 
                                  function(req,res,next){req.authresult});

what basically happened is once authenticated with the passport strategy , whatever object was returned in the strategy would be funneled into the REQ object where i could access it in the main controller function . Convenient right ?

Alright this is how koa does it , well afaik :

router.post('/someroute' , function(ctx,next){
return passport.authenticate('jwt' ,(err,user,info,status) =>{ 
           ....
 })(ctx);

Now that this situation is explained , my questions are :

1. Is it possible to do the routing like express , something like

router.post('/someroute',passport.authenticate(..),function(ctx){ ctx.user 
});

2. Why do i get a not found result if i don't pass the ctx object like

passport.authenticate(...)(ctx);

What is this kind of implementation called , putting an object into a defined method .. where do i learn about it ?

As usual, i have done some research and am ready to answer the question myself.

1.Yes , it is possible to do the routing like express without declaring the custom callback for passport authenticate.

router.post('../someroute',passport.authenticate('strategy',options),function(ctx){
//access passport return object through ctx.state.user
}

however the drawbacks of this are , if the strategy returns an error like done(err) , the error handling will not be done by your route callback rather will automatically be responded to with an internal server error by koa. If you wish to return an auth related error , it has to be done through the same ctx.state.user object with added properties .

2.passport.authenticate() returns a function , that expects a req,res/ctx object therefore not providing that will result in an error (internal promise rejection,no ctx provided) . In the above declaration , router.post handles this automatically.However , declaring it inside another function will require you to pass ctx.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM