WorkspaceService.cs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Security.Principal;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using BO.AppServer.Business.Exceptions;
  8. using BO.AppServer.Business.Mapper;
  9. using BO.AppServer.Business.Services.Base;
  10. using BO.AppServer.Data.Entity;
  11. using BO.AppServer.Data.Repository;
  12. using BO.AppServer.Metadata.Configuration;
  13. using BO.AppServer.Metadata.Dto;
  14. using BO.AppServer.Metadata.Enums;
  15. using Microsoft.AspNetCore.Identity;
  16. using Microsoft.Extensions.Logging;
  17. using Microsoft.Extensions.Options;
  18. using Quadarax.Foundation.Core.Data;
  19. using Quadarax.Foundation.Core.Data.Interface;
  20. using Quadarax.Foundation.Core.Data.Interface.Entity.Dto;
  21. using Quadarax.Foundation.Core.Exceptions;
  22. namespace BO.AppServer.Business.Services
  23. {
  24. public class WorkspaceService: UserContextService
  25. {
  26. #region *** Private fields ***
  27. private readonly WorkspaceRepo _repoWorkspace;
  28. private readonly BillingPlanRepo _repoBillingPlan;
  29. private readonly WorkspaceBillingRepo _repoWorkspaceBilling;
  30. #endregion
  31. #region *** Constructor ***
  32. public WorkspaceService(WorkspaceRepo repoWorkspace,
  33. BillingPlanRepo repoBillingPlan,
  34. WorkspaceBillingRepo repoWorkspaceBilling,
  35. IOptions<Configuration> config,
  36. UserRepo repoUser,
  37. UserManager<IdentityUser> userManager,
  38. IPrincipal currentPrincipal,
  39. ILoggerFactory logger) : base(config, repoUser, userManager, currentPrincipal, logger)
  40. {
  41. _repoWorkspace = repoWorkspace ?? throw new ArgumentNullException(nameof(repoWorkspace));
  42. _repoBillingPlan = repoBillingPlan ?? throw new ArgumentNullException(nameof(repoBillingPlan));
  43. _repoWorkspaceBilling = repoWorkspaceBilling ?? throw new ArgumentNullException(nameof(repoWorkspaceBilling));
  44. }
  45. #endregion
  46. #region *** Public Operations ***
  47. public async Task<ResultValueDto<WorkspaceRDto>> CreateWorkspaceAsync(WorkspaceCDto workspace)
  48. {
  49. var billingPlan = _repoBillingPlan.GetByCode(workspace.BillingPlanCode);
  50. if (billingPlan == null)
  51. {
  52. var exc = new EntityNotExistsException(typeof(BillingPlan), workspace.BillingPlanCode, 0);
  53. Log.LogWarning(exc.Message);
  54. throw exc;
  55. }
  56. var owner = _repoUser.GetByName(workspace.AssignedUserName);
  57. if (owner == null)
  58. {
  59. var exc = new EntityNotExistsException(typeof(User), workspace.AssignedUserName, 0);
  60. Log.LogWarning(exc.Message);
  61. throw exc;
  62. }
  63. var current = GetCurrentUser();
  64. var newWorkspace = _repoWorkspace.CreateWorkspace(workspace.Name, billingPlan, workspace.Apipassword, true, owner,current);
  65. _repoWorkspace.Commit();
  66. Log.LogInformation($"Workspace '{newWorkspace.Name}' [API-KEY:{newWorkspace.Apikey}] created and appends to users: {string.Join(",", newWorkspace.UserWorkspaces.Select(x=>x.User.Name))}");
  67. return new ResultValueDto<WorkspaceRDto>(newWorkspace.Map<Workspace, WorkspaceRDto>());
  68. }
  69. public async Task<ResultsValueDto<WorkspaceRDto>> GetWorkspacesAsync(WorkspaceScopeEnums scope, PagingDto paging,string ownerUserName)
  70. {
  71. List<Workspace> workspaces = null;
  72. switch (scope)
  73. {
  74. case WorkspaceScopeEnums.All:
  75. workspaces = _repoWorkspace.Query(paging).ToList();
  76. break;
  77. case WorkspaceScopeEnums.Empty:
  78. workspaces = _repoWorkspace.GetAllEmpty(paging).ToList();
  79. break;
  80. case WorkspaceScopeEnums.NotEmpty:
  81. workspaces = _repoWorkspace.GetAllNonEmpty(paging).ToList();
  82. break;
  83. case WorkspaceScopeEnums.My:
  84. var owner = _repoUser.GetByName(ownerUserName);
  85. if (owner == null)
  86. {
  87. var exc = new EntityNotExistsException(typeof(User), ownerUserName, 0);
  88. Log.LogWarning(exc.Message);
  89. throw exc;
  90. }
  91. workspaces = _repoWorkspace.GetAllByOwner(owner, paging).ToList();
  92. break;
  93. }
  94. return new ResultsValueDto<WorkspaceRDto>(workspaces.MapList<Workspace, WorkspaceRDto>());
  95. }
  96. public async Task<long> GetWorkspaceIdByAPIAccess(string apiKey, string apiPassword, string currentUserName)
  97. {
  98. var owner = string.IsNullOrEmpty(currentUserName) ? GetCurrentUser() : _repoUser.GetByName(currentUserName);
  99. if (owner == null)
  100. {
  101. var exc = new EntityNotExistsException(typeof(User), currentUserName, 0);
  102. Log.LogWarning(exc.Message);
  103. throw exc;
  104. }
  105. if (!Guid.TryParse(apiKey, out var apiKeyGuid))
  106. apiKeyGuid = Guid.Empty;
  107. Workspace workspace = null;
  108. if (await HasUserElevation(currentUserName))
  109. {
  110. // if elevated user and system user
  111. workspace = _repoWorkspace.GetByApiKey(apiKey);
  112. if (workspace.Apipassword != apiPassword)
  113. workspace = null;
  114. }
  115. else
  116. {
  117. // for rest
  118. workspace = _repoWorkspace.GetAllByOwner(owner, new Paging())
  119. .FirstOrDefault(x => x.Apikey == apiKeyGuid && x.Apipassword == apiPassword);
  120. }
  121. if (workspace == null)
  122. {
  123. var exc = new CodeException(1400, $"Workspace with APIKey '{apiKey}' not exists or API password is not valid!");
  124. Log.LogWarning(exc.Message + $"\nUser Context:'{owner.Name}' [{owner.Id}]");
  125. throw exc;
  126. }
  127. return workspace.Id;
  128. }
  129. public async Task<ResultValueDto<WorkspaceRDto>> GetWorkspace(WorkspaceIdentificationTypeEnum identificationType, string identificationValue)
  130. {
  131. var workspace = identificationType == WorkspaceIdentificationTypeEnum.Id ?
  132. _repoWorkspace.Get(ArgumentAsLong(nameof(identificationValue), identificationValue))
  133. : identificationType == WorkspaceIdentificationTypeEnum.ApiKey ? _repoWorkspace.GetByApiKey(identificationValue)
  134. : _repoWorkspace.GetByName(identificationValue);
  135. if (workspace == null)
  136. throw new NoDataException();
  137. var currentBillingPlan = GetCurrentWorkspaceBillingOrCreate(workspace.Id);
  138. // gather rest of data
  139. var result = new ResultValueDto<WorkspaceRDto>(workspace.Map<Workspace, WorkspaceRDto>());
  140. result.Value.CreditAmount = currentBillingPlan.ValueNumber;
  141. result.Value.BillingPlanCode = currentBillingPlan.BillingPlan.Code;
  142. return result;
  143. }
  144. public async Task<bool> ExistsWorkspace(WorkspaceIdentificationTypeEnum identificationType, string identificationValue)
  145. {
  146. var workspace = identificationType == WorkspaceIdentificationTypeEnum.Id ?
  147. _repoWorkspace.Get(ArgumentAsLong(nameof(identificationValue), identificationValue))
  148. : identificationType == WorkspaceIdentificationTypeEnum.ApiKey ? _repoWorkspace.GetByApiKey(identificationValue)
  149. : _repoWorkspace.GetByName(identificationValue);
  150. return workspace != null;
  151. }
  152. #endregion
  153. #region *** Private Operations ***
  154. private WorkspaceBilling GetCurrentWorkspaceBillingOrCreate(long workspaceId)
  155. {
  156. var currentBillingPlan = _repoWorkspaceBilling.GetByCurrentForWorkspace(workspaceId);
  157. if (currentBillingPlan == null)
  158. {
  159. currentBillingPlan = _repoWorkspaceBilling.CreateForWorkspace(workspaceId,
  160. _repoBillingPlan.GetByCode(_configuration.Business.DefaultBillingPlanCode));
  161. _repoWorkspaceBilling.Commit();
  162. Log.LogWarning($"Default billing plan was not set for workspace [{workspaceId}]. Set default billing plan '{currentBillingPlan.BillingPlan.Code}'.");
  163. }
  164. return currentBillingPlan;
  165. }
  166. #endregion
  167. }
  168. }