Skip to content

Instantly share code, notes, and snippets.

@eyston
Created Sep 9, 2011
Embed
What would you like to do?
// 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