A Filter Attribute that extends AuthorizeAttribute. It gets the roles for the user in the database and compares with the roles assigned to each controller or method.
public class UserRoleAuthorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
//Data Repository. Getting data from database
var repository = new LoginRoleRepository();
//GetCharacterSeparator is an Extension method of String class
//It seperates the comma separated roles.
//The data comes from the controller
var roles = Roles.GetCharacterSeparator(',', true);
if (httpContext.User.Identity.IsAuthenticated)
{
//Here I check if the user is in the role, you can have your own logic. The data is gotten from DB.
var userRoles =
repository.All().Where(obj => obj.Login.Username == httpContext.User.Identity.Name).Single().Roles;
foreach (var role in roles)
if (userRoles.Any(obj => obj.Name == role))
return true;
}
return false;
}
}
Then you just define the attribute for each method or controller as bellow.
//Both Doctors and Receptionist have access to Patient controller.
[UserRoleAuthorize(Roles="Doctors, Receptionist")]
public class PatientController : Controller
{
//Both Doctors and Receptionist have access to Schedule an appointment for patients.
public ActionResult Schedule()
{
return View();
}
//Only Doctors have access to Treat patients.
[UserRoleAuthorize(Roles="Doctors")]
public ActionResult TreatPatient()
{
return View();
}
}
You need to add extra information as:
//Here seperate the roles as Doctor:ReadWrite, Receptionist:Read
//If you see Doctor:ReadWrite means the doctor has Read and Write and so on.
//This code is in AuthorizeCore
var roles = Roles.GetCharacterSeparator(',', true);
//And Add the bellow to the controllers and methods.
[UserRoleAuthorize(Roles="Doctors:Write, Employees:Read")]