In KrakenJS, how to declare the Passport middleware before another one?

216 views Asked by At

I'm using Passport for authentication in my Kraken project. When I call authenticate, I pass "failWithError: true" so an error is passed to the "next" callback. I then have an errorHandler middleware declared like this in the config.json:

"errorHandler": {
    "priority": 130,
    "module": "path:./lib/errorHandler"
}

My problem is that passport returns the error directly, so I guess it's a problem of priorities.

I have tried registering passport like this:

app.requestBeforeRoute = function requestBeforeRoute(server) {
    server.use(passport.initialize());
};
passport.use(auth.localApiKeyStrategy());

And like this:

app.on('middleware:before:errorHandler', function (eventargs) {
    passport.use(auth.localApiKeyStrategy());
    app.use(passport.initialize());
});

But it's not working. Also, I found this: Adding a way to configure a scope to factory function but I haven't really got how to make it work.

Thank you very much.

1

There are 1 answers

0
Enric A. On BEST ANSWER

So, finally I came out with a solution. In my case I don't need the session middleware from passport, as I'm developing a REST API.

First, the passport declaration in config.json:

"passport": {
    "enabled": true,
    "priority": 10,
    "module": {
        "name": "passport",
        "method": "initialize"
    }
}

Then in index.js, I say passport to use my strategy:

passport.use(auth.localApiKeyStrategy());

Finally, in the controller of the model I implemented a custom callback as the Passport docs say you can, that I located in auth.js

router.get('/', function(req, res, next) {
    auth.authenticate(req, res, next, function() {
        // authenticated
        // stuff to do when authenticated
    });
});

// auth.js
exports.authenticate = function(req, res, next, callback) {
    passport.authenticate('localapikey', function(err, device) {
        if (err) {
            return next(err);
        }
        if (!device) {
            err = new Error();
            err.code = statusWell.UNAUTHORIZED;
            return next(err);
        }
        callback();
    })(req, res, next);
};

Now I can handle authentication and pass the error to my errorHandler middleware later using the next function.