Search in sources :

Example 1 with AlmPatDto

use of org.sonar.db.alm.pat.AlmPatDto in project sonarqube by SonarSource.

the class ListGithubOrganizationsAction method doHandle.

private ListGithubOrganizationsWsResponse doHandle(Request request) {
    try (DbSession dbSession = dbClient.openSession(false)) {
        userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS);
        String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING);
        AlmSettingDto almSettingDto = dbClient.almSettingDao().selectByKey(dbSession, almSettingKey).orElseThrow(() -> new NotFoundException(String.format("GitHub ALM Setting '%s' not found", almSettingKey)));
        String userUuid = requireNonNull(userSession.getUuid(), "User UUID is not null");
        String url = requireNonNull(almSettingDto.getUrl(), String.format("No URL set for GitHub ALM '%s'", almSettingKey));
        AccessToken accessToken;
        if (request.hasParam(PARAM_TOKEN)) {
            String code = request.mandatoryParam(PARAM_TOKEN);
            String clientId = requireNonNull(almSettingDto.getClientId(), String.format("No clientId set for GitHub ALM '%s'", almSettingKey));
            String clientSecret = requireNonNull(almSettingDto.getDecryptedClientSecret(encryption), String.format("No clientSecret set for GitHub ALM '%s'", almSettingKey));
            try {
                accessToken = githubApplicationClient.createUserAccessToken(url, clientId, clientSecret, code);
            } catch (IllegalArgumentException e) {
                // it could also be that the code has expired!
                throw BadRequestException.create("Unable to authenticate with GitHub. " + "Check the GitHub App client ID and client secret configured in the Global Settings and try again.");
            }
            Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
            if (almPatDto.isPresent()) {
                AlmPatDto almPat = almPatDto.get();
                almPat.setPersonalAccessToken(accessToken.getValue());
                dbClient.almPatDao().update(dbSession, almPat, userSession.getLogin(), almSettingDto.getKey());
            } else {
                AlmPatDto almPat = new AlmPatDto().setPersonalAccessToken(accessToken.getValue()).setAlmSettingUuid(almSettingDto.getUuid()).setUserUuid(userUuid);
                dbClient.almPatDao().insert(dbSession, almPat, userSession.getLogin(), almSettingDto.getKey());
            }
            dbSession.commit();
        } else {
            accessToken = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto).map(AlmPatDto::getPersonalAccessToken).map(UserAccessToken::new).orElseThrow(() -> new IllegalArgumentException("No personal access token found"));
        }
        int page = request.hasParam(PAGE) ? request.mandatoryParamAsInt(PAGE) : 1;
        int pageSize = request.hasParam(PAGE_SIZE) ? request.mandatoryParamAsInt(PAGE_SIZE) : 100;
        GithubApplicationClient.Organizations githubOrganizations = githubApplicationClient.listOrganizations(url, accessToken, page, pageSize);
        ListGithubOrganizationsWsResponse.Builder response = ListGithubOrganizationsWsResponse.newBuilder().setPaging(Common.Paging.newBuilder().setPageIndex(page).setPageSize(pageSize).setTotal(githubOrganizations.getTotal()).build());
        List<Organization> organizations = githubOrganizations.getOrganizations();
        if (organizations != null) {
            organizations.forEach(githubOrganization -> response.addOrganizations(AlmIntegrations.GithubOrganization.newBuilder().setKey(githubOrganization.getLogin()).setName(githubOrganization.getLogin()).build()));
        }
        return response.build();
    }
}
Also used : GithubApplicationClient(org.sonar.alm.client.github.GithubApplicationClient) Organization(org.sonar.alm.client.github.GithubApplicationClient.Organization) UserAccessToken(org.sonar.alm.client.github.security.UserAccessToken) AlmPatDto(org.sonar.db.alm.pat.AlmPatDto) NotFoundException(org.sonar.server.exceptions.NotFoundException) DbSession(org.sonar.db.DbSession) UserAccessToken(org.sonar.alm.client.github.security.UserAccessToken) AccessToken(org.sonar.alm.client.github.security.AccessToken) AlmSettingDto(org.sonar.db.alm.setting.AlmSettingDto) ListGithubOrganizationsWsResponse(org.sonarqube.ws.AlmIntegrations.ListGithubOrganizationsWsResponse)

