我们的业务有许多我们管理的网站,每个网站都有他们负责的网站等等。因此,就我们软件的权限而言,一切都是分层的。如果 site-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");
}
}
}
最佳答案
任何看起来像这样的东西:
((RolePrincipal)User).GetRoles().ToList()
...属于它自己的一个类(具有像“GetCurrentRoles”这样的接口(interface)方法),所以它很容易被模拟。
此外,这:
//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, ...)
的方法.这样你的 Controller 就可以说:
var roles = _sessionManager.GetCurrentRoles();
...
model.Edit = _orgViewRightsUtil.CanRolesEditOrganizationalView(roles, ...);
关于c# - 具有分层组织角色的应用程序角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6154681/