I have the class below to manage my specific implementation of a membership system using entity framework 6.1
Is the use of static access correct in this case? as far as I understood that EF context is not thread-safe so I'm instantiating one with every call through the using
statement. My second question, is the use of Boolean variable okay to signal failure in db transactions? an important point about this class is that it's going to be used quite frequently as the authentication wont rely on any session established with the user, it's also important to note that the users of this system will be quite limited.
Edit: I'm aware I can use the new identity system or any of the membership providers offered by ASP.NET but this custom provider is quite specific to a Windows authentication system and the use of any cookie-based system is not possible.
public static class AccountManager
{
private enum Role { User, Comment, CommentControl, Sysadmin }
public static bool IsUserInRole(string username, string role)
{
using (var ctx = new AccountsDbCtx())
{
var status = false;
var foundAcc = ctx.Accounts.Where(x => x.Username == username);
if (foundAcc.Any())
{
var s = foundAcc.SingleOrDefault();
if (s != null)
{
var exitingRole = s.Roles.Where(x => x.Name.Equals(role, StringComparison.InvariantCultureIgnoreCase));
if (exitingRole.Any())
{
status = true;
}
}
}
return status;
}
}
public static bool IsUserCached(string username)
{
using (var ctx = new AccountsDbCtx())
{
var result = true;
var foundAcc = ctx.Accounts.Where(x => x.Username == username);
if (!foundAcc.Any())
{
result = false;
}
return result;
}
}
public static bool CacheUser(string username)
{
using (var ctx = new AccountsDbCtx())
{
var status = false;
try
{
var newAcc = new Account
{
Active = true,
Username = username,
};
ctx.Accounts.Add(newAcc);
ctx.SaveChanges();
AssignRole(newAcc.Username, Role.User);
status = true;
}
catch
{ }
return status;
}
}
public static bool AssignRoleComment(string username)
{
return AssignRole(username, Role.Comment);
}
public static bool AssignRoleCommentControl(string username)
{
return AssignRole(username, Role.CommentControl);
}
public static bool AssignRoleSysAdmin(string username)
{
return AssignRole(username, Role.Sysadmin);
}
private static bool AssignRole(string accountName, Role role)
{
using (var ctx = new AccountsDbCtx())
{
var completed = false;
var roleToAssign = ctx.Roles.SingleOrDefault(x => x.Role1 == (int)role);
try
{
var currentAccount = ctx.Accounts.SingleOrDefault(x => x.Username.Contains(accountName));
if (currentAccount != null && roleToAssign != null) currentAccount.Roles.Add(roleToAssign);
ctx.SaveChanges();
completed = true;
}
catch
{}
return completed;
}
}
}