18269

Sails.js create Index(root) Controller

Question:

I was wondering if there is a way to have an index controller with an index action. my root is a login page and I wanted to detect if the users session is already authenticated and if so redirect them to another page.

Is there specific notation for how the controller is named? I have already tried IndexController.js and MainController.js. I can't seem to find anything in the documentation about this.

Sails.js Ver: 0.11.0

Answer1:

You need to make the controller and action yourself. From there, set up a <a href="http://sailsjs.org/documentation/concepts/policies" rel="nofollow">Policy</a> to define access.

To make the controller, run sails generate controller Index in console.

Then, open <strong>api/controllers/IndexController.js</strong>, make it look something like this:

module.exports = { index: function (req, res) { // add code to display logged in view } };

Set up <strong>config/routes.js</strong> to look like this:

module.exports.routes = { 'get /': 'IndexController.index', };

Afterwards, define a policy which has your authentication logic. Alternatively, you can use the included session authentication located at <strong>api/policies/sessionAuth.js</strong> assuming that your login action sets req.session.authenticated = true;. See <a href="http://sailsjs.org/documentation/concepts/policies" rel="nofollow">the docs on policies</a> for more info.

Lastly, connect the policy to the action in <strong>config/policies.js</strong>:

module.exports.policies = { IndexController: { '*': false, // set as default for IndexController actions index: 'sessionAuth' // or the name of your custom policy } }

Recommend