public async Task PointsEarned(Guid id, double points, MembershipPointsType type) { var entity = await GenericEntityFactory <Membership> .GetEntityAsync(_simpleEventStoreDbContext, id.ToString()); entity.PointsEarned(points, type); await _simpleEventStoreDbContext.SavePendingEventsAsync(entity.PendingEvents, 1, "Sample"); await _eventBusService.Publish(entity.PendingEvents); }
public async Task Handle(CustomerRegisteredEvent notification, CancellationToken cancellationToken) { var membership = new Membership(notification.Id); await _eventStoreDbContext.SavePendingEventsAsync(membership.PendingEvents, 1, "Sample"); await _eventBusService.Publish(membership.PendingEvents); }
public async Task Handle(MembershipPointsEarnedEvent notification, CancellationToken cancellationToken) { var membership = await _readModelDbContext.Memberships .Include(m => m.Points) .FirstOrDefaultAsync(m => m.Id == notification.Id); // this is require, as otherwise, the place where it save to the read mokdel will throw some exceptions _readModelDbContext.Entry(membership).State = EntityState.Detached; var newPoints = membership.TotalPoints; var newPointsPer100 = (int)(newPoints / 100); var previousPoints = membership.TotalPoints - notification.Amount; var previousPointsPer100 = (int)(previousPoints / 100); var rewardPointsEarned = newPointsPer100 - previousPointsPer100; if (rewardPointsEarned > 0) { var rewardType = (rewardPointsEarned == 1) ? RewardType.GiftVoucher : RewardType.FreeMeal; var entity = new Reward(membership.CustomerId, rewardType); await _simpleEventStoreDbContext.SavePendingEventsAsync(entity.PendingEvents, 1, "Sample"); await _eventBusService.Publish(entity.PendingEvents); } }
public async Task <IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { User user = await userManager.FindByEmailAsync(model.Email); if (user != null && user.PasswordHash != null) { ModelState.AddModelError(nameof(LoginViewModel.Email), $"The User with the email already exists"); return(View(model)); } else if (user == null) { user = new User { UserName = model.Name, Email = model.Email }; IdentityResult identityCreateResult = await userManager.CreateAsync(user, model.Password); if (!identityCreateResult.Succeeded) { return(ViewWithErrors(identityCreateResult, model)); } await userManager.AddToRoleAsync(user, "user"); eventBusService.Publish(new UserCreatedIntegrationEvent(user.Id)); } else { user.UserName = model.Name; foreach (IUserValidator <User> userValidator in userManager.UserValidators) { IdentityResult identityValidateResult = await userValidator.ValidateAsync(userManager, user); if (!identityValidateResult.Succeeded) { return(ViewWithErrors(identityValidateResult, model)); } } IdentityResult identityUpdateResult = await userManager.AddPasswordAsync(user, model.Password); if (!identityUpdateResult.Succeeded) { return(ViewWithErrors(identityUpdateResult, model)); } } await emailService.SendEmailAsync(user.Email !, "Confirm your email", await GenerateEmailConfirmationMessageAsync(user, model.ReturnUrl)); return(RedirectToAction(nameof(RegisterSuccess))); } return(View(model)); }
public async Task <bool> RegisterCustomerAsync(string username, string firstname, string lastname, string email) { // pretend to run some sort of validation here. // username must be unique. var isUsernameExists = _readModelDbContext.Customers.Any(c => c.Username == username); if (isUsernameExists) { return(false); } var customer = new Customer(Guid.NewGuid(), username, firstname, lastname, email); await _eventStoreDbContext.SavePendingEventsAsync(customer.PendingEvents, 1, "Sample"); await _eventBusService.Publish(customer.PendingEvents); return(true); }
public async Task <IActionResult> Callback() { string?externalId = User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value; string?externalLoginProvider = User.Identity?.AuthenticationType; string?userEmail = User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value; if (new[] { externalId, externalLoginProvider, userEmail }.Any(v => string.IsNullOrWhiteSpace(v))) { return(Redirect("/")); } User user = await userManager.FindByEmailAsync(userEmail); if (user == null) { user = new User { UserName = userEmail, Email = userEmail }; await userManager.CreateAsync(user); await userManager.AddToRoleAsync(user, "user"); await userManager.AddLoginAsync(user, new UserLoginInfo(externalLoginProvider, externalId, externalLoginProvider)); eventBusService.Publish(new UserCreatedIntegrationEvent(user.Id)); } else if (!dbContext.UserLogins.Any(ul => ul.LoginProvider == externalLoginProvider && ul.ProviderKey == externalId)) { await userManager.AddLoginAsync(user, new UserLoginInfo(externalLoginProvider, externalId, externalLoginProvider)); } await signInManager.SignInWithClaimsAsync(user, isPersistent : false, new Claim[] { new Claim("amr", "pwd") }); await HttpContext.SignOutAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme); string?returnUrl = (await HttpContext.AuthenticateAsync(IdentityServerConstants.ExternalCookieAuthenticationScheme)).Properties?.Items["returnUrl"]; return(Redirect(interaction.IsValidReturnUrl(returnUrl) ? returnUrl : "/")); }
public async Task <IActionResult> CreateAsync([FromBody] CreateNotificationRequest request) { try { request.ValidateSchema(); if (request.ValidationResult.IsInvalid()) { var errors = request.ValidationResult.GetErrors(); _logger.LogWarning("[NotificationController][CreateAsync]\nInvalid request\n{@request}\n{@errors}", request, errors); return(BadRequest(errors)); } _logger.LogInformation("[NotificationController][CreateAsync] Execute UseCase\n{@request}", request); await _eventBus.Publish <CreateNotificationEvent>(request); return(Ok()); } catch (Exception ex) { _logger.LogError(ex.Message, ex); return(StatusCode(StatusCodes.Status500InternalServerError)); } }
public async Task CreateProjectService(Guid organizationId, Guid projectId, ProjectServicePostRp resource, string userId = null) { string loggedUserId = userId ?? _identityService.GetUserId(); User user = await _userRepository.GetUser(loggedUserId); DomainModels.ProjectServiceTemplate projectServiceTemplate = await _projectServiceTemplateRepository.GetProjectServiceTemplateById(resource.ProjectServiceTemplateId); if (projectServiceTemplate == null) { await _domainManagerService.AddConflict($"The pipe template with id {resource.ProjectServiceTemplateId} does not exists."); return; } DomainModels.Organization organization = user.FindOrganizationById(organizationId); if (organization == null) { await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists."); return; } DomainModels.Project project = user.FindProjectById(projectId, false); if (project == null) { await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists."); return; } if (project.Status != EntityStatus.Active) { await _domainManagerService.AddConflict($"The project with id {projectId} must be in status Active to add a new service."); return; } DomainModels.ProjectService existingService = project.GetServiceByName(resource.Name); if (existingService != null) { await _domainManagerService.AddConflict($"The pipe name {resource.Name} has already been taken."); return; } CMSAuthCredentialModel cmsAuthCredential = this._cmsCredentialService(project.OrganizationCMS.Type).GetToken( _dataProtectorService.Unprotect(project.OrganizationCMS.AccountId), _dataProtectorService.Unprotect(project.OrganizationCMS.AccountName), _dataProtectorService.Unprotect(project.OrganizationCMS.AccessSecret), _dataProtectorService.Unprotect(project.OrganizationCMS.AccessToken)); CMSServiceAvailabilityResultModel cmsServiceAvailability = await _cmsService(project.OrganizationCMS.Type).ValidateServiceAvailability(cmsAuthCredential, project.OrganizationExternalId, project.ProjectExternalId, project.Name, resource.RepositoryName); if (!cmsServiceAvailability.Success) { await _domainManagerService.AddConflict($"The CMS data is not valid. {cmsServiceAvailability.GetReasonForNoSuccess()}"); return; } DomainModels.ProjectService newService = user.CreateProjectService(organizationId, projectId, project.OrganizationCMSId, resource.AgentPoolId, resource.Name, resource.RepositoryName, resource.Description, resource.ProjectServiceTemplateId, projectServiceTemplate.PipeType); //SaveChanges in CMS CMSServiceCreateModel serviceCreateModel = CMSServiceCreateModel.Factory.Create(project.OrganizationExternalId, project.ProjectExternalId, project.Name, resource.RepositoryName, project.ProjectVisibility == ProjectVisibility.Public ? true : false); CMSServiceCreateResultModel cmsServiceCreate = await _cmsService(project.OrganizationCMS.Type).CreateService(cmsAuthCredential, serviceCreateModel); if (!cmsServiceCreate.Success) { await _domainManagerService.AddConflict($"The CMS data is not valid. {cmsServiceCreate.GetReasonForNoSuccess()}"); return; } newService.UpdateExternalInformation(cmsServiceCreate.ServiceExternalId, cmsServiceCreate.ServiceExternalUrl, resource.Name); newService.AddEnvironmentsAndVariables(projectServiceTemplate.Parameters); _userRepository.Update(user); await _userRepository.SaveChanges(); await _domainManagerService.AddResult("ServiceId", newService.ProjectServiceId); if (project.OrganizationCPS == null) { project.OrganizationCPS = new OrganizationCPS { Type = CloudProviderService.None } } ; var @event = new ProjectServiceCreatedEvent(_correlationId) { OrganizationId = organization.OrganizationId, OrganizationName = organization.Name, ProjectId = project.ProjectId, ServiceId = newService.ProjectServiceId, ProjectExternalId = project.ProjectExternalId, ProjectExternalEndpointId = project.ProjectExternalEndpointId, ProjectExternalGitEndpoint = project.ProjectExternalGitEndpoint, ProjectVSTSFakeId = project.ProjectVSTSFakeId, ProjectVSTSFakeName = project.ProjectVSTSFakeName, ProjectName = project.Name, InternalProjectName = project.InternalName, AgentPoolId = newService.AgentPoolId, ServiceExternalId = newService.ProjectServiceExternalId, ServiceExternalUrl = newService.ProjectServiceExternalUrl, ServiceName = resource.Name, InternalServiceName = newService.InternalName, ServiceTemplateUrl = projectServiceTemplate.Url, CMSType = project.OrganizationCMS.Type, CMSAccountId = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountId), CMSAccountName = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountName), CMSAccessId = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessId), CMSAccessSecret = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessSecret), CMSAccessToken = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessToken), UserId = loggedUserId, TemplateParameters = projectServiceTemplate.Parameters.Select(x => new ProjectServiceTemplateParameterCreatedEvent() { VariableName = x.VariableName, Value = x.Value, Scope = x.Scope }).ToList(), CPSType = project.OrganizationCPS.Type, CPSAccessId = project.OrganizationCPS.Type == CloudProviderService.None ? string.Empty : _dataProtectorService.Unprotect(project.OrganizationCPS.AccessId), CPSAccessName = project.OrganizationCPS.Type == CloudProviderService.None ? string.Empty : _dataProtectorService.Unprotect(project.OrganizationCPS.AccessName), CPSAccessSecret = project.OrganizationCPS.Type == CloudProviderService.None ? string.Empty : _dataProtectorService.Unprotect(project.OrganizationCPS.AccessSecret), CPSAccessRegion = project.OrganizationCPS.Type == CloudProviderService.None ? string.Empty : _dataProtectorService.Unprotect(project.OrganizationCPS.AccessRegion), TemplateAccess = projectServiceTemplate.TemplateAccess, NeedCredentials = projectServiceTemplate.NeedCredentials, RepositoryCMSType = projectServiceTemplate.TemplateAccess == DomainModels.Enums.TemplateAccess.Organization ? projectServiceTemplate.Credential.CMSType : ConfigurationManagementService.VSTS, RepositoryAccessId = projectServiceTemplate.TemplateAccess == DomainModels.Enums.TemplateAccess.Organization ? projectServiceTemplate.NeedCredentials ? _dataProtectorService.Unprotect(projectServiceTemplate.Credential.AccessId) : string.Empty : string.Empty, RepositoryAccessSecret = projectServiceTemplate.TemplateAccess == DomainModels.Enums.TemplateAccess.Organization ? projectServiceTemplate.NeedCredentials ? _dataProtectorService.Unprotect(projectServiceTemplate.Credential.AccessSecret) : string.Empty : string.Empty, RepositoryAccessToken = projectServiceTemplate.TemplateAccess == DomainModels.Enums.TemplateAccess.Organization ? projectServiceTemplate.NeedCredentials ? _dataProtectorService.Unprotect(projectServiceTemplate.Credential.AccessToken) : string.Empty : string.Empty }; //Cloud Provider Data await _eventBusService.Publish(queueName : "ProjectServiceCreatedEvent", @event : @event); }
public async Task InviteUser(Guid organizationId, OrganizationUserInvitationPostRp resource) { string loggedUserId = _identityService.GetUserId(); string loggedUserName = _identityService.GetUserName(); User user = await _userRepository.GetUser(loggedUserId); Organization organization = user.FindOrganizationById(organizationId); if (organization == null) { await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists."); return; } PipelineRole role = user.GetRoleInOrganization(organizationId); if (role != PipelineRole.OrganizationAdmin) { await _domainManagerService.AddForbidden($"You are not authorized to invite users in this organization."); return; } User invitedUser = await _userRepository.GetUserByEmail(resource.UserEmail); if (invitedUser != null) { OrganizationUser organizationUser = organization.GetOrganizationUser(resource.UserEmail); if (organizationUser != null) { await _domainManagerService.AddConflict($"The user with email {resource.UserEmail} already exists."); return; } } OrganizationUserInvitation organizationUserInvitation = organization.GetOrganizationUserInvitation(resource.UserEmail); if (organizationUserInvitation != null) { await _domainManagerService.AddConflict($"The user with email {resource.UserEmail} was already invited."); return; } OrganizationUserInvitation newUserInvitation = OrganizationUserInvitation.Factory.Create(organizationId, invitedUser == null ? null : invitedUser.Id, resource.UserEmail, resource.Role, loggedUserId); organization.AddUserInvitation(newUserInvitation); await _userRepository.SaveChanges(); var @event = new OrganizationUserInvitedEvent(_correlationId) { OrganizationUserInvitationId = newUserInvitation.OrganizationUserInvitationId, InvitationType = newUserInvitation.InvitationType, RequestorFullName = loggedUserName, Role = newUserInvitation.Role, UserEmail = newUserInvitation.UserEmail, UserFullName = invitedUser == null ? null : invitedUser.GetFullName() }; await _eventBusService.Publish(queueName : "OrganizationUserInvitedEvent", @event : @event); }
public async Task CreateProjectFeatureService(Guid organizationId, Guid projectId, Guid featureId, ProjectFeatureServicePostRp resource) { string loggedUserId = _identityService.GetUserId(); User user = await _userRepository.GetUser(loggedUserId); DomainModels.Organization organization = user.FindOrganizationById(organizationId); if (organization == null) { await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists."); return; } DomainModels.Project project = user.FindProjectById(projectId); if (project == null) { await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists."); return; } DomainModels.PipelineRole role = user.GetRoleInProject(projectId); if (role != DomainModels.PipelineRole.ProjectAdmin) { await _domainManagerService.AddForbidden($"You are not authorized to create features in this project."); return; } if (project.Status != EntityStatus.Active) { await _domainManagerService.AddConflict($"The project with id {projectId} must be in status Active to add a new feature service."); return; } DomainModels.ProjectFeature feature = project.GetFeatureById(featureId); if (feature == null) { await _domainManagerService.AddNotFound($"The project feature with id {featureId} does not exists."); return; } if (feature.Status != EntityStatus.Active) { await _domainManagerService.AddConflict($"The project feature with id {featureId} must be in status Active to add a new feature service."); return; } if (resource.Services.Length == 0) { await _domainManagerService.AddConflict($"At least one pipe must be included."); return; } List <ProjectFeatureServiceCreatedEvent> projectFeatureServiceCreatedEventList = new List <ProjectFeatureServiceCreatedEvent>(); foreach (var item in resource.Services) { DomainModels.ProjectService projectService = project.GetServiceById(item); if (projectService == null) { await _domainManagerService.AddConflict($"The pipe with id {item} does not exists."); return; } if (projectService.Status != EntityStatus.Active) { await _domainManagerService.AddConflict($"The pipe with id {item} must be in status Active to be added as a feature service."); return; } DomainModels.ProjectFeatureService projectFeatureService = feature.GetFeatureServiceById(item); if (projectFeatureService != null) { await _domainManagerService.AddConflict($"The pipe with id {item} already exists in the feature."); return; } var variables = projectService.Environments.First(x => x.ProjectEnvironment.Type == EnvironmentType.Root).Variables; feature.AddService(item, variables); projectFeatureServiceCreatedEventList.Add(new ProjectFeatureServiceCreatedEvent(_correlationId) { OrganizationId = organization.OrganizationId, ProjectId = project.ProjectId, FeatureId = feature.ProjectFeatureId, ProjectExternalId = project.ProjectExternalId, ProjectExternalEndpointId = project.ProjectExternalEndpointId, ProjectExternalGitEndpoint = project.ProjectExternalGitEndpoint, ProjectVSTSFakeName = project.ProjectVSTSFakeName, ProjectVSTSFakeId = project.ProjectVSTSFakeId, OrganizationName = organization.Name, ProjectName = project.Name, FeatureName = feature.Name, CMSType = project.OrganizationCMS.Type, CMSAccountId = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountId), CMSAccountName = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountName), CMSAccessId = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessId), CMSAccessSecret = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessSecret), CMSAccessToken = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessToken), CPSType = project.OrganizationCPS.Type, CPSAccessId = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessId), CPSAccessName = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessName), CPSAccessSecret = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessSecret), CPSAccessRegion = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessRegion), ServiceId = item, ServiceExternalId = projectService.ProjectServiceExternalId, ServiceExternalUrl = projectService.ProjectServiceExternalUrl, ServiceName = projectService.Name, InternalServiceName = projectService.InternalName, ServiceTemplateUrl = projectService.ProjectServiceTemplate.Url, ReleaseStageId = projectService.ReleaseStageId, AgentPoolId = project.AgentPoolId, UserId = loggedUserId }); } _userRepository.Update(user); await _userRepository.SaveChanges(); //send events foreach (var @event in projectFeatureServiceCreatedEventList) { await _eventBusService.Publish(queueName : "ProjectFeatureServiceCreatedEvent", @event : @event); } }
public async Task PatchProjectService(Guid organizationId, Guid projectId, Guid serviceId, ProjectServicePatchtRp resource) { var service = await _projectServiceRepository.GetProjectServiceById(organizationId, projectId, serviceId); if (service == null) { await _domainManagerService.AddNotFound($"The pipe with id {serviceId} does not exists."); return; } if (resource.CommitStageId.HasValue) { service.CommitStageId = resource.CommitStageId.Value; } if (resource.ReleaseStageId.HasValue) { service.ReleaseStageId = resource.ReleaseStageId.Value; } if (resource.CommitServiceHookId.HasValue) { service.CommitServiceHookId = resource.CommitServiceHookId.Value; } if (resource.ReleaseServiceHookId.HasValue) { service.ReleaseServiceHookId = resource.ReleaseServiceHookId.Value; } if (resource.CodeServiceHookId.HasValue) { service.CodeServiceHookId = resource.CodeServiceHookId.Value; } if (resource.ReleaseStartedServiceHookId.HasValue) { service.ReleaseStartedServiceHookId = resource.ReleaseStartedServiceHookId.Value; } if (resource.ReleasePendingApprovalServiceHookId.HasValue) { service.ReleasePendingApprovalServiceHookId = resource.ReleasePendingApprovalServiceHookId.Value; } if (resource.ReleaseCompletedApprovalServiceHookId.HasValue) { service.ReleaseCompletedApprovalServiceHookId = resource.ReleaseCompletedApprovalServiceHookId.Value; } if (resource.PipelineStatus.HasValue) { service.PipelineStatus = resource.PipelineStatus.Value; } _projectServiceRepository.Update(service); await _projectServiceRepository.SaveChanges(); if (resource.ReleaseStageId.HasValue) { var @event = new ProjectEnvironmentCreatedEvent(_correlationId) { OrganizationId = service.Project.Organization.OrganizationId, OrganizationName = service.Project.Organization.Name, ProjectId = service.Project.ProjectId, ProjectExternalId = service.Project.ProjectExternalId, ProjectExternalEndpointId = service.Project.ProjectExternalEndpointId, ProjectVSTSFakeName = service.Project.ProjectVSTSFakeName, ProjectName = service.Project.Name, CMSType = service.Project.OrganizationCMS.Type, CMSAccountId = _dataProtectorService.Unprotect(service.Project.OrganizationCMS.AccountId), CMSAccountName = _dataProtectorService.Unprotect(service.Project.OrganizationCMS.AccountName), CMSAccessId = _dataProtectorService.Unprotect(service.Project.OrganizationCMS.AccessId), CMSAccessSecret = _dataProtectorService.Unprotect(service.Project.OrganizationCMS.AccessSecret), CMSAccessToken = _dataProtectorService.Unprotect(service.Project.OrganizationCMS.AccessToken), ReleseStageId = resource.ReleaseStageId.Value }; @event.Environments = new List <ProjectEnvironmentItemCreatedEvent>(); foreach (var item in service.Environments) { var parentEnvironment = service.Project.GetEnvironments().First(x => x.ProjectEnvironmentId == item.ProjectEnvironmentId); var serviceEnvironment = new ProjectEnvironmentItemCreatedEvent(); serviceEnvironment.Id = item.ProjectEnvironmentId; serviceEnvironment.Name = parentEnvironment.Name; serviceEnvironment.RequiredApproval = parentEnvironment.RequiresApproval; serviceEnvironment.Variables = new List <ProjectEnvironmentItemVariableCreatedEvent>(); serviceEnvironment.Rank = parentEnvironment.Rank; serviceEnvironment.LastSuccessVersionId = item.LastSuccessVersionId; serviceEnvironment.LastSuccessVersionName = item.LastSuccessVersionName; if (parentEnvironment.Variables != null) { foreach (var variable in parentEnvironment.Variables) { serviceEnvironment.Variables.Add(new ProjectEnvironmentItemVariableCreatedEvent() { Name = variable.Name, Value = variable.Value }); } } if (item.Variables != null) { foreach (var variable in item.Variables) { serviceEnvironment.Variables.Add(new ProjectEnvironmentItemVariableCreatedEvent() { Name = variable.Name, Value = variable.Value }); } } @event.Environments.Add(serviceEnvironment); } //Cloud Provider Data @event.CPSType = service.Project.OrganizationCPS.Type; @event.CPSAccessId = _dataProtectorService.Unprotect(service.Project.OrganizationCPS.AccessId); @event.CPSAccessName = _dataProtectorService.Unprotect(service.Project.OrganizationCPS.AccessName); @event.CPSAccessSecret = _dataProtectorService.Unprotect(service.Project.OrganizationCPS.AccessSecret); @event.CPSAccessRegion = _dataProtectorService.Unprotect(service.Project.OrganizationCPS.AccessRegion); await _eventBusService.Publish(queueName : "ProjectEnvironmentCreatedEvent", @event : @event); } }
public async Task CreateProject(Guid organizationId, ProjectPostRp resource) { string loggedUserId = _identityService.GetUserId(); User user = await _userRepository.GetUser(loggedUserId); Organization organization = user.FindOrganizationById(organizationId); if (organization == null) { await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists."); return; } OrganizationCMS organizationCMS = organization.GetConfigurationManagementServiceById(resource.OrganizationCMSId); if (organizationCMS == null) { await _domainManagerService.AddNotFound($"The configuration management service with id {resource.OrganizationCMSId} does not exists."); return; } if (organizationCMS.Type == ConfigurationManagementService.VSTS && resource.projectVisibility == ProjectVisibility.None) { await _domainManagerService.AddConflict($"The project visibility should be Private or Public."); return; } OrganizationCPS organizationCPS = null; if (resource.OrganizationCPSId.HasValue) { organizationCPS = organization.GetCloudProviderServiceById(resource.OrganizationCPSId.Value); if (organizationCPS == null) { await _domainManagerService.AddNotFound($"The cloud provider service with id {resource.OrganizationCPSId} does not exists."); return; } } else { organizationCPS = new OrganizationCPS { Type = CloudProviderService.None }; } ProjectTemplate projectTemplate = null; if (resource.ProjectTemplateId.HasValue) { projectTemplate = await _projectTemplateRepository.GetProjectTemplateById(resource.ProjectTemplateId.Value); if (projectTemplate == null) { await _domainManagerService.AddNotFound($"The project template with id {resource.ProjectTemplateId.Value} does not exists."); return; } } Project existingProject = organization.GetProjectByName(resource.Name); if (existingProject != null) { await _domainManagerService.AddConflict($"The project name {resource.Name} has already been taken."); return; } //Auth CMSAuthCredentialModel cmsAuthCredential = this._cmsCredentialService(organizationCMS.Type).GetToken( _dataProtectorService.Unprotect(organizationCMS.AccountId), _dataProtectorService.Unprotect(organizationCMS.AccountName), _dataProtectorService.Unprotect(organizationCMS.AccessSecret), _dataProtectorService.Unprotect(organizationCMS.AccessToken)); CMSProjectAvailabilityResultModel cmsProjectAvailability = await _cmsService(organizationCMS.Type).ValidateProjectAvailability(cmsAuthCredential, resource.TeamId, resource.Name); if (!cmsProjectAvailability.Success) { await _domainManagerService.AddConflict($"The CMS data is not valid. {cmsProjectAvailability.GetReasonForNoSuccess()}"); return; } Project newProject = user.CreateProject(organizationId, resource.TeamId, resource.Name, resource.Description, resource.ProjectType, resource.OrganizationCMSId, resource.OrganizationCPSId, resource.ProjectTemplateId, resource.AgentPoolId, resource.projectVisibility, organizationCPS.Type, organizationCMS.Type); //SaveChanges in CSM CMSProjectCreateModel projectCreateModel = CMSProjectCreateModel.Factory.Create(organization.Name, resource.Name, resource.Description, resource.projectVisibility); projectCreateModel.TeamId = resource.TeamId; CMSProjectCreateResultModel cmsProjectCreate = await _cmsService(organizationCMS.Type).CreateProject(cmsAuthCredential, projectCreateModel); if (!cmsProjectCreate.Success) { await _domainManagerService.AddConflict($"The CMS data is not valid. {cmsProjectCreate.GetReasonForNoSuccess()}"); return; } newProject.UpdateExternalInformation(cmsProjectCreate.ProjectExternalId, resource.Name); _userRepository.Update(user); await _userRepository.SaveChanges(); await _domainManagerService.AddResult("ProjectId", newProject.ProjectId); //send event var @event = new ProjectCreatedEvent(_correlationId) { OrganizationId = organization.OrganizationId, ProjectId = newProject.ProjectId, ProjectName = newProject.Name, InternalProjectName = newProject.InternalName, ProjectVSTSFake = this._slugService.GetSlug($"{organization.Owner.Email} {organization.Name} {newProject.Name}"), AgentPoolId = newProject.AgentPoolId, CMSType = organizationCMS.Type, CMSAccountId = _dataProtectorService.Unprotect(organizationCMS.AccountId), CMSAccountName = _dataProtectorService.Unprotect(organizationCMS.AccountName), CMSAccessId = _dataProtectorService.Unprotect(organizationCMS.AccessId), CMSAccessSecret = _dataProtectorService.Unprotect(organizationCMS.AccessSecret), CMSAccessToken = _dataProtectorService.Unprotect(organizationCMS.AccessToken), CPSType = organizationCPS.Type, CPSAccessId = organizationCPS.Type != CloudProviderService.None ? _dataProtectorService.Unprotect(organizationCPS.AccessId) : string.Empty, CPSAccessName = organizationCPS.Type != CloudProviderService.None ? _dataProtectorService.Unprotect(organizationCPS.AccessName) : string.Empty, CPSAccessSecret = organizationCPS.Type != CloudProviderService.None ? _dataProtectorService.Unprotect(organizationCPS.AccessSecret) : string.Empty, CPSAccessAppId = organizationCPS.Type != CloudProviderService.None ? _dataProtectorService.Unprotect(organizationCPS.AccessAppId) : string.Empty, CPSAccessAppSecret = organizationCPS.Type != CloudProviderService.None ? _dataProtectorService.Unprotect(organizationCPS.AccessAppSecret) : string.Empty, CPSAccessDirectory = organizationCPS.Type != CloudProviderService.None ? _dataProtectorService.Unprotect(organizationCPS.AccessDirectory) : string.Empty, UserId = loggedUserId }; if (resource.ProjectTemplateId.HasValue) { @event.ProjectTemplate = new ProjectTemplateCreatedEvent(); @event.ProjectTemplate.Services = projectTemplate.Services.Select(x => new ProjectTemplateServiceCreatedEvent() { Name = x.Name, ProjectServiceTemplateId = x.ProjectServiceTemplateId }).ToList(); } await _eventBusService.Publish(queueName : "ProjectCreatedEvent", @event : @event); }
public async Task CreateProjectFeature(Guid organizationId, Guid projectId, ProjectFeaturePostRp resource) { string loggedUserId = _identityService.GetUserId(); DomainModels.User user = await _userRepository.GetUser(loggedUserId); DomainModels.Organization organization = user.FindOrganizationById(organizationId); if (organization == null) { await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists."); return; } DomainModels.Project project = user.FindProjectById(projectId); if (project == null) { await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists."); return; } DomainModels.PipelineRole role = user.GetRoleInProject(projectId); if (role != DomainModels.PipelineRole.ProjectAdmin) { await _domainManagerService.AddForbidden($"You are not authorized to create features in this project."); return; } if (project.Status != DomainModels.EntityStatus.Active) { await _domainManagerService.AddConflict($"The project with id {projectId} must be in status Active to add a new feature."); return; } if (resource.Services.Length == 0) { await _domainManagerService.AddConflict($"At least one pipe must be included in the feature."); return; } var preparingServices = project.GetPreparingServices(); if (preparingServices.Any()) { await _domainManagerService.AddConflict($"The project with id {projectId} has pipes in status Preparing. All services must be in status Active to create a new feature"); return; } DomainModels.ProjectFeature existingFeature = project.GetFeatureByName(resource.Name); if (existingFeature != null) { await _domainManagerService.AddConflict($"The feature name {resource.Name} has already been taken."); return; } DomainModels.ProjectFeature newFeature = user.CreateProjectFeature(organizationId, projectId, resource.Name, resource.Description); //services asociated (TODO: services on demand) List <ProjectFeatureServiceCreatedEvent> @events = new List <ProjectFeatureServiceCreatedEvent>(); foreach (var item in resource.Services) { DomainModels.ProjectService projectService = project.GetServiceById(item); if (projectService == null) { await _domainManagerService.AddConflict($"The pipe id {item} does not exists."); return; } var variables = projectService.Environments.First(x => x.ProjectEnvironment.Type == EnvironmentType.Root).Variables; newFeature.AddService(item, variables); var serviceCredential = this._cloudCredentialService.ProjectServiceCredentialResolver(project, projectService); @events.Add(new ProjectFeatureServiceCreatedEvent(_correlationId) { ServiceId = item, ServiceExternalId = projectService.ProjectServiceExternalId, ServiceExternalUrl = projectService.ProjectServiceExternalUrl, ServiceName = projectService.Name, InternalServiceName = projectService.InternalName, ServiceTemplateUrl = serviceCredential.BranchUrl, ReleaseStageId = projectService.ReleaseStageId, AgentPoolId = project.AgentPoolId, OrganizationId = organization.OrganizationId, ProjectId = project.ProjectId, FeatureId = newFeature.ProjectFeatureId, ProjectExternalId = serviceCredential.ProjectExternalId, ProjectExternalEndpointId = project.ProjectExternalEndpointId, ProjectExternalGitEndpoint = project.ProjectExternalGitEndpoint, ProjectVSTSFakeName = project.ProjectVSTSFakeName, ProjectVSTSFakeId = project.ProjectVSTSFakeId, OrganizationName = organization.Name, ProjectName = serviceCredential.ProjectName, FeatureName = newFeature.Name, CMSType = serviceCredential.CMSType, CMSAccountId = serviceCredential.AccountId, CMSAccountName = serviceCredential.AccountName, CMSAccessId = serviceCredential.AccessId, CMSAccessSecret = serviceCredential.AccessSecret, CMSAccessToken = serviceCredential.AccessToken, CPSType = project.OrganizationCPS.Type, CPSAccessId = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessId), CPSAccessName = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessName), CPSAccessSecret = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessSecret), CPSAccessRegion = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessRegion), TemplateAccess = projectService.ProjectServiceTemplate.TemplateAccess, IsImported = projectService.IsImported, NeedCredentials = projectService.ProjectServiceTemplate.NeedCredentials, RepositoryCMSType = serviceCredential.CMSType, RepositoryAccessId = serviceCredential.AccessId, RepositoryAccessSecret = serviceCredential.AccessSecret, RepositoryAccessToken = serviceCredential.AccessToken, UserId = loggedUserId }); } _userRepository.Update(user); await _userRepository.SaveChanges(); await _domainManagerService.AddResult("FeatureId", newFeature.ProjectFeatureId); //send events foreach (var @event in @events) { await _eventBusService.Publish(queueName : "ProjectFeatureServiceCreatedEvent", @event : @event); } }
public async Task CreateProjectServiceEnvironmentVariables(Guid organizationId, Guid projectId, Guid serviceId, Guid environmentId, ProjectServiceEnvironmentVariablePostRp resource) { string loggedUserId = _identityService.GetUserId(); DomainModels.User user = await _userRepository.GetUser(loggedUserId); DomainModels.Organization organization = user.FindOrganizationById(organizationId); if (organization == null) { await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists."); return; } DomainModels.Project project = user.FindProjectById(projectId); if (project == null) { await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists."); return; } DomainModels.PipelineRole role = user.GetRoleInProject(projectId); if (role != DomainModels.PipelineRole.ProjectAdmin) { await _domainManagerService.AddForbidden($"You are not authorized to create environments variables in this project."); return; } if (project.Status != DomainModels.EntityStatus.Active) { await _domainManagerService.AddConflict($"The project with id {projectId} must be in status Active to add a new feature."); return; } DomainModels.ProjectService projectService = project.GetServiceById(serviceId); if (projectService == null) { await _domainManagerService.AddNotFound($"The project service with id {serviceId} does not exists."); return; } if (projectService.Status != DomainModels.EntityStatus.Active) { await _domainManagerService.AddConflict($"The pipe with id {serviceId} must be in status Active to add/modify variables."); return; } DomainModels.ProjectServiceEnvironment environment = projectService.GetServiceEnvironment(environmentId); if (environment == null) { await _domainManagerService.AddNotFound($"The environment with id {environmentId} does not exists."); return; } foreach (var resourceVariable in resource.Items) { if (string.IsNullOrEmpty(resourceVariable.Name) || string.IsNullOrEmpty(resourceVariable.Value)) { await _domainManagerService.AddConflict($"The environment variable name/value is mandatory."); return; } var variable = environment.GetVariableByName(resourceVariable.Name); if (variable != null) { environment.SetVariable(resourceVariable.Name, resourceVariable.Value); } else { environment.AddVariable(resourceVariable.Name, resourceVariable.Value); } } _userRepository.Update(user); await _userRepository.SaveChanges(); var @event = new ProjectEnvironmentCreatedEvent(_correlationId) { OrganizationId = organization.OrganizationId, OrganizationName = organization.Name, ProjectId = project.ProjectId, ProjectExternalId = project.ProjectExternalId, ProjectExternalEndpointId = project.ProjectExternalEndpointId, ProjectVSTSFakeName = project.ProjectVSTSFakeName, ProjectName = project.Name, CMSType = project.OrganizationCMS.Type, CMSAccountId = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountId), CMSAccountName = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountName), CMSAccessId = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessId), CMSAccessSecret = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessSecret), CMSAccessToken = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessToken), ReleseStageId = projectService.ReleaseStageId.Value }; @event.Environments = new List <ProjectEnvironmentItemCreatedEvent>(); foreach (var item in projectService.Environments) { var parentEnvironment = project.GetEnvironments().First(x => x.ProjectEnvironmentId == item.ProjectEnvironmentId); var serviceEnvironment = new ProjectEnvironmentItemCreatedEvent(); serviceEnvironment.Name = parentEnvironment.Name; serviceEnvironment.RequiredApproval = parentEnvironment.RequiresApproval; serviceEnvironment.Rank = parentEnvironment.Rank; serviceEnvironment.Variables = new List <ProjectEnvironmentItemVariableCreatedEvent>(); foreach (var variable in parentEnvironment.Variables) { serviceEnvironment.Variables.Add(new ProjectEnvironmentItemVariableCreatedEvent() { Name = variable.Name, Value = variable.Value }); } foreach (var variable in item.Variables) { serviceEnvironment.Variables.Add(new ProjectEnvironmentItemVariableCreatedEvent() { Name = variable.Name, Value = variable.Value }); } @event.Environments.Add(serviceEnvironment); } //Cloud Provider Data @event.CPSType = project.OrganizationCPS.Type; @event.CPSAccessId = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessId); @event.CPSAccessName = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessName); @event.CPSAccessSecret = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessSecret); @event.CPSAccessRegion = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessRegion); await _eventBusService.Publish(queueName : "ProjectEnvironmentCreatedEvent", @event : @event); }
public async Task CreateProjectEnvironmentVariables(Guid organizationId, Guid projectId, Guid environmentId, ProjectEnvironmentVariablePostRp resource) { string loggedUserId = _identityService.GetUserId(); DomainModels.User user = await _userRepository.GetUser(loggedUserId); DomainModels.Organization organization = user.FindOrganizationById(organizationId); if (organization == null) { await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists."); return; } DomainModels.Project project = user.FindProjectById(projectId); if (project == null) { await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists."); return; } DomainModels.PipelineRole role = user.GetRoleInProject(projectId); if (role != DomainModels.PipelineRole.ProjectAdmin) { await _domainManagerService.AddForbidden($"You are not authorized to create environments variables in this project."); return; } if (project.Status != DomainModels.EntityStatus.Active) { await _domainManagerService.AddConflict($"The project with id {projectId} must be in status Active to add a new feature."); return; } DomainModels.ProjectEnvironment environment = project.GetEnvironmentById(environmentId); if (environment == null) { await _domainManagerService.AddNotFound($"The environment with id {environmentId} does not exists."); return; } bool autoProvision = false; if (environment.Type == DomainModels.EnvironmentType.Root) { foreach (var resourceVariable in resource.Items) { if (string.IsNullOrEmpty(resourceVariable.Name) || string.IsNullOrEmpty(resourceVariable.Value)) { await _domainManagerService.AddConflict($"The environment variable name/value is mandatory."); return; } var variable = environment.GetVariableByName(resourceVariable.Name); if (variable != null) { environment.SetVariable(resourceVariable.Name, resourceVariable.Value); } else { environment.AddVariable(resourceVariable.Name, resourceVariable.Value); } } } else { DomainModels.ProjectEnvironment rootEnvironment = project.GetRootEnvironment(); foreach (var variable in rootEnvironment.Variables) { var resourceVariable = resource.Items.FirstOrDefault(x => x.Name.Equals(variable.Name, StringComparison.InvariantCultureIgnoreCase)); if (resourceVariable == null) { await _domainManagerService.AddConflict($"The environment variable {variable.Name} is mandatory."); return; } if (string.IsNullOrEmpty(resourceVariable.Value)) { await _domainManagerService.AddConflict($"The environment variable value {variable.Name} is mandatory."); return; } var existingVariable = environment.GetVariableByName(resourceVariable.Name); if (existingVariable != null) { environment.SetVariable(resourceVariable.Name, resourceVariable.Value); } else { environment.AddVariable(resourceVariable.Name, resourceVariable.Value); } } if (environment.Status == DomainModels.EntityStatus.Preparing) { autoProvision = environment.AutoProvision; } environment.Activate(); } var projectServices = project.GetServicesWithReleaseStages(); //replicate service environments foreach (var projectService in projectServices) { var rootVariables = projectService.GetRootEnvironmentVariables(); projectService.AddEnvironment(environment.ProjectEnvironmentId, rootVariables); } _userRepository.Update(user); await _userRepository.SaveChanges(); //send events foreach (var projectService in projectServices) { var @event = new ProjectEnvironmentCreatedEvent(_correlationId) { OrganizationId = organization.OrganizationId, OrganizationName = organization.Name, ProjectId = project.ProjectId, ProjectExternalId = project.ProjectExternalId, ProjectExternalEndpointId = project.ProjectExternalEndpointId, ProjectVSTSFakeName = project.ProjectVSTSFakeName, ProjectName = project.Name, CMSType = project.OrganizationCMS.Type, CMSAccountId = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountId), CMSAccountName = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountName), CMSAccessId = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessId), CMSAccessSecret = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessSecret), CMSAccessToken = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessToken), EnvironmentId = environment.ProjectEnvironmentId, EnvironmentName = environment.Name, EnvironmentRank = environment.Rank, EnvironmentAutoProvision = autoProvision, ReleseStageId = projectService.ReleaseStageId.Value, ServiceName = projectService.Name, ServiceLastBuildSuccessVersionId = projectService.LastBuildSuccessVersionId, ServiceLastBuildSuccessVersionName = projectService.LastBuildSuccessVersionName }; @event.Environments = new List <ProjectEnvironmentItemCreatedEvent>(); foreach (var item in projectService.Environments) { var parentEnvironment = project.GetEnvironments().First(x => x.ProjectEnvironmentId == item.ProjectEnvironmentId); var serviceEnvironment = new ProjectEnvironmentItemCreatedEvent(); serviceEnvironment.Id = item.ProjectEnvironmentId; serviceEnvironment.Name = parentEnvironment.Name; serviceEnvironment.RequiredApproval = parentEnvironment.RequiresApproval; serviceEnvironment.Variables = new List <ProjectEnvironmentItemVariableCreatedEvent>(); serviceEnvironment.Rank = parentEnvironment.Rank; serviceEnvironment.LastSuccessVersionId = item.LastSuccessVersionId; serviceEnvironment.LastSuccessVersionName = item.LastSuccessVersionName; if (parentEnvironment.Variables != null) { foreach (var variable in parentEnvironment.Variables) { serviceEnvironment.Variables.Add(new ProjectEnvironmentItemVariableCreatedEvent() { Name = variable.Name, Value = variable.Value }); } } if (item.Variables != null) { foreach (var variable in item.Variables) { serviceEnvironment.Variables.Add(new ProjectEnvironmentItemVariableCreatedEvent() { Name = variable.Name, Value = variable.Value }); } } @event.Environments.Add(serviceEnvironment); } //Cloud Provider Data @event.CPSType = project.OrganizationCPS.Type; @event.CPSAccessId = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessId); @event.CPSAccessName = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessName); @event.CPSAccessSecret = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessSecret); @event.CPSAccessRegion = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessRegion); await _eventBusService.Publish(queueName : "ProjectEnvironmentCreatedEvent", @event : @event); } }
public async Task CreateOrganizationProjectServiceTemplate(Guid organizationId, OrganizationProjectServiceTemplatePostRp resource) { string loggedUserId = _identityService.GetUserId(); User user = await _userRepository.GetUser(loggedUserId); Organization organization = user.FindOrganizationById(organizationId); if (organization == null) { await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists."); return; } PipelineRole role = user.GetRoleInOrganization(organizationId); if (role != PipelineRole.OrganizationAdmin) { await _domainManagerService.AddForbidden($"You are not authorized to create project service templates in this organization."); return; } OrganizationProjectServiceTemplate existingTemplate = organization.GetProjectServiceTemplateByName(resource.Name); if (existingTemplate != null) { await _domainManagerService.AddConflict($"The project service templates {resource.Name} has already been taken."); return; } ProjectServiceTemplate sourceProjectServiceTemplate = await _projectServiceTemplateRepository.GetProjectServiceTemplateInternalById(resource.SourceProjectServiceTemplateId); if (existingTemplate != null) { await _domainManagerService.AddConflict($"The source project service templates {resource.Name} does not exists."); return; } ProgrammingLanguage programmingLanguage = await _programmingLanguageRepository.GetProgrammingLanguageById(resource.ProgrammingLanguageId); if (programmingLanguage == null) { await _domainManagerService.AddNotFound($"The programming language with id {resource.ProgrammingLanguageId} does not exists."); return; } OrganizationCMS organizationCMS = organization.GetConfigurationManagementServiceById(resource.ConnectionId); if (organizationCMS == null) { await _domainManagerService.AddNotFound($"The connection with id {resource.ConnectionId} does not exists."); return; } if (organizationCMS.ConnectionType != Domain.Models.Enums.CMSConnectionType.TemplateLevel) { await _domainManagerService.AddConflict($"The connection with id {resource.ConnectionId} is not for templates."); return; } /*Create repository : BEGIN*/ CMSAuthCredentialModel cmsAuthCredential = this._cmsCredentialService(organizationCMS.Type).GetToken( _dataProtectorService.Unprotect(organizationCMS.AccountId), _dataProtectorService.Unprotect(organizationCMS.AccountName), _dataProtectorService.Unprotect(organizationCMS.AccessSecret), _dataProtectorService.Unprotect(organizationCMS.AccessToken)); var teamId = string.Empty; var projectId = string.Empty; if (resource.RepositoryCMSType == ConfigurationManagementService.Bitbucket) { teamId = resource.TeamId; projectId = resource.ProjectExternalId; } else { teamId = resource.ProjectExternalId; projectId = resource.ProjectExternalId; } CMSServiceAvailabilityResultModel cmsServiceAvailability = await _cmsService(organizationCMS.Type).ValidateServiceAvailability(cmsAuthCredential, teamId, projectId, resource.ProjectExternalName, resource.Name); if (!cmsServiceAvailability.Success) { await _domainManagerService.AddConflict($"The CMS data is not valid. {cmsServiceAvailability.GetReasonForNoSuccess()}"); return; } //SaveChanges in CMS CMSServiceCreateModel serviceCreateModel = CMSServiceCreateModel.Factory.Create(teamId, projectId, resource.ProjectExternalName, resource.Name, true); CMSServiceCreateResultModel cmsServiceCreate = await _cmsService(organizationCMS.Type).CreateService(cmsAuthCredential, serviceCreateModel); if (!cmsServiceCreate.Success) { await _domainManagerService.AddConflict($"The CMS data is not valid. {cmsServiceCreate.GetReasonForNoSuccess()}"); return; } /*Create repository : END*/ var template = user.AddProjectTemplateService(organizationId, resource.Name, sourceProjectServiceTemplate.ServiceCMSType, sourceProjectServiceTemplate.ServiceCPSType, resource.Description, cmsServiceCreate.ServiceExternalUrl, resource.Logo, resource.PipeType, Domain.Models.Enums.TemplateType.Standard, Domain.Models.Enums.TemplateAccess.Organization, true, resource.ProgrammingLanguageId, resource.Framework, resource.RepositoryCMSType, organizationCMS.AccessId, organizationCMS.AccessSecret, organizationCMS.AccessToken, sourceProjectServiceTemplate.Parameters); _projectServiceTemplateRepository.Add(template); await _projectServiceTemplateRepository.SaveChanges(); _userRepository.Update(user); await _userRepository.SaveChanges(); var @event = new ProjectServiceTemplateCreatedEvent(_correlationId) { OrganizationId = organization.OrganizationId, ProjectServiceTemplateId = template.ProjectServiceTemplateId, SourceTemplateUrl = sourceProjectServiceTemplate.Url, TemplateAccess = template.TemplateAccess, NeedCredentials = template.NeedCredentials, RepositoryCMSType = template.Credential.CMSType, RepositoryAccessId = template.NeedCredentials ? _dataProtectorService.Unprotect(template.Credential.AccessId) : string.Empty, RepositoryAccessSecret = template.NeedCredentials ? _dataProtectorService.Unprotect(template.Credential.AccessSecret) : string.Empty, RepositoryAccessToken = template.NeedCredentials ? _dataProtectorService.Unprotect(template.Credential.AccessToken) : string.Empty, RepositoryUrl = template.Url }; await _eventBusService.Publish(queueName : "ProjectServiceTemplateCreatedEvent", @event : @event); }
public async Task DeleteOrganization(Guid organizationId) { string loggedUserId = _identityService.GetUserId(); User user = await _userRepository.GetUser(loggedUserId); Organization organization = user.FindOrganizationById(organizationId); if (organization == null) { await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists."); return; } PipelineRole role = user.GetRoleInOrganization(organizationId); if (role != PipelineRole.OrganizationAdmin) { await _domainManagerService.AddForbidden($"You are not authorized to delete this organization."); return; } if (organization.Status != EntityStatus.Active) { await _domainManagerService.AddConflict($"The organization with id {organizationId} must be in status Active to be modified/deleted."); return; } var preparingProjects = organization.GetPreparingProjects(); if (preparingProjects.Any()) { await _domainManagerService.AddConflict($"The organization with id {organizationId} has projects in status Preparing. All projects must be in status Active to delete the organization"); return; } //validate if there are any projects/services/features in preparing status foreach (var project in organization.Projects) { var preparingServices = project.GetPreparingServices(); if (preparingServices.Any()) { await _domainManagerService.AddConflict($"The project with id {project.ProjectId} ({project.Name}) has pipes in status Preparing. All services must be in status Active to delete the project"); return; } var preparingFeatures = project.GetPreparingFeatures(); if (preparingFeatures.Any()) { await _domainManagerService.AddConflict($"The project with id {project.ProjectId} ({project.Name}) has features in status Preparing. All features must be in status Active to delete the project"); return; } } user.DeleteOrganization(organizationId); _userRepository.Update(user); await _userRepository.SaveChanges(); //send event to delete projects in CMS var projects = await _organizationRepository.GetProjects(organizationId); List <ProjectDeletedEvent> projectEventList = new List <ProjectDeletedEvent>(); foreach (var project in projects) { var organizationCMS = await _organizationCMSRepository.FindOrganizationCMSById(project.OrganizationCMSId); projectEventList.Add(new ProjectDeletedEvent(_correlationId, project.IsImported) { OrganizationExternalId = project.OrganizationExternalId, CMSType = organizationCMS.Type, CMSAccountId = _dataProtectorService.Unprotect(organizationCMS.AccountId), CMSAccountName = _dataProtectorService.Unprotect(organizationCMS.AccountName), CMSAccessId = _dataProtectorService.Unprotect(organizationCMS.AccessId), CMSAccessSecret = _dataProtectorService.Unprotect(organizationCMS.AccessSecret), CMSAccessToken = _dataProtectorService.Unprotect(organizationCMS.AccessToken), ProjectExternalId = project.ProjectExternalId, ProjectVSTSFakeId = project.ProjectVSTSFakeId }); } var organizationDeletedEvent = new OrganizationDeletedEvent(_correlationId) { Projects = projectEventList }; await _eventBusService.Publish(queueName : "OrganizationDeletedEvent", @event : organizationDeletedEvent); foreach (var project in projects) { //send event to delete clous services in CPS - Services var services = await _projectRepository.GetProjectServices(organizationId, project.ProjectId); var environments = await _projectRepository.GetProjectEnvironments(organizationId, project.ProjectId); foreach (var service in services) { var projectServiceDeletedEvent = new ProjectServiceDeletedEvent(_correlationId) { OrganizationExternalId = project.OrganizationExternalId, OrganizationName = organization.Name, ProjectName = project.Name, ServiceName = service.Name, ProjectVSTSFakeName = project.ProjectVSTSFakeName, ProjectExternalId = project.ProjectExternalId, ProjectServiceExternalId = service.ProjectServiceExternalId, CommitStageId = service.CommitStageId, ReleaseStageId = service.ReleaseStageId, CommitServiceHookId = service.CommitServiceHookId, ReleaseServiceHookId = service.ReleaseServiceHookId, CodeServiceHookId = service.CodeServiceHookId, ReleaseStartedServiceHookId = service.ReleaseStartedServiceHookId, ReleasePendingApprovalServiceHookId = service.ReleasePendingApprovalServiceHookId, ReleaseCompletedApprovalServiceHookId = service.ReleaseCompletedApprovalServiceHookId, Environments = environments.Select(x => x.Name).ToList(), CMSType = project.OrganizationCMS.Type, CMSAccountId = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountId), CMSAccountName = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountName), CMSAccessId = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessId), CMSAccessSecret = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessSecret), CMSAccessToken = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessToken), CPSType = project.OrganizationCPS.Type, CPSAccessId = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessId), CPSAccessName = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessName), CPSAccessSecret = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessSecret), CPSAccessRegion = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessRegion), CPSAccessAppId = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessAppId), CPSAccessAppSecret = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessAppSecret), CPSAccessDirectory = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessDirectory), SourceEvent = Domain.Models.Enums.SourceEvent.Organization }; await _eventBusService.Publish(queueName : "ProjectServiceDeletedEvent", @event : projectServiceDeletedEvent); } //send event to delete clous services in CPS - Features var features = await _projectRepository.GetProjectFeatures(organizationId, project.ProjectId); foreach (var feature in features) { var featureServices = await _projectFeatureRepository.GetProjectFeatureServices(organizationId, project.ProjectId, feature.ProjectFeatureId); List <ProjectFeatureServiceDeletedEvent> projectFeatureServiceDeletedEventList = new List <ProjectFeatureServiceDeletedEvent>(); foreach (var item in feature.Services) { projectFeatureServiceDeletedEventList.Add(new ProjectFeatureServiceDeletedEvent(_correlationId) { ServiceId = item.ProjectServiceId, ServiceExternalId = item.ProjectService.ProjectServiceExternalId, ServiceExternalUrl = item.ProjectService.ProjectServiceExternalUrl, ServiceName = item.ProjectService.Name, ServiceTemplateUrl = item.ProjectService.ProjectServiceTemplate.Url, CommitStageId = item.CommitStageId, ReleaseStageId = item.ReleaseStageId, CommitServiceHookId = item.CommitServiceHookId, ReleaseServiceHookId = item.ReleaseServiceHookId, CodeServiceHookId = item.CodeServiceHookId, ReleaseStartedServiceHookId = item.ReleaseStartedServiceHookId, ReleasePendingApprovalServiceHookId = item.ReleasePendingApprovalServiceHookId, ReleaseCompletedApprovalServiceHookId = item.ReleaseCompletedApprovalServiceHookId }); } var projectFeatureDeletedEvent = new ProjectFeatureDeletedEvent(_correlationId) { OrganizationId = organization.OrganizationId, OrganizationName = organization.Name, ProjectId = project.ProjectId, Services = projectFeatureServiceDeletedEventList, ProjectExternalId = project.ProjectExternalId, ProjectExternalEndpointId = project.ProjectExternalEndpointId, ProjectVSTSFakeName = project.ProjectVSTSFakeName, ProjectName = project.Name, FeatureId = feature.ProjectFeatureId, FeatureName = feature.Name, CMSType = project.OrganizationCMS.Type, CMSAccountId = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountId), CMSAccountName = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountName), CMSAccessId = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessId), CMSAccessSecret = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessSecret), CMSAccessToken = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessToken), CPSType = project.OrganizationCPS.Type, CPSAccessId = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessId), CPSAccessName = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessName), CPSAccessSecret = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessSecret), CPSAccessRegion = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessRegion), CPSAccessAppId = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessAppId), CPSAccessAppSecret = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessAppSecret), CPSAccessDirectory = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessDirectory), SourceEvent = Domain.Models.Enums.SourceEvent.Organization }; await _eventBusService.Publish(queueName : "ProjectFeatureDeletedEvent", @event : projectFeatureDeletedEvent); } } }