Hide different actions for different user profiles

5

I am in a project where I have 3 different levels of profiles: Administrator , Teacher and Coordinator . I already have the login module, registers and such.

What happens is that I wanted for each profile type to appear only what is allowed, hiding the parts of the system that it can not access according to its hierarchy.

Is this direct in the view ? If so, how do you do it?

    
asked by anonymous 25.05.2014 / 03:15

2 answers

1

Another possible situation would be, to have the different profiles, create partials corresponding to each user profile that exists in the system. That is, if you have 3 different profiles, separate the system into areas and decorate the actions with the possible permissions, according to your system and then each profile only accesses your area. In short, create an action that returns a specific partial for that type of profile. This solves the whole problem with permissions, as each profile can only access what is allowed, which is not, does not access!
To create these permissions you can use as a base this link as the basis for doing this operation, that is, another question of mine.

I hope I have helped!

    
15.06.2014 / 02:33
6

Considering that your project uses at least Membership or ASP.NET Identity , note the following attribute on top of each View:

[Authorize(Roles = "Administrador, Professor, Coordenador")]
public ActionResult MinhaAction() { ... }

To authorize some users in Role , use the following command in some part of your code:

Roles.AddUserToRole("LoginDoUsuario", "Administrador");

To check your code if the user belongs to some Role , use:

if (User.IsInRole("Administrador")) { ... }

To remove the user from a Role , use:

Roles.RemoveUserFromRole("LoginDoUsuario", "Administrador");

For Views, the principle is the same:

@if (User.IsInRole("Administrador")) { ... }

To check the Roles of the current user:

@Roles.GetRolesForUser()

Or from a specific user:

@Roles.GetRolesForUser("LoginDoUsuario")

Incidentally, you can use the attribute without specifying Role only to check if the user is logged in:

[Authorize]
public ActionResult MinhaAction() { ... }

If no authentication scheme is specified, your application will use SimpleMembership if it is MVC4 or ASP.NET Identity with Basic Authentication if it is MVC5.

As stated, you can customize the authentication scheme by reimplementing some classes. In any case, this part would already serve another question.

    
25.05.2014 / 03:25