Example 2 with AlmPatDto

use of org.sonar.db.alm.pat.AlmPatDto in project sonarqube by SonarSource.

the class SearchGitlabReposAction method doHandle.

private AlmIntegrations.SearchGitlabReposWsResponse doHandle(Request request) {
    String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING);
    String projectName = request.param(PARAM_PROJECT_NAME);
    int pageNumber = request.mandatoryParamAsInt("p");
    int pageSize = request.mandatoryParamAsInt("ps");
    try (DbSession dbSession = dbClient.openSession(false)) {
        userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS);
        String userUuid = requireNonNull(userSession.getUuid(), "User UUID cannot be null");
        AlmSettingDto almSettingDto = dbClient.almSettingDao().selectByKey(dbSession, almSettingKey).orElseThrow(() -> new NotFoundException(String.format("ALM Setting '%s' not found", almSettingKey)));
        Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
        String personalAccessToken = almPatDto.map(AlmPatDto::getPersonalAccessToken).orElseThrow(() -> new IllegalArgumentException("No personal access token found"));
        String gitlabUrl = requireNonNull(almSettingDto.getUrl(), "ALM url cannot be null");
        ProjectList gitlabProjectList = gitlabHttpClient.searchProjects(gitlabUrl, personalAccessToken, projectName, pageNumber, pageSize);
        Map<String, ProjectKeyName> sqProjectsKeyByGitlabProjectId = getSqProjectsKeyByGitlabProjectId(dbSession, almSettingDto, gitlabProjectList);
        List<GitlabRepository> gitlabRepositories = gitlabProjectList.getProjects().stream().map(project -> toGitlabRepository(project, sqProjectsKeyByGitlabProjectId)).collect(toList());
        Paging.Builder pagingBuilder = Paging.newBuilder().setPageIndex(gitlabProjectList.getPageNumber()).setPageSize(gitlabProjectList.getPageSize());
        Integer gitlabProjectListTotal = gitlabProjectList.getTotal();
        if (gitlabProjectListTotal != null) {
            pagingBuilder.setTotal(gitlabProjectListTotal);
        }
        return AlmIntegrations.SearchGitlabReposWsResponse.newBuilder().addAllRepositories(gitlabRepositories).setPaging(pagingBuilder.build()).build();
    }
}
Also used : AlmSettingDto(org.sonar.db.alm.setting.AlmSettingDto) ProjectList(org.sonar.alm.client.gitlab.ProjectList) PROVISION_PROJECTS(org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS) AlmIntegrations(org.sonarqube.ws.AlmIntegrations) GitlabRepository(org.sonarqube.ws.AlmIntegrations.GitlabRepository) Function(java.util.function.Function) DbSession(org.sonar.db.DbSession) Request(org.sonar.api.server.ws.Request) WebService(org.sonar.api.server.ws.WebService) ProjectAlmSettingDto(org.sonar.db.alm.setting.ProjectAlmSettingDto) Map(java.util.Map) GitlabHttpClient(org.sonar.alm.client.gitlab.GitlabHttpClient) Objects.requireNonNull(java.util.Objects.requireNonNull) Response(org.sonar.api.server.ws.Response) AlmPatDto(org.sonar.db.alm.pat.AlmPatDto) Collectors.toSet(java.util.stream.Collectors.toSet) Project(org.sonar.alm.client.gitlab.Project) Set(java.util.Set) Paging(org.sonarqube.ws.Common.Paging) Collectors(java.util.stream.Collectors) BinaryOperator(java.util.function.BinaryOperator) NotFoundException(org.sonar.server.exceptions.NotFoundException) DbClient(org.sonar.db.DbClient) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Optional(java.util.Optional) AlmIntegrationsWsAction(org.sonar.server.almintegration.ws.AlmIntegrationsWsAction) UserSession(org.sonar.server.user.UserSession) WsUtils.writeProtobuf(org.sonar.server.ws.WsUtils.writeProtobuf) Paging(org.sonarqube.ws.Common.Paging) AlmPatDto(org.sonar.db.alm.pat.AlmPatDto) NotFoundException(org.sonar.server.exceptions.NotFoundException) GitlabRepository(org.sonarqube.ws.AlmIntegrations.GitlabRepository) DbSession(org.sonar.db.DbSession) ProjectList(org.sonar.alm.client.gitlab.ProjectList) AlmSettingDto(org.sonar.db.alm.setting.AlmSettingDto) ProjectAlmSettingDto(org.sonar.db.alm.setting.ProjectAlmSettingDto)

