Skip to content

Instantly share code, notes, and snippets.

@eyston
Created September 9, 2011 01:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eyston/1205296 to your computer and use it in GitHub Desktop.
Save eyston/1205296 to your computer and use it in GitHub Desktop.
// controller
[CanViewProfile]
public ActionResult Show(int id)
{
var view = new ShowProfileQuery(id).Execute();
return View(view);
}
// before filter
// CurrentUser is property injected every request since the filter is a singleton
public class CanViewProfile : AuthorizationAttribute
{
public User CurrentUser { get; set; }
protected override bool Authorized(ActionExecutingContext filterContext)
{
var id = idFromActionParameters(filterContext);
if (CurrentUser.IsAdmin)
return true;
if(CurrentUser.ProfileId == id)
return true;
return false;
}
private int idFromActionParameters(ActionExecutingContext filterContext)
{
return (int)filterContext.ActionParameters.Single(ap => ap.Key == "id").Value;
}
}
// so the filter logic can be tested outside of the controller.
// but testing that the filter is applied to the action ... not possible in
// ASP.NET MVC outside of hitting the server
// so this class has two responsibilties
// 1) extracting the information from the filter context / request
// 2) performing authorization logic
//
// pretty clear place you can separate this ... if you weren't lazy like me
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment