In my article
Drag And Drop Role Management with Asp.Net, MVC & jQuery[
^] you can see how I check the role the current user has to see if they have the authority to run the action.
During the initialisation of the system you can add the roles into the database by calling a method in the global.asax Application_Start;
Obviously you would do this on the first run just to set things up. Later on you can either comment this out or do some logic checking to see if the roles or user accounts already exist.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
InitialiseRoles(false);
InitialiseDefaultUsers();
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<TM470Project.DBContexts.CombinedDBContext>());
}
then the two methods are
private void InitialiseRoles(Boolean DeleteExistingRoles)
{
if (DeleteExistingRoles)
{
String[] oldRoles = Roles.GetAllRoles();
foreach (String role in oldRoles)
{
String[] users = Roles.GetUsersInRole(role);
foreach (String user in users)
{
Roles.RemoveUserFromRole(user, role);
}
Roles.DeleteRole(role);
}
}
String[] NewRoles = new String[] {"KPI-Daily-View","KPI-Daily-Create", "KPI-Daily-Edit", "KPI-Daily-Delete", "KPI-Losses-View","KPI-Losses-Create","KPI-Losses-Edit","KPI-Losses-Delete", "Drilling-Report-View","Drilling-Report-Create","Drilling-Report-Edit","Drilling-Report-Delete", "Admin-User-View","Admin-User-Add","Admin-User-Edit","Admin-User-Delete","Admin-User-ChangePassword", "Admin-Assets-View","Admin-Assets-Create","Admin-Assets-Edit","Admin-Assets-Delete"};
foreach (String role in NewRoles)
{
if (!Roles.RoleExists(role))
{
Roles.CreateRole(role);
}
}
}
You can then add the default users onto the system by doing;
private void InitialiseDefaultUsers()
{
MembershipUser user = null;
user = Membership.GetUser("SuperUser");
if (user == null)
{
Membership.CreateUser("SuperUser", "ThePassword","SuperUser@the-email.net");
}
String[] roles = Roles.GetAllRoles();
foreach (String role in roles)
{
if (!(Roles.IsUserInRole("SuperUser", role)))
{
Roles.AddUserToRole("SuperUser", role);
}
}
user = Membership.GetUser("Guest");
if (user==null)
{
Membership.CreateUser("Guest", "guest-password", "guest@the-email.net");
}
String[] guestRoles = new String[] {"KPI-Daily-View","KPI-Losses-View","Drilling-Report-View"};
foreach (String role in guestRoles)
{
if (!(Roles.IsUserInRole("Guest", role)))
{
Roles.AddUserToRole("Guest", role);
}
}
}
Note: the code above is from my OU project that the drag and drop article was also based on, hence all those different roles for the different things the application was doing.