Example 3 with AlmPatDto

use of org.sonar.db.alm.pat.AlmPatDto in project sonarqube by SonarSource.

the class CheckPatAction method doHandle.

private void doHandle(Request request) {
    try (DbSession dbSession = dbClient.openSession(false)) {
        userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS);
        String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING);
        String userUuid = requireNonNull(userSession.getUuid(), "User cannot be null");
        AlmSettingDto almSettingDto = dbClient.almSettingDao().selectByKey(dbSession, almSettingKey).orElseThrow(() -> new NotFoundException(String.format("ALM Setting '%s' not found", almSettingKey)));
        AlmPatDto almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto).orElseThrow(() -> new IllegalArgumentException(String.format("personal access token for '%s' is missing", almSettingKey)));
        switch(almSettingDto.getAlm()) {
            case AZURE_DEVOPS:
                azureDevOpsHttpClient.checkPAT(requireNonNull(almSettingDto.getUrl(), URL_CANNOT_BE_NULL), requireNonNull(almPatDto.getPersonalAccessToken(), PAT_CANNOT_BE_NULL));
                break;
            case BITBUCKET:
                // Do an authenticate call to Bitbucket Server to validate that the user's personal access token is valid
                bitbucketServerRestClient.getRecentRepo(requireNonNull(almSettingDto.getUrl(), URL_CANNOT_BE_NULL), requireNonNull(almPatDto.getPersonalAccessToken(), PAT_CANNOT_BE_NULL));
                break;
            case GITLAB:
                gitlabHttpClient.searchProjects(requireNonNull(almSettingDto.getUrl(), URL_CANNOT_BE_NULL), requireNonNull(almPatDto.getPersonalAccessToken(), PAT_CANNOT_BE_NULL), null, null, null);
                break;
            case BITBUCKET_CLOUD:
                bitbucketCloudRestClient.validateAppPassword(requireNonNull(almPatDto.getPersonalAccessToken(), APP_PASSWORD_CANNOT_BE_NULL), requireNonNull(almSettingDto.getAppId(), WORKSPACE_CANNOT_BE_NULL));
                break;
            case GITHUB:
            default:
                throw new IllegalArgumentException(String.format("unsupported ALM %s", almSettingDto.getAlm()));
        }
    }
}
Also used : DbSession(org.sonar.db.DbSession) AlmPatDto(org.sonar.db.alm.pat.AlmPatDto) NotFoundException(org.sonar.server.exceptions.NotFoundException) AlmSettingDto(org.sonar.db.alm.setting.AlmSettingDto)

Example 4 with AlmPatDto

use of org.sonar.db.alm.pat.AlmPatDto in project sonarqube by SonarSource.

the class ListAzureProjectsAction method doHandle.

