0

Im trying to hide some admin specific buttons on my masterpage from users with no adminrights.

my code looks like this so far:

<% if (Request.IsAuthenticated)
    {%>
        <%: Html.ActionLink("Administrer", "Index", "User", new { Area = "Users" }, new { @class = "menubutton", @id = "settingsbutton" })%>
      <%} else { }%>

now i want to do a check in the IF() statement if the current user is an administrator. im using the ASP.NET membership system and have a speciel class attached to each user with some exstra information including information about if he is an admin or not (bool).

my question is how do i go about calling a method that checks this or something similar?

AronChan
  • 245
  • 3
  • 19
  • I was thinking it would be something like if (Request.IsAuthenticated && "Method that checks for adminrights") – AronChan Apr 11 '12 at 18:36
  • i just dont know how to call such a method from the masterpage to a controller – AronChan Apr 11 '12 at 18:37
  • 1
    See http://stackoverflow.com/questions/409213/how-can-i-create-a-view-that-has-different-displays-according-to-the-role-the-us or http://stackoverflow.com/questions/4610749/asp-net-mvc-check-role-inside-view – Luke Hutton Apr 11 '12 at 18:48
  • Not exactly the solution i was looking for but it definately has some advantages to it. thank you – AronChan Apr 11 '12 at 18:56
  • @AronChan What *are* you looking for? The `System.Security.Principal` (User) is available in the View. Is that the object you have attached extra info to? – Steve Mallory Apr 11 '12 at 19:03
  • I have an object attached to the ASP.NET user which is basicly a collection of items that is attached to that user. my first thought was to use it to determine if the user was admin or not. but i see now that it is much better to use the role system already in place :) – AronChan Apr 11 '12 at 19:18

1 Answers1

3
<% if (Request.IsAuthenticated && User.IsInRole("Administrator"))
    {%>
        <%: Html.ActionLink("Administrer", "Index", "User", new { Area = "Users" }, new { @class = "menubutton", @id = "settingsbutton" })%>
      <%} else { }%>

If you are using the ASP.NET Membership Provider and the ASP.NET Role Provider to link your users to their roles, you can just invoke the IsInRole(string) method on your view's IPrincipal User object.

danludwig
  • 46,965
  • 25
  • 159
  • 237
  • It seems that i dont have the IPrincipal User object. how exactly do i go about getting that? – AronChan Apr 11 '12 at 21:28
  • I managed to access my user by using: HttpContext.Current.User.IsInRole("administrator") Is this just as good as your example or is there a specific reason that you did it that way? – AronChan Apr 11 '12 at 22:20
  • `HttpContext.Current.User.IsInRole("administrator")` is fine. Maybe it's only MVC3 or the Razor view engine that provides @User by default in the view page. – danludwig Apr 11 '12 at 22:27