thegeek
thegeek

Reputation: 127

What is the right way to determine user roles and grant API access in Node.js Web-Server?

I have a Web-server with REST APIs in Node.js-express setup. I have different APIs exposed and i use OAuth to authenticate users. Once i identify user i retrieve his role and decide to grant permission for an API. The problem is all my APIs have code repeated and all of them have to check the role and determine the permissions. Is there any better way to do this? Should i look at ACL? In general i am novice in Web-services and may not be aware of best solutions. Thanks.

Example code :

var accessCallback = function (err, user) {
    if(err == null) {
        var userRole = getUserRole (user.role_id);
        if(userRole == ROLE.SUPERVISOR || userRole == ROLE.MANAGER || userRole == ROLE.EMPLOYEE){
            doStuff(); //business logic
        }
        else {
            response.status(400).send (error.UserAccessDeniedError());
        }
    }
    else {
        response.status(500).send(error.DatabaseError(err));
    }
};

access.determineUser (req.body.tokenID, accessCallback);

Upvotes: 1

Views: 161

Answers (1)

DrakaSAN
DrakaSAN

Reputation: 7853

What you could do is declare a list of roles that allow the user, and check if the user's role is in that list:

var userRole = getUserRole(user.role_id);

function foo(error, user) {
    if(error == null) {
        var authorizedRoles = [
                ROLE.SUPERVISOR,
                ROLE.MANAGER
            ];
        if(authorizedRoles.indexOf(userRole) > -1) {
            //Authorized
        } else {
            //Error
        }
    } //...

Then, you can configure the authorized roles of each of your API point, and even put the verification in a middleware function.

Upvotes: 1

Related Questions