2015-05-29 74 views
0

我想根據用戶角色限制對某些頁面的訪問。因此,我不希望登錄用戶能夠更改其瀏覽器中的URL以導航到他們不應該訪問的頁面。所以對於這樣的路線,我正在做類似:阻止用戶導航到限制其角色的頁面

action: function() { 
    if (!Roles.userIsInRole(Meteor.user(), 'admin')) { 
     this.render("AcressRestricted"); 
    } else { 
     // Do routing for admin users here.... 
    } 
} 

這是標準的路要走嗎?我是否需要將此代碼添加到每個我想要限制的頁面,或者是否有更通用的解決方案/快捷方式?

回答

3

您可以使用Router.onBeforeAction:

Router.onBeforeAction(function() { 
    if (!Roles.userIsInRole(Meteor.user(), 'admin')) { 
     this.render("AcressRestricted"); 
    } else { 
     this.next(); 
    } 
}, {only : 'route_one', 'route_two'}); 

這將僅適用於route_oneroute_two工作。

一定要命名你在使用什麼「只有」或你的路由定義「除」:

Router.route('/' { 
    name: 'route_one', 
    ... 
}); 
+0

我沒有意識到我必須爲'except'命名路線,這可能是我的另一個問題的答案!但除此之外,我喜歡這個解決方案,我應該在與我的其他問題相同的'Router.onBeforeAction'中擁有它(http://stackoverflow.com/questions/30522609/routing-to-home-screen-when-not-signed-在)還是可以做兩個功能?再次,我今晚會嘗試一下,謝謝! – Dan

+1

@丹是可以做兩個功能的。您可以將每個分配給您想要的任何一組路線。我認爲你的問題是命名路線。與其他問題也.. – Akshat

1

你可以設置你的代碼了一點點不同,以使其更容易重複使用,和避免跨路由的任何更改複製並粘貼:

var adminFilter = function() { 


if (Meteor.logginIn()) { 
    //Logic for if they are an admin 
    this.render('loading'); 
    this.stop(); 
    } else if (!user.admin()) { 
    // Logic for if they are 
    this.render('AcressRestricted'); 
    this.stop(); 
    } 
}; 

然後只要你需要它,只是「前:」砸在沿側

Router.map(function() { 
    this.route('adminPage', { 
    path: '/admin', 
    before: adminFilter 
    }); 
}); 
+1

謝謝,把它放在一個功能當然!我會首先嚐試Akshat的答案,因爲它可以讓我一起列出所有「限制」路線,但是感謝這個主意! – Dan