yoon
yoon

Reputation: 1385

How can I return when a middleware goes next()?

I use express-ip-access-control in order to do ACL checking.

My middleware function goes like this:

const ipAccessControl = require('express-ip-access-control')

function accessControl (req, res, next) {
    ipAccessControl(someOptions)(req, res, next)

    // additional ACL checking logic
    ...
    switch(result) {
        case ALLOW:
            next()
            break
        case DENY:
            res.status(400).send("denied")
    }
}

That ipAccessControl does work well, but I don't know how to return when ipAccessControl allows access and calls next().

The above code always does both ipAccessControl and additional ACL checking logic.

Is there a way to check the result of ipAccessControl, and return only when ipAccessControl calls next()?

I don't want my additional checking logic to be called when the access is allowed by ipAccessControl.

That ipAccessControl should be called before the additional ACL checking logic.

Any thought appreciated.

Upvotes: 0

Views: 62

Answers (1)

jfriend00
jfriend00

Reputation: 707158

You can pass your own function in place of next() and then you will know when it is done:

const ipAccessControl = require('express-ip-access-control')

function accessControl (req, res, next) {
    ipAccessControl(someOptions)(req, res, function(err) {
        if (err) {
            // call the actual next with the error
            return next(err);
        } else {
            // additional ACL checking logic
            ...
            switch(result) {
                case ALLOW: ...
                case DENY: ...
            }
            // when done successfully, call next() here
            // or if there's an error, then send an error response
            // or call next(err)
        }
    })

}

Upvotes: 1

Related Questions