2014-01-23 77 views
5

我试图使用routes.js来定义到'/account'的路由。SailsJS基于策略的路由视图

我想不管是谁试图访问路径要经过UserControllercheckLogin行动,如果安全检查通过,那么用户应该与定义的视图是home/account

这里呈现的是我的代码:

routes.js:

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

policies.js:

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

让我看看/account,由于某种原因没有通过isAuthenticated政策检查。

+0

快速的问题:似乎你'试图将策略逻辑放在控制器中(从“checkLogin”这个名称的声音到isAuthenticated策略中应该做的是什么),您是否修改了该策略? –

回答

4

简而言之:在routes.js的同一条路线中,不应同时使用控制器/动作风格或视图风格路由。

根据路由器的source code,一旦有一个路径对象view属性,结合停止,所以基本上帆从来不知道到哪个控制器您/account路径应被路由,这意味着你的UserController特异性政策的配置从来没有火灾。

所以,只需从路径中删除view属性,就可以始终在动作中指定显式渲染的视图路径(如果需要非标准视图路径)。

9

在这里看起来有点困惑,政策,控制器和视图的工作方式。正如@bredikhin注意到的,你的控制器永远不会被调用,因为路由被绑定到一个视图。同样重要的是要注意策略不能绑定到视图,只有给控制器。正确的设置应该是这样的:

config/routes.js

'/account': 'UserController.account' 

config/policies.js

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

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. 

    } 

api/controllers/UserController.js

module.exports = { 

    account: function(req, res) { 

    res.view('home/account'); 

    } 
} 
+0

这个'你的控制器永远不会被调用,因为路由被绑定到一个视图'是这个答案的一个非常重要的部分 – LethalyXKoded

1

对于政策的静态工作,可以设置与控制器和行动路线:

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

并设置视图/布局在您的控制器:

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