Making Roles Multi-Tenant

So far, we have made users page work in multi-tenant style. Seems like we did too many changes to make it work. But remember that we are trying to turn a system that is not designed to be multi-tenant into such one.

Let’s apply similar principles to the Roles table.

Again, a user in one tenant shouldn’t see or modify roles in other tenants and work in isolation.

We start by adding TenantId property to RoleRow.cs:

  1. namespace MultiTenancy.Administration.Entities
  2. {
  3. //...
  4. public sealed class RoleRow : Row, IIdRow, INameRow
  5. {
  6. [Insertable(false), Updatable(false)]
  7. public Int32? TenantId
  8. {
  9. get { return Fields.TenantId[this]; }
  10. set { Fields.TenantId[this] = value; }
  11. }
  12. //...
  13. public class RowFields : RowFieldsBase
  14. {
  15. //...
  16. public Int32Field TenantId;
  17. //...
  18. }
  19. }
  20. }

Then we’ll do several changes in RoleRepository.cs:

  1. private class MySaveHandler : SaveRequestHandler<MyRow>
  2. {
  3. protected override void SetInternalFields()
  4. {
  5. base.SetInternalFields();
  6. if (IsCreate)
  7. Row.TenantId = ((UserDefinition)Authorization.UserDefinition).TenantId;
  8. }
  9. protected override void ValidateRequest()
  10. {
  11. base.ValidateRequest();
  12. if (IsUpdate)
  13. {
  14. var user = (UserDefinition)Authorization.UserDefinition;
  15. if (Old.TenantId != user.TenantId)
  16. Authorization.ValidatePermission(PermissionKeys.Tenants);
  17. }
  18. }
  19. }
  20. private class MyDeleteHandler : DeleteRequestHandler<MyRow>
  21. {
  22. protected override void ValidateRequest()
  23. {
  24. base.ValidateRequest();
  25. var user = (UserDefinition)Authorization.UserDefinition;
  26. if (Row.TenantId != user.TenantId)
  27. Authorization.ValidatePermission(PermissionKeys.Tenants);
  28. }
  29. }
  30. private class MyRetrieveHandler : RetrieveRequestHandler<MyRow>
  31. {
  32. protected override void PrepareQuery(SqlQuery query)
  33. {
  34. base.PrepareQuery(query);
  35. var user = (UserDefinition)Authorization.UserDefinition;
  36. if (!Authorization.HasPermission(PermissionKeys.Tenants))
  37. query.Where(fld.TenantId == user.TenantId);
  38. }
  39. }
  40. private class MyListHandler : ListRequestHandler<MyRow>
  41. {
  42. protected override void ApplyFilters(SqlQuery query)
  43. {
  44. base.ApplyFilters(query);
  45. var user = (UserDefinition)Authorization.UserDefinition;
  46. if (!Authorization.HasPermission(PermissionKeys.Tenants))
  47. query.Where(fld.TenantId == user.TenantId);
  48. }
  49. }