SailsJS Policy based route with a view

[亡魂溺海] 提交于 2019-12-05 22:47:08

问题


I'm trying to use the routes.js to define a route to '/account'.

I want whoever is trying to access that path to go through the UserController and the checkLogin action and if the security check passes, then the user should be rendered with the defined view which is home/account

Here is my code:

routes.js:

'/account': {
    controller: 'UserController',
    action: 'checkLogin',
    view: 'home/account'
  }

policies.js:

UserController: {
    '*': 'isAuthenticated',
    'login': true,
    'checkLogin': true
  }

It let's me view /account without going through the isAuthenticated policy check for some reason.


回答1:


There looks to be a little confusion here as to how policies, controllers and views work. As @bredikhin notes above, your controller will never be called because the route is being bound to a view. It's also important to note that policies cannot be bound to views, only to controllers. The correct setup should be something like:

In config/routes.js:

'/account': 'UserController.account'

In config/policies.js:

UserController: {
  '*': 'isAuthenticated' // will run on all UserController actions
  // or
  'account': 'isAuthenticated' // will run just on account action
}

In api/policies/isAuthenticated.js:

    module.exports = function(req, res, next) {

     // Your auth code here, returning next() if auth passes, otherwise
     // res.forbidden(), or throw error, or redirect, etc.

    }

In api/controllers/UserController.js:

module.exports = {

  account: function(req, res) {

     res.view('home/account');

  }
}



回答2:


To put it short: either controller/action-style or view-style routing should be used within the same route in routes.js, not both simultaneously.

According to the router's source code, once there is a view property in a route object, binding stops, so basically Sails never knows to which controller your /account path should be routed, which means that your UserController-specific policy config never fires.

So, just remove the view property from the route, you can always specify the view path (if you want a non-standard one) with explicit rendering from within your action.




回答3:


For statics work with policies, you can set your route with controller and action:

'GET /login': 'AuthController.index',

And set view/layout in your controller:

index: function (req, res) {
    res.view('auth/login', { layout: 'path/layout' } );
},


来源:https://stackoverflow.com/questions/21303217/sailsjs-policy-based-route-with-a-view

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!