I have the following code...
const auth = new Authentication();
mainApp.use(auth.checkToken.bind(auth));
mainApp.use(mount('/auth', auth.app));
class Authentication{
constructor() {
this.redirectApp = new Koa();
this.redirectApp.use(this.onLogin);
this.logoutApp = new Koa();
this.logoutApp.use(this.onLogout);
this.callbackApp = new Koa();
this.callbackApp.use(this.onCallback);
this.app = new Koa();
this.app.use(mount('/login', this.redirectApp));
this.app.use(mount('/callback', this.callbackApp));
this.app.use(mount('/logout', this.logoutApp));
}
checkToken(ctx, next){
if(ctx.path === "/auth/login" || ctx.path === "/auth/callback" || ctx.path === "/auth/logout"){
next();
} else{
const cookie = ctx.cookies.get("userInfo");
if(cookie == null){
ctx.redirect("/auth/login");
} else{
const userInfo = JSON.parse(ctx.cookies.get("userInfo"));
if(userInfo.accessToken){
// TODO: check the token;
next();
} else{
ctx.redirect("/auth/login");
}
}
}
}
onLogin(ctx){
const path = `https://${domain}/authorize?response_type=code&client_id=${clientId}&redirect_uri=${redirectUrl}&scope=email&audience=${audience}&state=`;
ctx.redirect(path);
}
}
When I go to the root (http://localhost:3000) I can see it hit the ctx.redirect(path);
but I get a 404. If I comment out mainApp.use(auth.checkToken.bind(auth));
and hit /auth/login
directly it works fine.
Why can I not do a redirect after the initial middleware?
Fixed it with an await on next...
async checkToken(ctx, next){
if(ctx.path === "/auth/login" || ctx.path === "/auth/callback" || ctx.path === "/auth/logout"){
await next();
} else{
const cookie = ctx.cookies.get("userInfo");
if(cookie == null){
ctx.redirect("/auth/login");
} else{
const userInfo = JSON.parse(ctx.cookies.get("userInfo"));
if(userInfo.accessToken){
// TODO: check the token;
await next();
} else{
ctx.redirect("/auth/login");
}
}
}
}