Created
September 9, 2011 01:46
-
-
Save eyston/1205296 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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