SaaS CMS has officially launched! Learn more now.

How to get a list of users in v12 and update them?

Vote:
 

I'm looking to grab the entire list of users who are not administrators and deactivate them.

I've found a way to do it, but it's not elegant and feels very hacky.  I'm writing it as a Scheduled Job:

public override string Execute()
    {
      try
      {
          Task<string> resultThingTask = (Task<string>)Task.Run(DisableNonAdminUsers);
          resultThingTask.Wait();
          var result = resultThingTask.Result;

          return "job completed successfully.  See the EPi log for details.";
      }
      catch (Exception ex)
      {
        return $"job failed: {ex.Message}";
      }
    }   


private async Task<string> DisableNonAdminUsers()
    {
      var users = await AsyncEnumerable.ToListAsync<IUIUser>((IAsyncEnumerable<IUIUser>)AsyncEnumerable.OrderBy<IUIUser, string>(_userProvider.GetAllUsersAsync(0, 1000), (Func<IUIUser, string>)(u => u.Username)), new CancellationToken());
      foreach (var u in users)
      {
        var roles = _roleProvider.GetRolesForUserAsync(u.Username);
        if (!await roles.ContainsAsync(Roles.Administrators))
        {
          // Disable the user account
          u.IsApproved = false;
          await _userProvider.UpdateUserAsync(u);
        }
      }

      return "";
    }

The only function I could find to grab all users was the GetAllUsersAsync... which is async and needed wrapping in order to use it from my non-async function.

Does anyone have a better way to do this?

Cheers,

Lance

#307754
Aug 31, 2023 16:14
Vote:
 

Writing this without any morning coffee - assuming you are using aspnet identity, you can use UserManager.Users to get all users. then for each user, use user.IsInRole to check if they are administrator

if you have many users, performance should be a consideration

#307809
Sep 01, 2023 5:50
* You are NOT allowed to include any hyperlinks in the post because your account hasn't associated to your company. User profile should be updated.