Simple role management for SailsJS

You have probably heard this form me. I am working on a Sails js project and I wanted to implement a simple role management. That means that I have several routes like: “/admin”, “/login”, “/users” and I want the admin route  to be accessed only from admins, login to be accessed from admin and users and the users route to be accessed from only the users.

I have created a simple project which can be found on GitHub.

I have a Roles global object which looks like this:

global.Roles =

My user model has a roles field which is an array. It looks like this:

UserSchema = new mongoose.Schema
    type: String
    required: true
    index: true
    type: String
    required: true
    type: [String]
    required: true
    type: Boolean
    required: true
    index: true
    default: true

How stuff works?

Sails has the convention of policies. What I did was to register a api/policies/sessionAuth.js policy which determines if the current logged in user, who is stored in the req.session variable, has the role which is needed to access the route.

The role for each route can be seen in the config/routes.js file. I simply attach the custom “roles” property which is an array of Roles to the request route. Then in the sessionAuth policy I access it from the request.options.

'get /home': { controller: "HomeController", action: "getDashboard", roles: [Roles.ADMIN] }

The last step is simply to validate if the user has each of the roles required in the route. If he does not -> throw him an exception… haha.

Simple as that using policies you can attach custom properties to the route and evaluate them later in a policy. This way I made a custom property for params validation of a request. It is in my previous blog post.

You may also like...