Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of User.IsInRole() in a View

In my mvc5 project to disable an action link for unauthorized users i did like this

@if (User.IsInRole("Admin") | User.IsInRole("Manager"))
{ 
        @Html.ActionLink("Add New Record", "ProductTypeIndex", "ProductType")
} 

But if there are many roles to check then this @if() gets long. How to avoid this? Do i need custom helpers for this(if so how can i approach it)? Help appreciated..

like image 561
Isuru Avatar asked Sep 03 '15 07:09

Isuru


People also ask

How does user IsInRole work?

IsInRole first checks the IsRoleListCached property to determine whether a cached list of role names for the current user is available. If the IsRoleListCached property is true , the cached list is checked for the specified role. If the IsInRole method finds the specified role in the cached list, it returns true .


1 Answers

You could write your own extension method and use it in your code.

public static class PrincipalExtensions
{
    public static bool IsInAllRoles(this IPrincipal principal, params string[] roles)
    {
        return roles.All(r => principal.IsInRole(r));
    }

    public static bool IsInAnyRoles(this IPrincipal principal, params string[] roles)
    {
        return roles.Any(r => principal.IsInRole(r));
    }
}

Now simply you could call this extension method like this:

// user must be assign to all of the roles  
if(User.IsInAllRoles("Admin","Manager","YetOtherRole"))
{
    // do something
} 

// one of the roles sufficient
if(User.IsInAnyRoles("Admin","Manager","YetOtherRole"))
{
    // do something
} 

While you could use these extension methods in views as well but try to avoid writing your apps logic in views as much as possible since views not unit testable easily.

like image 131
Sam FarajpourGhamari Avatar answered Sep 20 '22 12:09

Sam FarajpourGhamari