Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CustomAuthRepository
public class CustomAuthRepository : OrmLiteAuthRepository<AspNetUser, UserAuthDetails>
{
public CustomAuthRepository(IDbConnectionFactory dbFactory, string namedConnnection = null) : base(dbFactory, namedConnnection)
{
}
public override void AssignRoles(string userAuthId, ICollection<string> roles = null, ICollection<string> permissions = null)
{
var userAuth = GetUserAuth(userAuthId) as User;
if (userAuth == null)
return;
Exec(db =>
{
if (!roles.IsEmpty())
{
var dbRoles = db.LoadSelect<AspNetUserRole>(x => x.UserId == userAuth.Id);
var roleSet = EnumerableExtensions.ToHashSet(dbRoles.Select(x => x.Role.Name));
foreach (var role in roles)
{
var dbRole = db.Select<AspNetRole>(x => x.Name == role).FirstOrDefault();
if (!roleSet.Contains(role) && dbRole != null)
{
db.Insert(new AspNetUserRole()
{
UserId = userAuth.Id,
RoleId = dbRole.Id
});
}
}
}
if (!permissions.IsEmpty())
{
//Delegate to ServiceStacks default permission store
base.AssignRoles(userAuthId, null, permissions);
}
});
}
public override ICollection<string> GetRoles(string userAuthId)
{
if (GetUserAuth(userAuthId) is User userAuth)
{
return Exec(db =>
{
var roles = db.LoadSelect<AspNetUserRole>(x => x.UserId == userAuth.Id)
.Select(x => x.Role.Name);
return roles.ToList();
});
}
return new List<string>();
}
public override bool HasRole(string userAuthId, string role)
{
if (GetUserAuth(userAuthId) is User userAuth)
{
return Exec(db =>
{
var roles = db.LoadSelect<AspNetUserRole>(x => x.UserId == userAuth.Id)
.Select(x => x.Role.Name);
return roles.Contains(role);
});
}
return false;
}
//I modified this method and it is untested, but you get the point
public override void UnAssignRoles(string userAuthId, ICollection<string> roles = null, ICollection<string> permissions = null)
{
if (GetUserAuth(userAuthId) is User authUser)
{
Exec(db =>
{
if (!roles.IsEmpty())
{
var dbRoles = db.LoadSelect<AspNetRole>(x => roles.Contains(x.Name)).Select(x => x.Id);
db.Delete<AspNetUserRole>(x => x.UserId == authUser.Id && dbRoles.Contains(x.RoleId));
}
//Delegate to ServiceStacks Permission store
base.UnAssignRoles(userAuthId, null, permissions);
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.