具有分层组织角色的应用程序角色

本文关键字:角色 应用程序 分层 | 更新日期: 2023-09-27 17:57:54

我们的业务有许多我们管理的网站,每个网站都有他们负责的网站等等。因此,就我们软件的权限而言,一切都是分层的。如果站点X上的人想编辑站点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");
    }
  }
}

具有分层组织角色的应用程序角色

任何看起来像这样的东西:

((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, ...);