passport.jskoa2koa-routerkoa-passport

How to encapsulate Koa-Passport?


Perhaps this has a very easy answer, yet something is off with my code. Here is what I want to do.

I created a koa2 app using koa-passport, and I want to encapsulate the usage of Passport in a class AuthAdapter (shortened below).

class AuthAdapter {
    setup(koaApp) {
        koaApp.use(passport.initialize());

        passport.use('http-bearer', new PassportHttpBearerStrategy(function(token, done) {
            koaApp.log.info('passport: payload request', token);
            return done(null, { clientId: 1 });
        }));
    }

    async authroute(ctx, next) {
        return passport.authenticate('http-bearer', (error, user, info) => {
            if (error) {
                ctx.throw(500, 'Authentication Error');
            } if (!user) {
                ctx.throw(403, 'Authentication Forbidden');
            } else {
                ctx.log.debug('Passport-Route-Mw: auth ok', { user: user, info: info });
            }
        })(ctx, next);
    }
}

And I have an API class and declared the routes like:

static _setupRoutes(koaApp, koaRouter) {
    koaRouter
        .get('getter', '/getter', koaApp.authAdapter.authroute, MyApi.myGetterMethod);
    koaApp
        .use(koaRouter.routes())
        .use(koaRouter.allowedMethods());
}

... MyApi

static async myGetterMethod(ctx) {
   ...
}

Now the problem: setup and setupRoutes are getting called correctly. Passport verify is executing, adn the authroute method is also executing.

My problem is that myGetterMethod is not.

My suspicion is that by encapsulating the passport.authenticate, the "return" is not running as it should.

How should that be implemented? await?

UPDATE: thanks for the answer below, indeed that was the solution, so my method ended up like this:

async function authenticate(ctx, next) {
    // https://github.com/rkusa/koa-passport/issues/125#issuecomment-462614317

    return passport.authenticate('http-bearer', { session: false }, async(err, user, info) => {
        if (err || !user) {
            ctx.throw(401, 'passport-auth: user unauthenticated');
        }

        await next();
    })(ctx);
};

Solution

  • i think you need call next in callback, because koa-passport will stop call next when you provide custom callback

    koa-passport

    line 94: call custom callback will always call resolve(false)

    line 149: if resolve(cont !== false) call next

    as the result, use custom callback will stop chain. you need call next in your callback.