Пример #1
0
        public async Task <CMSServiceCreateResultModel> CreateService(CMSAuthCredentialModel authCredential, CMSServiceCreateModel model)
        {
            var vstsmodel = new CMSVSTSServiceCreateModel();

            vstsmodel.Name       = model.Name;
            vstsmodel.Project    = new CMSVSTSServiceProjectCreateModel();
            vstsmodel.Project.Id = model.ProjectExternalId;

            CMSServiceCreateResultModel result = new CMSServiceCreateResultModel();

            var response = await _httpProxyService.PostAsync($"{model.ProjectExternalId}/_apis/git/repositories?api-version={_vstsOptions.Value.ApiVersion}", vstsmodel, authCredential);

            if (!response.IsSuccessStatusCode || response.StatusCode == System.Net.HttpStatusCode.NonAuthoritativeInformation)
            {
                if (response.StatusCode == System.Net.HttpStatusCode.NonAuthoritativeInformation)
                {
                    result.Fail($"Code: {response.StatusCode}, Reason: The credentials are not correct");
                    return(result);
                }

                result.Fail($"Code: {response.StatusCode}, Reason: {await response.Content.ReadAsStringAsync()}");
                return(result);
            }

            var responseModel = await response.MapTo <CMSVSTSServiceCreateResultModel>();

            result.ServiceExternalId  = responseModel.Id;
            result.ServiceExternalUrl = responseModel.RemoteUrl;

            return(result);
        }
        public async Task <CMSServiceCreateResultModel> CreateService(CMSAuthCredentialModel authCredential, CMSServiceCreateModel model)
        {
            CMSServiceCreateResultModel result = new CMSServiceCreateResultModel();

            var client = new HttpClient();

            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authCredential.AccessToken);
            client.BaseAddress = new Uri(authCredential.Url);

            var teamResult = await GetAccountTeams(client, authCredential);

            var defaultTeam = teamResult.Teams.FirstOrDefault(c => c.TeamId.Equals(model.TeamId));

            var response = await client.GetAsync($"/{API_VERSION}/teams/{defaultTeam.UserName}/projects/");

            var projectResult = await response.MapTo <CMSBitBucketProjectListModel>();

            var defaultProject = projectResult.Projects.FirstOrDefault(c => c.Key.Equals(model.ProjectExternalId));

            var bitbucketModel = new
            {
                scm         = "git",
                is_private  = true,
                name        = model.Name,
                description = model.Name,
                project     = new
                {
                    key = defaultProject.Key
                }
            };

            var repositoryKey = model.Name.ToLower().Replace(" ", "");

            response = await client.PostAsync($"/{API_VERSION}/repositories/{defaultTeam.UserName}/{repositoryKey}", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(bitbucketModel), Encoding.UTF8, "application/json"));

            if (!response.IsSuccessStatusCode)
            {
                result.Fail($"Code: {response.StatusCode}, Reason: {await response.Content.ReadAsStringAsync()}");
                return(result);
            }

            var serviceCreated = await response.MapTo <CMSBitBucketRepositoryModel>();

            result.ServiceExternalId  = repositoryKey;
            result.ServiceExternalUrl = serviceCreated.Links.Clone.FirstOrDefault(c => c.Name.Equals("https", StringComparison.OrdinalIgnoreCase)).Href;

            return(result);
        }
Пример #3
0
        public async Task <CMSServiceCreateResultModel> CreateService(CMSAuthCredentialModel authCredential, CMSServiceCreateModel model)
        {
            CMSServiceCreateResultModel result = new CMSServiceCreateResultModel();

            var accountList = await GetAccounts(authCredential);

            var defaultTeam = accountList.Items.FirstOrDefault(c => c.AccountId.Equals(authCredential.AccountId));

            var gitHubModel = new
            {
                name         = GetServiceName(model.ProjectName, model.Name),
                description  = model.ProjectName,
                Private      = model.IsPublic ? false : true,
                has_issues   = true,
                has_projects = true,
                has_wiki     = true
            };

            var urlRepo = "";

            if (defaultTeam != null && defaultTeam.IsOrganization)
            {
                urlRepo = $"/orgs/{defaultTeam.Name}/repos";
            }
            else
            {
                urlRepo = $"/user/repos";
            }

            var response = await _httpProxyService.PostAsync(urlRepo, gitHubModel, authCredential, Headers);

            if (!response.IsSuccessStatusCode)
            {
                result.Fail($"Code: {response.StatusCode}, Reason: {await response.Content.ReadAsStringAsync()}");
                return(result);
            }

            var serviceCreated = await response.MapTo <CMSGitHubRepositoryModel>();

            result.ServiceExternalId  = serviceCreated.Id;
            result.ServiceExternalUrl = serviceCreated.CloneUrl;

            return(result);
        }
        public async Task <CMSServiceCreateResultModel> CreateService(CMSAuthCredentialModel authCredential, CMSServiceCreateModel model)
        {
            CMSServiceCreateResultModel result = new CMSServiceCreateResultModel();

            var httpClient = new HttpClient();

            var gitLabModel = new
            {
                name                   = model.Name,
                description            = model.ProjectName,
                namespace_id           = model.ProjectExternalId,
                issues_enabled         = true,
                merge_requests_enabled = true,
                ci_config_path         = "scripts/build.definition.yml"
            };

            var request = new HttpRequestMessage(HttpMethod.Post, $"{authCredential.Url}/projects");

            request.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(gitLabModel), Encoding.UTF8, "application/json");

            request.Headers.Add("Private-Token", authCredential.AccessToken);

            var response = await httpClient.SendAsync(request);

            if (!response.IsSuccessStatusCode)
            {
                result.Fail($"Code: {response.StatusCode}, Reason: {await response.Content.ReadAsStringAsync()}");
                return(result);
            }

            var serviceCreated = await response.MapTo <CMSGitLabProjectModel>();

            result.ServiceExternalId  = serviceCreated.Id.ToString();
            result.ServiceExternalUrl = serviceCreated.CloneUrl;

            return(result);
        }
        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);
        }
Пример #6
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);
        }