I'm working with an MVC application and Windows Authentication. I've already implemented a custom role provider which will return an array of roles that it is now pulling from my database.
Custom Role Provider (plain)
public class CustomRoleProvider : RoleProvider
{
...other methods removed...
//Custom Override
public override string[] GetRolesForUser(string username)
{
//Get custom roles from username
using (MyDBEntities db = new MyDBEntities ())
{
var roles = (from p in db.MyProcedure(username)
select p.UserRole).ToArray();
if (roles != null)
{
return roles;
}
else
{
return new string[] { };
}
}
}
}
What I would like to do next is some cleanup on the username that is being returned. Right now I'm doing this within the GetRolesForUser method. The first thing I do is strip off the "company//" from the domain, then I remove a certain prefix that is used, then I run the username through a testing procedure we have, which will return an impersonated username if the application is being tested.
Don't worry about the specifics of all of that. All I'd like to do is to move that cleanup code to a custom membership provider in the GetUser
method and return the username like I want it. How can I implement that?
Custom Role Provider (with extra code)
public class CustomRoleProvider : RoleProvider
{
...other methods removed...
//Custom Override
public override string[] GetRolesForUser(string username)
{
//Strip off the domain and lower text
username = username.ToString().ToLower().Split('\\')[1];
//remove company prefix
if (username.Contains("somePrefix-"))
{
username = username.Substring(username.IndexOf("somePrefix-") + 11);
}
//Return impersonated username if being tested
MyRepository myRepository = new MyRepository();
username = myRepository.GetUserName(username);
//I want to move out all of that code from above
//Get custom roles from username
using (MyDBEntities db = new MyDBEntities ())
{
var roles = (from p in db.MyProcedure(username)
select p.UserRole).ToArray();
if (roles != null)
{
return roles;
}
else
{
return new string[] { };
}
}
}
}
Custom Membership Provider
I'd like to move that cleanup code here, so after login, the username is returned how I want it.
public class CustomMembershipProvider : MembershipProvider
{
...other methods removed...
public override MembershipUser GetUser(string username, bool userIsOnline)
{
//I'd like to move my custom code here
//Strip off the domain and lower text
username = username.ToString().ToLower().Split('\\')[1];
//remove company prefix
if (username.Contains("somePrefix-"))
{
username = username.Substring(username.IndexOf("somePrefix-") + 11);
}
//Return impersonated username if being tested
MyRepository myRepository = new MyRepository();
username = myRepository.GetUserName(username);
//So now that's I've formatted the username as I want it,
//how can I return that as part of the MembershipUser return type?
}