What's the best way to change a Role?

in my API a user can be either a User or an Admin and I’m having some troubles editing a role of a user.

if I do:

var userAuth = _userAuthRepository.GetByPredicate(x => x.Company == companyId && x.Email == uc.User.Email).First();
var oldRoles = userAuth.Roles.ToList();
var newRole = new List<string> { request.Role.Value.ToString() };

_myAuthRepository.UnAssignRoles(userAuth, oldRoles); // remove all
_myAuthRepository.AssignRoles(userAuth, newRole);    // add

I get a new duplicate user in UserAuth table :open_mouth:

if I go full NHibernate:

var allRoles = _rolesRepository.GetByPredicate(x => x.UserAuthId == userAuth.Id).ToList();
if (allRoles.Any())
    // delete all
    foreach (var role in allRoles) _rolesRepository.Delete(role);

// add new
_rolesRepository.SaveOrUpdate(new UserAuthRole() { 
                               UserAuthId = userAuth.Id, 
                               Role = request.Role.Value.ToString() });

I get an exception No persister for: ServiceStack.Auth.UserAuthRole

what am I doing wrong?

What _userAuthRepository are you using?

_userAuthRepository is a custom AuthRepository based on this source.

but UnAssignRoles get’s from ServiceStack.Auth.UserAuthRepositoryExtensions not from the repository…

Hi Bruno, this is the implementation of the AssignRoles/UnAssingRoles.

Basically since your custom NHibernateUserAuthRepository doesn’t implement IManageRoles interface all it’s doing is mutating the userAuth.Roles and userAuth.Permissions Collections and calling:

_userAuthRepository.SaveUserAuth(userAuth);

The duplicate userAuth issue must be somewhere in the SaveUserAuth() implementation.

Hi @mythz, I’ve implemented IManageRoles and all worked as intended, exactly what I was missing!

Once again, thank you so much!