private ListAzureProjectsWsResponse doHandle(Request request) {
    try (DbSession dbSession = dbClient.openSession(false)) {
        userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS);
        String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING);
        String userUuid = requireNonNull(userSession.getUuid(), "User UUID is not null");
        AlmSettingDto almSettingDto = dbClient.almSettingDao().selectByKey(dbSession, almSettingKey).orElseThrow(() -> new NotFoundException(String.format("ALM Setting '%s' not found", almSettingKey)));
        Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
        String pat = almPatDto.map(AlmPatDto::getPersonalAccessToken).orElseThrow(() -> new IllegalArgumentException("No personal access token found"));
        String url = requireNonNull(almSettingDto.getUrl(), "URL cannot be null");
        GsonAzureProjectList projectList = azureDevOpsHttpClient.getProjects(url, pat);
        List<AzureProject> values = projectList.getValues().stream().map(ListAzureProjectsAction::toAzureProject).sorted(comparing(AzureProject::getName, String::compareToIgnoreCase)).collect(Collectors.toList());
        ListAzureProjectsWsResponse.Builder builder = ListAzureProjectsWsResponse.newBuilder().addAllProjects(values);
        return builder.build();
    }
}
Also used : GsonAzureProjectList(org.sonar.alm.client.azure.GsonAzureProjectList) AlmPatDto(org.sonar.db.alm.pat.AlmPatDto) NotFoundException(org.sonar.server.exceptions.NotFoundException) ListAzureProjectsWsResponse(org.sonarqube.ws.AlmIntegrations.ListAzureProjectsWsResponse) GsonAzureProject(org.sonar.alm.client.azure.GsonAzureProject) AzureProject(org.sonarqube.ws.AlmIntegrations.AzureProject) DbSession(org.sonar.db.DbSession) AlmSettingDto(org.sonar.db.alm.setting.AlmSettingDto)

Example 5 with AlmPatDto

use of org.sonar.db.alm.pat.AlmPatDto in project sonarqube by SonarSource.

the class SearchBitbucketCloudReposAction method doHandle.

