Skip to content

Instantly share code, notes, and snippets.

@jjwilliams42
Last active October 9, 2019 11:22
Show Gist options
  • Save jjwilliams42/3a4177fa23bea8e810380b0b607e2784 to your computer and use it in GitHub Desktop.
Save jjwilliams42/3a4177fa23bea8e810380b0b607e2784 to your computer and use it in GitHub Desktop.
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