我们的业务有许多我们管理的网站,每个网站都有他们负责的网站等等。因此,就我们的软件的权限而言,一切都是分层的。如果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");
}
}
}
答案 0 :(得分: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, ...);