I have a web system that provides access to 3 types of user (Student, Teacher and Admin) in which I want to restrict the access of certain users to an ActionResult of the controllers.
I have a web system that provides access to 3 types of user (Student, Teacher and Admin) in which I want to restrict the access of certain users to an ActionResult of the controllers.
You can do it with a ActionFilterAttribute
overwriting the OnActionExecuting
method that is executed before the Action method.
For example, your class Usuario
(or whatever you call it) adds a property Nivel
that will have the value of a enum
called Nivel
:
public class Usuario
{
public string Nombre { get; set;}
public int Id { get; set; }
public Nivel Nivel { get; set; }
}
public enum Nivel{
Estudiante,
Docente,
Administrador
}
When the user starts session, save the user information in the Session object. You have to make sure to assign the property Nivel
since it will be the important one in this case:
[HttpPost]
public ActionResult Login(string usuario, string contrasena)
{
Usuario usuario = ValidarUsuario(usuario, contrasena);
if(usuario == null)
{
ViewBag.Error = "Usuario o contraseña invalido";
return View();
}
else{
Session["usuario"] = usuario; // guardamos la informacion del usuario
return View("Index", "Home");
}
}
Now you create a class that you will inherit from ActionFilterAttribute
:
public class RequiereNivelAttribute : System.Web.Mvc.ActionFilterAttribute
{
public RequiereNivelAttribute(Nivel nivel)
{
this.nive = nivel;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
// validamos si la sesion ha sido asignada
if(context.HttpContext.Session["usuario"] != null)
{
Usuario = context.HttpContext.Session["usuario"] as Usuario;
if(usuario.Nivel != this.nivel)
{
// como no es del mismo nivel especificado, lo redireccionamos al index de la app
context.Result = new RedirectResult("~/Home/Index");
}
}
}
}
Now you only have to specify in the Action, the level that the user requires to access, otherwise it will be redirected to the / Home / Index:
public class ConfigController : Controller
{
[RequiereNivel(Nivel.Administrador)]
public ActionResult InfoMaestros()
{
return View();
}
[RequiereNivel(Nivel.Docente)]
public ActionResult InfoPerfil()
{
return View();
}
}
If the user does not have the specified level, then he will not be able to access the action.
Remember that it's just an example. You will adapt it to your needs and the way you want to do it.