Filtering Users By TenantId

We first need to load and cache user tenant information in UserDefinition.

Open UserDefinition.cs under Multitenancy.Web/ Modules/ Administration/ User/ Authentication and add a TenantId property.

  1. namespace MultiTenancy.Administration
  2. {
  3. using Serenity;
  4. using System;
  5. [Serializable]
  6. public class UserDefinition : IUserDefinition
  7. {
  8. public string Id { get { return UserId.ToInvariant(); } }
  9. public string DisplayName { get; set; }
  10. public string Email { get; set; }
  11. public short IsActive { get; set; }
  12. public int UserId { get; set; }
  13. public string Username { get; set; }
  14. public string PasswordHash { get; set; }
  15. public string PasswordSalt { get; set; }
  16. public string Source { get; set; }
  17. public DateTime? UpdateDate { get; set; }
  18. public DateTime? LastDirectoryUpdate { get; set; }
  19. public int TenantId { get; set; }
  20. }
  21. }

This is the class that is returned when you ask for current user through Authorization.UserDefinition.

We also need to modify the code where this class is loaded. In the same folder, edit UserRetrieveService.cs and change GetFirst method like below:

  1. private UserDefinition GetFirst(IDbConnection connection, BaseCriteria criteria)
  2. {
  3. var user = connection.TrySingle<Entities.UserRow>(criteria);
  4. if (user != null)
  5. return new UserDefinition
  6. {
  7. UserId = user.UserId.Value,
  8. Username = user.Username,
  9. Email = user.Email,
  10. DisplayName = user.DisplayName,
  11. IsActive = user.IsActive.Value,
  12. Source = user.Source,
  13. PasswordHash = user.PasswordHash,
  14. PasswordSalt = user.PasswordSalt,
  15. UpdateDate = user.UpdateDate,
  16. LastDirectoryUpdate = user.LastDirectoryUpdate,
  17. TenantId = user.TenantId.Value
  18. };
  19. return null;
  20. }

Now, it’s time to filter listed users by TenantId. Open UserRepository.cs, locate MyListHandler class and modify it like this:

  1. private class MyListHandler : ListRequestHandler<MyRow>
  2. {
  3. protected override void ApplyFilters(SqlQuery query)
  4. {
  5. base.ApplyFilters(query);
  6. var user = (UserDefinition)Authorization.UserDefinition;
  7. if (!Authorization.HasPermission(PermissionKeys.Tenants))
  8. query.Where(fld.TenantId == user.TenantId);
  9. }
  10. }

Here, we first get a reference to cached user definition of currently logged user.

We check if he has tenant administration permission, which only admin will have in the end. If not, we filter listed records by TenantId.