Stian
Stian

Reputation: 1602

How should I check the user's roles in a view?

I'm doing a check on the logged in user's roles in _LoginPartial.cshtml, to change a design element based on the role.

Is this a good way of doing it, or is there a better way?

int ix = User.IsInRole("SiteAdmin")
    ? 0
    : User.IsInRole("SysOp")
        ? 1
        : User.IsInRole("SupportAgent")
            ? 2
            : User.IsInRole("GroupAdmin")
                ? 3
                : User.IsInRole("GroupUser")
                    ? 4
                    : 5;

Then I use ix as an indexer in the string[] btnDesign[]:

class="btn @(btnDesign[ix])"

I'm aware that my check potentially causes five separate trips to the database, and that is why I'm asking this question.

Update I have "optimized" it slightly. Seeing as there are more "GroupUser"s than "SiteAdmin"s, I turned the check on it's head (and removed one role, SupportAgent):

int ix = User.IsInRole("GroupUser")
    ? 0
    : User.IsInRole("GroupAdmin")
        ? 1
        : User.IsInRole("SysOp")
            ? 2
            : User.IsInRole("SiteAdmin")
                ? 3
                : 4;

Now the check will presumably be as fast as possible for the majority of the logged in users, which are "GroupUser"s.

Still, I would like to know if it is possible to improve it further.

Upvotes: 0

Views: 384

Answers (1)

lzydrmr
lzydrmr

Reputation: 909

You could define a mapping of roles to indices in a dictionary at some convenient place:

var roleMapping = new Dictionary<string,int>();
roleMapping.Add("SiteAdmin", 0);
...

In your code, you could retrieve all the roles of the user in one call:

var idUser = UserManager.GetUserAsync(User).Result;
var roles = UserManager.GetRolesAsync(idUser).Result;

Now, determine the "most significant" index considering the roles that the user has through

int significantIndex = roleMapping
                         .Where(kv => roles.Contains(kv.Key))
                         .Select(kv => kv.Value)
                         .Min();

Here it is assumed that the index with the lowest value is the best match for the current user.

Upvotes: 1

Related Questions