Enable authentication in KAPTL Sails.js app

Stas Demchuk

by Stas Demchuk on 11/17/2015

Sails.js

Sails.js has a lot of helper modules and generators that help you configure authentication and authorization. It is also built on top of Express, which means we can use Express middlewares like Passport to configure our own super secure authentication system.

We recommend to do this via sails-generate-auth module, because this module does all the routine and leaves you just the bare minimum of configuration before authentication actually works.

First, install the generator via npm install sails-generate-auth. As soon as that's done, you should be able to generate a scaffold for your auth system with sails generate auth command. But, when you run that, you'll receive an error stating that something already exists in config/locales/en.json. You should move or delete that file as well as the services/protocols directory, and re-run the generator.

After that, choose Passport providers you'll use. Open config/passport.js and comment/delete the configurations you don't need. You'll have to install passport modules for the providers you will use, like npm install passport passport-twitter passport-local passport-google --save and fill in client IDs and secrets for the active configs.

Next, configure the routes. Paste following code above the '/' route definition:

'get /login': 'AuthController.login',
'get /logout': 'AuthController.logout',
'get /register': 'AuthController.register',
'post /auth/local': 'AuthController.callback',
'post /auth/local/:action': 'AuthController.callback',
'get /auth/:provider': 'AuthController.provider',
'get /auth/:provider/callback': 'AuthController.callback',

And finally, secure the routes with a policy in config/policies.js:

'*': [ 'sessionAuth', 'passport' ]

sessionAuth is responsible for checking if the user is authenticated and sending 403 if not. passport just sets the value of res.locals.user to req.user once Passport is initialized. To customize these behaviors, check the file with a policy name you wish to customize in api/policies directory.

What about roles?

There is another handy generator called sails-permissions. To install it, run npm install sails-permissions.

Afterwards, configure .sailsrc:

{
  "generators": {
    "modules": {
      "permissions-api": "sails-permissions/generator"
    }
  }
}

Finally, run sails generate permissions-api and use the generated code. Detailed documentation on sails-permissions features like creating and managing user's roles and permissions is available here.

Have any questions or suggestions? Let us know in the comments!