views:

35

answers:

2

I added the AuthorizeAttribute to secure my ActionResult.

[Authorize(Roles = "MyUser, Admin")]
    public ActionResult Index()
    {
        var allData = myDataRepository.FindAllData();
        return View(allData);
    }

The Index view displays a list of data from my table. I want to show 1 row is the user Role is MyUser and all rows if the Role is Admin.

Is the correct (MVC) way just checking for the user Role and doing an if else?

A: 

I believe you are going to want to include the role limitation to your repository and allow that to determine what data to return.

var allData = myDataRepository.FindAllDataForRole(roleName);

Hal

Hal
If I extend this idea on the response from alexn - it would be something like var allData.MyDataRepository.FindAllDataForRole(HttpContext.Current.User.IsInRole("Admin") ? "Admin" : "");I just prefer to keep decisions like that out of the view and let the view display whatever I throw at it.
Hal
A: 

If the User (or their role) is a proper domain object to you, and is altering the results of your Index() metohd, then the Index method itself should take said user as a parameter, first off.

The Authorize filter is about whether the person should be able to execute a given action at all, not about what data they can see in that action.

As Hal said, the user's role should then be applied as a criteria in your query of the repository, or perhaps apply the user itself as a criteria (if, for example, a single user has rights by several roles plus individual user rights).

Something like this, then:

[Authorize(Roles="MyUser, Admin")]
public ViewResult Index(User user)
{
     return View(repo.GetDataForUser(user));
}

Then, inside your repository's GetDataForUser method, you do whatever filtering on rights or whatever.

Paul