2016-12-07 41 views
0

我正在創建一個包含4個角色的管理面板。管理員擁有所有數據的權限。組織者角色可以訪問他的數據。第三個角色可以訪問組織者允許的數據。 4rth角色可以訪問3rth角色允許的權限。如何管理角色和查詢?

在CRUD操作我使用此代碼獲取當前用戶ID:

var currentUser = Guid.Parse(Thread.CurrentPrincipal.Identity.GetUserId()); 

,並通過此ID數據訪問層。如果當前用戶是所需實體的所有者,則CRUD操作將執行。 在數據訪問leyer我checkes如果當前用戶ID相匹配的實體的用戶ID,然後它讓做了手術:

var product=_dbContext.Products.Where(x=>x.UserId==currentUser && x.ProductId== productId); 

但我希望管理員能夠執行這些操作了。我知道我可以根據當前用戶角色編寫多個方法來執行相同的操作。但是有沒有更清晰的解決方案?

例如,主辦方可以編輯id = 1的產品,因爲他是該產品的所有者,id = 1。但我想,也可以編輯id = 1的產品。

回答

0

我認爲你在尋找這樣的事情......

var rolesForUser = await userManager.GetRolesAsync(currentUser); 
Product product; 

if (rolesForUser.Contains("Admin")) 
{ 
    product = _dbContext.Products.Where(x.ProductId == productId); 
} 
else 
{ 
    product = _dbContext.Products.Where(x => x.UserId == currentUser && x.ProductId == productId); 
}