2011-05-27 126 views
3

我們的業務擁有多個我們管理的網站,並且這些網站中的每個網站都有他們負責的網站等等。因此,就軟件權限而言,所有內容都是分層次的。如果站點-X中的人員想要編輯site-X和任何子站點-X的內容,則應該允許他們訪問。我們也有應用程序角色,主要是管理員,可以讓一個人編輯所有內容並維護應用程序。具有分層組織角色的應用程序角色

我目前正在處理這個應用程序的權限,我已經得到了一切工作,但我真的很討厭它。它笨重,不太可測試,並且看起來不像它在我的MVC應用程序的正確位置。我希望有人對我如何重構這段代碼有一些想法,並讓它變得更重要,更可測試,並且可能使它更加有用。

預先感謝您。

public class OuController : BaseController { 
    private readonly IOrganizationUnitRepository repo; 

    public OUController(IOrganizationUnitRepository repo) { 
     this.repo = repo; 
    } 

    public ActionResult Details(string site) { 

     //Get the site we are viewing 
     var ou = repo.GetOuByName(site); 

     //make sure the site really exists 
     if (ou != null) { 

     //Get all the roles for the current user via the role provider 
     //will return the sites they are able to manage along with 
     //any application roles they have 
     var roles = ((RolePrincipal)User).GetRoles().ToList(); 

     //Get all the parents of the current ou, this will include itself 
     var parents = repo.GetParents(ou, new List<OU>()); 

     //create a new viewmodel object 
     //ou is used for details obviously 
     //parents are used for a breadcrumb 
     var model = new OrganizationalViewModel(ou, parents); 

     //if a user has no roles, there is no way he can possibly edit 
     if (roles.Any()) { 
      if(roles.Contains(InfoRoles.Administrator.ToString())) { 

      model.CanEdit = true; 

      } else if(parents == null) { 

      //If there are no parents, check if this ou is in users list of roles 
      model.CanEdit = roles.Contains(ou.DisplayName); 

      } else { 

      //check to see if any of the roles i have are parents of the current ou 
      model.CanEdit = parents.Any(c => roles.Contains(c.DisplayName)); 

      } 

     } 

     return View("Details", model); 

     } 

     return View("NotFound"); 

    } 
    } 
} 

回答

2

任何看起來像這樣:

((RolePrincipal)User).GetRoles().ToList() 

...屬於一個它自己的階級(包含「GetCurrentRoles」接口方法),所以它可以很容易地嘲笑。

而且,這樣的:

//if a user has no roles, there is no way he can possibly edit 
    if (roles.Any()) { 
     if(roles.Contains(InfoRoles.Administrator.ToString())) { 

     return true; 

     } else if(parents == null) { 

     //If there are no parents, check if this ou is in users list of roles 
     return roles.Contains(ou.DisplayName); 

     } else { 

     //check to see if any of the roles i have are parents of the current ou 
     return parents.Any(c => roles.Contains(c.DisplayName)); 

     } 

...屬於在一種稱爲像CanRolesEditOrganizationalView(IEnumerable<RolePrinciple> roles, ...)一個實用工具類。這樣你的控制器就可以說:

var roles = _sessionManager.GetCurrentRoles(); 
... 
model.Edit = _orgViewRightsUtil.CanRolesEditOrganizationalView(roles, ...); 
相關問題