private SearchBitbucketcloudReposWsResponse doHandle(Request request) {
    userSession.checkLoggedIn().checkPermission(PROVISION_PROJECTS);
    String almSettingKey = request.mandatoryParam(PARAM_ALM_SETTING);
    String repoName = request.param(PARAM_REPO_NAME);
    int page = request.mandatoryParamAsInt(PAGE);
    int pageSize = request.mandatoryParamAsInt(PAGE_SIZE);
    try (DbSession dbSession = dbClient.openSession(false)) {
        AlmSettingDto almSettingDto = dbClient.almSettingDao().selectByKey(dbSession, almSettingKey).orElseThrow(() -> new NotFoundException(String.format("ALM Setting '%s' not found", almSettingKey)));
        String workspace = ofNullable(almSettingDto.getAppId()).orElseThrow(() -> new IllegalArgumentException(String.format("workspace for alm setting %s is missing", almSettingDto.getKey())));
        String userUuid = requireNonNull(userSession.getUuid(), "User UUID cannot be null");
        Optional<AlmPatDto> almPatDto = dbClient.almPatDao().selectByUserAndAlmSetting(dbSession, userUuid, almSettingDto);
        String pat = almPatDto.map(AlmPatDto::getPersonalAccessToken).orElseThrow(() -> new IllegalArgumentException("No personal access token found"));
        RepositoryList repositoryList = bitbucketCloudRestClient.searchRepos(pat, workspace, repoName, page, pageSize);
        Map<String, String> sqProjectKeyByRepoSlug = getSqProjectKeyByRepoSlug(dbSession, almSettingDto, repositoryList.getValues());
        List<BBCRepo> bbcRepos = repositoryList.getValues().stream().map(repository -> toBBCRepo(repository, workspace, sqProjectKeyByRepoSlug)).collect(toList());
        SearchBitbucketcloudReposWsResponse.Builder builder = SearchBitbucketcloudReposWsResponse.newBuilder().setIsLastPage(repositoryList.getNext() == null).setPaging(Paging.newBuilder().setPageIndex(page).setPageSize(pageSize).build()).addAllRepositories(bbcRepos);
        return builder.build();
    }
}
Also used : AlmSettingDto(org.sonar.db.alm.setting.AlmSettingDto) BBCRepo(org.sonarqube.ws.AlmIntegrations.BBCRepo) PROVISION_PROJECTS(org.sonar.db.permission.GlobalPermission.PROVISION_PROJECTS) Repository(org.sonar.alm.client.bitbucket.bitbucketcloud.Repository) DbSession(org.sonar.db.DbSession) SearchBitbucketcloudReposWsResponse(org.sonarqube.ws.AlmIntegrations.SearchBitbucketcloudReposWsResponse) PAGE(org.sonar.api.server.ws.WebService.Param.PAGE) Request(org.sonar.api.server.ws.Request) WebService(org.sonar.api.server.ws.WebService) ProjectAlmSettingDto(org.sonar.db.alm.setting.ProjectAlmSettingDto) Collectors.toMap(java.util.stream.Collectors.toMap) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) Response(org.sonar.api.server.ws.Response) AlmPatDto(org.sonar.db.alm.pat.AlmPatDto) Collectors.toSet(java.util.stream.Collectors.toSet) Optional.ofNullable(java.util.Optional.ofNullable) BitbucketCloudRestClient(org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClient) Set(java.util.Set) Paging(org.sonarqube.ws.Common.Paging) RepositoryList(org.sonar.alm.client.bitbucket.bitbucketcloud.RepositoryList) BinaryOperator(java.util.function.BinaryOperator) NotFoundException(org.sonar.server.exceptions.NotFoundException) DbClient(org.sonar.db.DbClient) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) ProjectDto(org.sonar.db.project.ProjectDto) Optional(java.util.Optional) PAGE_SIZE(org.sonar.api.server.ws.WebService.Param.PAGE_SIZE) AlmIntegrationsWsAction(org.sonar.server.almintegration.ws.AlmIntegrationsWsAction) UserSession(org.sonar.server.user.UserSession) WsUtils.writeProtobuf(org.sonar.server.ws.WsUtils.writeProtobuf) BBCRepo(org.sonarqube.ws.AlmIntegrations.BBCRepo) AlmPatDto(org.sonar.db.alm.pat.AlmPatDto) NotFoundException(org.sonar.server.exceptions.NotFoundException) DbSession(org.sonar.db.DbSession) SearchBitbucketcloudReposWsResponse(org.sonarqube.ws.AlmIntegrations.SearchBitbucketcloudReposWsResponse) RepositoryList(org.sonar.alm.client.bitbucket.bitbucketcloud.RepositoryList) AlmSettingDto(org.sonar.db.alm.setting.AlmSettingDto) ProjectAlmSettingDto(org.sonar.db.alm.setting.ProjectAlmSettingDto)

Aggregations

AlmPatDto (org.sonar.db.alm.pat.AlmPatDto)34 NotFoundException (org.sonar.server.exceptions.NotFoundException)24 AlmSettingDto (org.sonar.db.alm.setting.AlmSettingDto)23 Test (org.junit.Test)19 UserDto (org.sonar.db.user.UserDto)19 DbSession (org.sonar.db.DbSession)14 TestRequest (org.sonar.server.ws.TestRequest)11 AlmPatsTesting.newAlmPatDto (org.sonar.db.alm.integration.pat.AlmPatsTesting.newAlmPatDto)10 ProjectAlmSettingDto (org.sonar.db.alm.setting.ProjectAlmSettingDto)7 Collectors (java.util.stream.Collectors)5 GithubApplicationClient (org.sonar.alm.client.github.GithubApplicationClient)5 UserAccessToken (org.sonar.alm.client.github.security.UserAccessToken)5 List (java.util.List)4 Map (java.util.Map)4 Objects.requireNonNull (java.util.Objects.requireNonNull)4 Optional (java.util.Optional)4 Set (java.util.Set)4 BinaryOperator (java.util.function.BinaryOperator)4 Collectors.toList (java.util.stream.Collectors.toList)4 Collectors.toSet (java.util.stream.Collectors.toSet)4