Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You're on the right track, but you can encapsulate all of the permission check into a single method like <code>GetProductForUser</code>, which takes a product, user, and the required permission. By throwing an exception that's caught in the controller's OnException handler, the handling is all in one place:</p> <pre><code>enum Permission { Forbidden = 0, Access = 1, Admin = 2 } public class ProductForbiddenException : Exception { } public class ProductsController { public Product GetProductForUser(int id, User u, Permission perm) { Product p = ProductRepository.GetProductById(id); if (ProductPermissionService.UserPermission(u, p) &lt; perm) { throw new ProductForbiddenException(); } return p; } public ActionResult Edit(int id) { User u = UserRepository.GetUserSomehowFromTheRequest(); Product p = GetProductForUser(id, u, Permission.Admin); return View(p); } public ActionResult View(int id) { User u = UserRepository.GetUserSomehowFromTheRequest(); Product p = GetProductForUser(id, u, Permission.Access); return View(p); } public override void OnException(ExceptionContext filterContext) { if (typeof(filterContext.Exception) == typeof(ProductForbiddenException)) { // handle me! } base.OnException(filterContext); } } </code></pre> <p>You just have to provide ProductPermissionService.UserPermission, to return a user's permission on a given product.By using a Permission enum (I think I've got the right syntax...) and comparing permissions with <code>&lt;</code>, Admin permissions imply Access permissions, which is pretty much always right.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload