Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Way To Access User Permissions From View

In my ASP.NET MVC site, my set up allows users to have roles, and roles have permissions. Generally, these permissions are set for a controller. In my site's main navigational menu, an Authenticated user can see all items, even if they aren't authorized to access that page.

Currently I can only configure the menu based off if the user is authenticated:

@if (Request.IsAuthenticated){ }

I'm wondering, what's the best way to pass the user's permissions to a view, only for the sake of configuring the menu for that user? Is there some common way of doing it, or will I have to implement this myself? I haven't found much information on it, but maybe I'm using the wrong search terms.

Thanks for any advice.

EDIT

Sorry I may not have been clear enough. This is my main nav menu, in the _Layout page. Also, permissions assigned to a role are very configurable by an admin (they can also create and delete roles), so checking if the user is in a role won't meet my needs.

like image 661
Jonesopolis Avatar asked Oct 02 '22 17:10

Jonesopolis


2 Answers

You could create an action in say, the CommonController, which returns a partial view containing your navigation. This partial view can have its own model which can be populated from the controller. This allows you to use dependency injection for instance.

The action could look like this:

[ChildActionOnly]
public ActionResult Navigation()
{
    var model = new NavigationModel();
    // populate the model..

    return PartialView("_Navigation", model);
}

You can render this partial in your view (_Layout.cshtml in your case) like this:

@Html.Action("Navigation", "Common")

For most cases, Request.IsAuthenticated is just fine. Only use this if you need something more advanced.

like image 68
Henk Mollema Avatar answered Oct 05 '22 12:10

Henk Mollema


You can use Roles class static method IsUserInRole:

@if (Roles.IsUserInRole("Admin"))
{
   // ...
}
like image 37
Eric.Y.Fan Avatar answered Oct 05 '22 10:10

Eric.Y.Fan