Mohamed Rashiq
Mohamed Rashiq

Reputation: 322

How to Authorize APIs in passport js ( Set up APIs that can only accessible some privileged type of users)?

I have been working on API authentication using passport js. Now i have to write APIs that can be accessible by only some privileged type of users.(some APIs are accessible to admin only.Some for Vendors). In user model i have specified role of each user(if the user is admin,vendor or customer).

I have solved similar problem in drop-wizard using "drop-wizard-auth".

If the user does not have the privilege to access the API it should show error-403

Please share link or advise that can solve my problem.

Upvotes: 0

Views: 338

Answers (1)

zshan4444
zshan4444

Reputation: 430

Try this solution:

In model users, you have "user_type" field which receive below integers.

// model for user 

module.exports = (sequelize, DataTypes) => {

let users = sequelize.define ('users', {

    id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, field: 'id' },
    name: { type: DataTypes.STRING (50), field: 'name' },
    ..
    user_type: { type: DataTypes.INTEGER, field: 'user_type' } // 0 for admin, 1 for vendor, 2 for customer 
    },
});
 return users;
};

The below function will be passport.js file which checks that this user has the correct role to hit this endpoint or not.

passport.isAuthorized = ( userType ) => {
  return (req, res, next) => {
    if (userType == 0) { // mean its admin 
        if (req.user.user_type == 0) { // user value stored in req through deserialize fucntion
            return next(); // user has correct admin role
        } else {
          return next({ error: 'Please need admin level access to hit endpoint' 
         });
       }
    } else if (userType == 1) { // mean its vendor 
        if (req.user.user_type == 1) {
            return next(); // user has correct vendor role
        } else {
          return next({ error: 'Please need vendor level access to hit endpoint' 
        }
    } else if (userType == 2) { // mean its custumer
        if (req.user.user_type == 2) {
            return next(); // user has correct custumer role
        } else {
          return next({ error: 'Please need customer level access to hit endpoint' 
        }
    }
    return next({ error: 'something!went wrong.' });
  };
};

In routes file, you just need to add these middlewares.

app.post('baseURL/get-user-list',
    passport.isAuthenticated, // check user is authorized or not
    passport.isAuthorized(1), // check user role, if you want to check for admin pass 0, for vendor pass 1, for customer pass 2
    controllerUser.getUser
);

Upvotes: 1

Related Questions