In ASP MVC we have the Authorize attribute to perform check at either a controller level or at a controller method level. But what if you need to do check permissions inside a controller method e.g let say your doing some update or create action to submit a blog post. Some users with revant permissions can attach files or make the blog post sticky. So when you are creating a new post you need to do all these additional check before saving the model. In Laravel there is the concept of abilites where you can do checks inside a controller method to see if a user has the ability to perform the relevant actions. Similarly you can use those abilitis inside views to check what item to display or hide - all this comes out of the box.
Is there anything similar in ASP MVC. How would you implement checking permissions within a controller method. Do you create a permission class with properties such as
public class Permissions
{
private readonly IPrincipal user;
public Permissions (IPrincipal user)
{
this.user = user;
}
public bool CanUploadFiles
{
get { return user.IsInAnyRole("Standard", "Admin"); }
}
public bool CanDeleteItems
{
get { return user.IsInRole("Admin"); }
}
public bool CanLockPost
{
get { return user.IsInRole("Admin"); }
}
// other permissions
}
Then inside controller action:
public ActionResult Create(PostViewModel viewModel)
{
var permissions = new Permissions(User);
if (ModelState.IsValid)
{
var post = new Post
{
if (permissions.CanLockPost)
{
post.IsLocked = viewModel.IsLocked;
}
if (permissions.CanStickyPost)
{
post.IsSticky = viewModel.IsSticky;
}
// Set other properties
}
_postRepository.Add(post);
}
}
Or would you save permissions in the database. I would like to hear your thoughts on how you go about implementing checks at a more granular level than simply at a controller or controller action level. Some code examples to demonstrate would be helpful.