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);
        }
Ejemplo n.º 2
0
        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);
        }