[英]meteor-useraccounts and alanning meteor-roles - Check role on sign-in
是否可以檢查“登錄”上的用戶角色,並且比方說用戶是否以“管理員”角色顯示一個頁面,是否可以以“基本用戶”角色顯示另一個頁面(轉到另一條路線)。
讓我們看一下useraccounts:iron-routing軟件包的文檔的Routes部分。
這應該可以解決您的問題
AccountsTemplates.configureRoute('signIn', {
redirect: function(){
var user = Meteor.user();
if (user && Roles.userIsInRole(user, ['admin'])) {
Router.go('admin');
}
else {
Router.go('home');
}
}
});
請仔細檢查您是否可以從客戶端訪問用戶roles
字段:讓我們查看allanning:roles官方文檔
要為用戶定義默認角色,請使用以下命令:
// server
Accounts.onLogin(function(user) {
var user = user.user;
var defaultRole = ['student'];
if (!user.roles){
Roles.addUsersToRoles(user, defaultRole)
};
})
我正在使用流星用戶帳戶和alaning meteor-roles軟件包,對我來說很好用。
如果我沒有過時的話(看看http://docs.meteor.com/#/full/meteor_users表示我不是),那么用戶角色就不會內置。 對於該任務,應該有一些擴展名,您可以根據自己選擇的內容檢查其文檔。
但是,在Meteor中實現自己的簡單角色邏輯並不是很困難:
首先,在Accounts.onCreateUser
函數中為用戶對象提供新的屬性role
並將其分配給默認角色。 如果您沒有Accounts.onCreateUser
,則創建一個服務器端。 它可能看起來像這樣:
Accounts.onCreateUser(function(options, user) {
// Add an user roles array
user.roles = ["default-user"];
if (options.profile)
user.profile = options.profile;
return user;
}
接下來,您將需要實現一些邏輯,以將"admin"
或您喜歡的對信任用戶的任何內容添加到其角色數組中。 這取決於您,對於剛開始沒有大量管理員的情況,您還可以選擇在MongoDB中手動進行。
現在,確保將用戶對象的新屬性發布給當前登錄的用戶。 為此,請使用以null
為第一個參數的Meteor.publish
來尋址當前用戶,如下所示:
Meteor.publish(null, function () {
return Meteor.users.find({_id: this.userId}, {fields: {
'roles': 1,
'profile': 1, // You probably want to publish the profile of a user to himself
// And here would be any other custom stuff you need
}});
});
這樣一來,您已經可以進行單獨的樣式設置或路由客戶端。 例如,您可以執行以下操作:
if (Meteor.user().roles.indexOf("admin") > -1) {
// Route for admins!
}
您還可以解析數組,並將用戶角色作為類添加到body
元素中,例如僅向管理員顯示某些元素。 這可以通過以下方式完成:
Meteor.user().roles.forEach(function(role){
$('body').addClass(role);
});
請注意,這僅是“美容”,但您也可以在服務器端實現真正的安全性。 因此,如果您只希望管理員可以使用Meteoer訂閱或Meteor方法,請向其添加以下內容:
var requestingUser = Meteor.users.findOne({ '_id': this.userId});
if (!_.contains(requestingUser.roles, "admin")) {
// Terminate the pbulish function or Meteor method here when there is no "admin" role
return;
}
如前所述,這僅在服務器端有效,應在Meteor.publish
函數的開始或Meteor.methods
塊中函數的開始。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.