Represent the notion of access to a particular operation as
a Privilege. For example, in this case we want to be able to say whether the
current user is authorized to edit a particular article. That's all that's
involved here. So we need an abstraction that allows us to refer to a user, an
article, and a place to store the logic to say whether or not the operation is
authorized. Something like this:
public abstract class Privilege<T>
{
public abstract bool AuthorizedToEdit(T item, User user);
}
public class ArticlePrivilege : Privilege<Article>
{
public override bool AuthorizedToEdit(Article item, User user)
{
if(user.IsInRole(Roles.Editor)) return true;
if(user.IsInRole(Roles.Author))
{
return UserIsArticleAuthor(item,user) && ArticleNotSubmitted(item);
}
return false;
}
// implement UserIsArticleAuthor() and ArticleNotSubmitted() here
}
Now within our page, if we want to determine whether the
user is authorized to edit the article, we simply create a new privilege object
and check its AuthorizedToEdit() method. This could easily be made into an
extension method on User, Article, or both, if desired for convenience.
var articlePrivilege = new ArticlePrivilege();
if(articlePrivilege.AuthorizedToEdit(article, currentUser))
{
editLink.Visible = true;
}