rkusa/koa-passport

The callback in ctx.login() is not being executed, "Error: Failed to serialize user into session"

devt3000 opened this issue · 9 comments

ctx.login(payload, err => {

    if (err) {
      ctx.status.response = 400;
      ctx.response.body = { error: "dick 2" };
    } else {
     // generate a signed json web token and return it in the response
      const token = jwt.sign(JSON.stringify(payload), secret);
      console.log(token);

     // assign our jwt to the cookie
      ctx.cookies.set("jwt", jwt, { httpOnly: true, secure: true });
      ctx.response.status = 200;
      ctx.response.body = { username };
    }
  });

I'm using console.log() to see if the token is being generated but there is nothing in the output.

pub.post('/login', (ctx,next)=>{
if(ctx.isAuthenticated()){
if(ctx.state.xhr){
ctx.throw(409, 'Schon authenticated!')
}else{
return ctx.redirect('/')
}
}
return passport.authenticate('local', (err,user,info,status)=>{
if(ctx.state.xhr){
if(err){ctx.body={success:false,info:err.message}; ctx.throw(500,err.message);}
if(user===false){
ctx.body={success:false,info:info.message}
ctx.throw(401,info.message)
}else{
ctx.body={success:true,info:info.message, redirect:ctx.session.dorthin || '/'}
return ctx.login(user)
}
}else{
if(err){
ctx.session.bmessage={success:false,error:err.message}; return ctx.redirect('/login');
}
if(user===false){
ctx.session.bmessage={success:false, error:info.message};
ctx.redirect('/login')
}else{
ctx.redirect(ctx.session.dorthin || '/')
return ctx.login(user)
}
}
}
)(ctx,next)
})

Thanks. That isn't sessionless authentication though, I'm trying to use JWTs here.

Aha, may be you should to disable session in options in a function passport.authenticate('basic', {session: false}, ....)

Or may be in a jwt based application you should use this https://github.com/koajs/jwt

@Globik I'm using the npm package "jsonwebtoken", it's good.

@Globik okay, I will try that asap.

if (!user) { ctx.body = { success: false }; ctx.throw(401); } else { const payload = { username: user.username, expires: Date.now() + 1000000 };

  token = jwt.sign(JSON.stringify(payload), secret);
  ctx.cookies.set("jwt", token, { httpOnly: true, secure: false });
  ctx.body = { success: true };

  return ctx.login(user);
}

})(ctx); await next();

This code fixed my issue. Thanks!