Search in sources :

Example 1 with ScmUnauthorizedException

use of org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException in project che-server by eclipse-che.

the class BitbucketServerPersonalAccessTokenFetcher method fetchPersonalAccessToken.

@Override
public PersonalAccessToken fetchPersonalAccessToken(Subject cheUser, String scmServerUrl) throws ScmUnauthorizedException, ScmCommunicationException {
    if (!bitbucketServerApiClient.isConnected(scmServerUrl)) {
        LOG.debug("not a  valid url {} for current fetcher ", scmServerUrl);
        return null;
    }
    final String tokenName = format(TOKEN_NAME_TEMPLATE, cheUser.getUserId(), apiEndpoint.getHost());
    try {
        BitbucketUser user = bitbucketServerApiClient.getUser(EnvironmentContext.getCurrent().getSubject());
        LOG.debug("Current bitbucket user {} ", user);
        // cleanup existed
        List<BitbucketPersonalAccessToken> existingTokens = bitbucketServerApiClient.getPersonalAccessTokens(user.getSlug()).stream().filter(p -> p.getName().equals(tokenName)).collect(Collectors.toList());
        for (BitbucketPersonalAccessToken existedToken : existingTokens) {
            LOG.debug("Deleting existed che token {} {}", existedToken.getId(), existedToken.getName());
            bitbucketServerApiClient.deletePersonalAccessTokens(user.getSlug(), existedToken.getId());
        }
        BitbucketPersonalAccessToken token = bitbucketServerApiClient.createPersonalAccessTokens(user.getSlug(), tokenName, DEFAULT_TOKEN_SCOPE);
        LOG.debug("Token created = {} for {}", token.getId(), token.getUser());
        return new PersonalAccessToken(scmServerUrl, EnvironmentContext.getCurrent().getSubject().getUserId(), user.getName(), valueOf(user.getId()), token.getName(), valueOf(token.getId()), token.getToken());
    } catch (ScmBadRequestException | ScmItemNotFoundException e) {
        throw new ScmCommunicationException(e.getMessage(), e);
    }
}
Also used : ScmBadRequestException(org.eclipse.che.api.factory.server.scm.exception.ScmBadRequestException) ImmutableSet(com.google.common.collect.ImmutableSet) Logger(org.slf4j.Logger) URL(java.net.URL) ScmCommunicationException(org.eclipse.che.api.factory.server.scm.exception.ScmCommunicationException) ScmItemNotFoundException(org.eclipse.che.api.factory.server.scm.exception.ScmItemNotFoundException) LoggerFactory(org.slf4j.LoggerFactory) Set(java.util.Set) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) BitbucketServerApiClient(org.eclipse.che.api.factory.server.bitbucket.server.BitbucketServerApiClient) PersonalAccessTokenFetcher(org.eclipse.che.api.factory.server.scm.PersonalAccessTokenFetcher) ScmUnauthorizedException(org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException) Inject(javax.inject.Inject) List(java.util.List) EnvironmentContext(org.eclipse.che.commons.env.EnvironmentContext) String.valueOf(java.lang.String.valueOf) BitbucketUser(org.eclipse.che.api.factory.server.bitbucket.server.BitbucketUser) PersonalAccessToken(org.eclipse.che.api.factory.server.scm.PersonalAccessToken) Subject(org.eclipse.che.commons.subject.Subject) Optional(java.util.Optional) Named(javax.inject.Named) BitbucketPersonalAccessToken(org.eclipse.che.api.factory.server.bitbucket.server.BitbucketPersonalAccessToken) ScmItemNotFoundException(org.eclipse.che.api.factory.server.scm.exception.ScmItemNotFoundException) PersonalAccessToken(org.eclipse.che.api.factory.server.scm.PersonalAccessToken) BitbucketPersonalAccessToken(org.eclipse.che.api.factory.server.bitbucket.server.BitbucketPersonalAccessToken) ScmCommunicationException(org.eclipse.che.api.factory.server.scm.exception.ScmCommunicationException) BitbucketPersonalAccessToken(org.eclipse.che.api.factory.server.bitbucket.server.BitbucketPersonalAccessToken) BitbucketUser(org.eclipse.che.api.factory.server.bitbucket.server.BitbucketUser) ScmBadRequestException(org.eclipse.che.api.factory.server.scm.exception.ScmBadRequestException)

Example 2 with ScmUnauthorizedException

use of org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException in project devspaces-images by redhat-developer.

the class GitlabOAuthTokenFetcher method fetchPersonalAccessToken.

@Override
public PersonalAccessToken fetchPersonalAccessToken(Subject cheSubject, String scmServerUrl) throws ScmUnauthorizedException, ScmCommunicationException {
    scmServerUrl = StringUtils.trimEnd(scmServerUrl, '/');
    GitlabApiClient gitlabApiClient = getApiClient(scmServerUrl);
    if (gitlabApiClient == null || !gitlabApiClient.isConnected(scmServerUrl)) {
        LOG.debug("not a  valid url {} for current fetcher ", scmServerUrl);
        return null;
    }
    if (oAuthAPI == null) {
        throw new ScmCommunicationException(format("OAuth 2 is not configured for SCM provider [%s]. For details, refer " + "the documentation in section of SCM providers configuration.", OAUTH_PROVIDER_NAME));
    }
    OAuthToken oAuthToken;
    try {
        oAuthToken = oAuthAPI.getToken(OAUTH_PROVIDER_NAME);
        GitlabUser user = gitlabApiClient.getUser(oAuthToken.getToken());
        PersonalAccessToken token = new PersonalAccessToken(scmServerUrl, cheSubject.getUserId(), user.getUsername(), Long.toString(user.getId()), NameGenerator.generate(OAUTH_2_PREFIX, 5), NameGenerator.generate("id-", 5), oAuthToken.getToken());
        Optional<Boolean> valid = isValid(token);
        if (valid.isEmpty() || !valid.get()) {
            throw new ScmCommunicationException("Current token doesn't have the necessary  privileges. Please make sure Che app scopes are correct and containing at least: " + DEFAULT_TOKEN_SCOPES.toString());
        }
        return token;
    } catch (UnauthorizedException e) {
        throw new ScmUnauthorizedException(cheSubject.getUserName() + " is not authorized in " + OAUTH_PROVIDER_NAME + " OAuth provider.", OAUTH_PROVIDER_NAME, "2.0", getLocalAuthenticateUrl());
    } catch (NotFoundException | ServerException | ForbiddenException | BadRequestException | ScmItemNotFoundException | ScmBadRequestException | ConflictException e) {
        LOG.warn(e.getMessage());
        throw new ScmCommunicationException(e.getMessage(), e);
    }
}
Also used : ForbiddenException(org.eclipse.che.api.core.ForbiddenException) ScmItemNotFoundException(org.eclipse.che.api.factory.server.scm.exception.ScmItemNotFoundException) ServerException(org.eclipse.che.api.core.ServerException) ConflictException(org.eclipse.che.api.core.ConflictException) ScmCommunicationException(org.eclipse.che.api.factory.server.scm.exception.ScmCommunicationException) ScmItemNotFoundException(org.eclipse.che.api.factory.server.scm.exception.ScmItemNotFoundException) NotFoundException(org.eclipse.che.api.core.NotFoundException) ScmBadRequestException(org.eclipse.che.api.factory.server.scm.exception.ScmBadRequestException) OAuthToken(org.eclipse.che.api.auth.shared.dto.OAuthToken) PersonalAccessToken(org.eclipse.che.api.factory.server.scm.PersonalAccessToken) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) ScmUnauthorizedException(org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException) ScmBadRequestException(org.eclipse.che.api.factory.server.scm.exception.ScmBadRequestException) BadRequestException(org.eclipse.che.api.core.BadRequestException) ScmUnauthorizedException(org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException)

Example 3 with ScmUnauthorizedException

use of org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException in project devspaces-images by redhat-developer.

the class BitbucketServerPersonalAccessTokenFetcher method fetchPersonalAccessToken.

@Override
public PersonalAccessToken fetchPersonalAccessToken(Subject cheUser, String scmServerUrl) throws ScmUnauthorizedException, ScmCommunicationException {
    if (!bitbucketServerApiClient.isConnected(scmServerUrl)) {
        LOG.debug("not a  valid url {} for current fetcher ", scmServerUrl);
        return null;
    }
    final String tokenName = format(TOKEN_NAME_TEMPLATE, cheUser.getUserId(), apiEndpoint.getHost());
    try {
        BitbucketUser user = bitbucketServerApiClient.getUser(EnvironmentContext.getCurrent().getSubject());
        LOG.debug("Current bitbucket user {} ", user);
        // cleanup existed
        List<BitbucketPersonalAccessToken> existingTokens = bitbucketServerApiClient.getPersonalAccessTokens(user.getSlug()).stream().filter(p -> p.getName().equals(tokenName)).collect(Collectors.toList());
        for (BitbucketPersonalAccessToken existedToken : existingTokens) {
            LOG.debug("Deleting existed che token {} {}", existedToken.getId(), existedToken.getName());
            bitbucketServerApiClient.deletePersonalAccessTokens(user.getSlug(), existedToken.getId());
        }
        BitbucketPersonalAccessToken token = bitbucketServerApiClient.createPersonalAccessTokens(user.getSlug(), tokenName, DEFAULT_TOKEN_SCOPE);
        LOG.debug("Token created = {} for {}", token.getId(), token.getUser());
        return new PersonalAccessToken(scmServerUrl, EnvironmentContext.getCurrent().getSubject().getUserId(), user.getName(), valueOf(user.getId()), token.getName(), valueOf(token.getId()), token.getToken());
    } catch (ScmBadRequestException | ScmItemNotFoundException e) {
        throw new ScmCommunicationException(e.getMessage(), e);
    }
}
Also used : ScmBadRequestException(org.eclipse.che.api.factory.server.scm.exception.ScmBadRequestException) ImmutableSet(com.google.common.collect.ImmutableSet) Logger(org.slf4j.Logger) URL(java.net.URL) ScmCommunicationException(org.eclipse.che.api.factory.server.scm.exception.ScmCommunicationException) ScmItemNotFoundException(org.eclipse.che.api.factory.server.scm.exception.ScmItemNotFoundException) LoggerFactory(org.slf4j.LoggerFactory) Set(java.util.Set) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) BitbucketServerApiClient(org.eclipse.che.api.factory.server.bitbucket.server.BitbucketServerApiClient) PersonalAccessTokenFetcher(org.eclipse.che.api.factory.server.scm.PersonalAccessTokenFetcher) ScmUnauthorizedException(org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException) Inject(javax.inject.Inject) List(java.util.List) EnvironmentContext(org.eclipse.che.commons.env.EnvironmentContext) String.valueOf(java.lang.String.valueOf) BitbucketUser(org.eclipse.che.api.factory.server.bitbucket.server.BitbucketUser) PersonalAccessToken(org.eclipse.che.api.factory.server.scm.PersonalAccessToken) Subject(org.eclipse.che.commons.subject.Subject) Optional(java.util.Optional) Named(javax.inject.Named) BitbucketPersonalAccessToken(org.eclipse.che.api.factory.server.bitbucket.server.BitbucketPersonalAccessToken) ScmItemNotFoundException(org.eclipse.che.api.factory.server.scm.exception.ScmItemNotFoundException) PersonalAccessToken(org.eclipse.che.api.factory.server.scm.PersonalAccessToken) BitbucketPersonalAccessToken(org.eclipse.che.api.factory.server.bitbucket.server.BitbucketPersonalAccessToken) ScmCommunicationException(org.eclipse.che.api.factory.server.scm.exception.ScmCommunicationException) BitbucketPersonalAccessToken(org.eclipse.che.api.factory.server.bitbucket.server.BitbucketPersonalAccessToken) BitbucketUser(org.eclipse.che.api.factory.server.bitbucket.server.BitbucketUser) ScmBadRequestException(org.eclipse.che.api.factory.server.scm.exception.ScmBadRequestException)

Example 4 with ScmUnauthorizedException

use of org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException in project devspaces-images by redhat-developer.

the class HttpBitbucketServerApiClient method getUser.

@Override
public BitbucketUser getUser(Subject cheUser) throws ScmUnauthorizedException, ScmCommunicationException, ScmItemNotFoundException {
    try {
        // Since Bitbucket server API doesn't provide a way to get an account profile currently
        // authenticated user we will try to find it and by iterating over the list available to the
        // current user Bitbucket users and attempting to get their personal access tokens. To speed
        // up this process first of all we will search among users that contain(somewhere in Bitbucket
        // user
        // entity) Che's user username. At the second step, we will search against all visible(to the
        // current Che's user) bitbucket users that are not included in the first list.
        Set<String> usersByName = getUsers(cheUser.getUserName()).stream().map(BitbucketUser::getSlug).collect(Collectors.toSet());
        Optional<BitbucketUser> currentUser = findCurrentUser(usersByName);
        if (currentUser.isPresent()) {
            return currentUser.get();
        }
        Set<String> usersAllExceptByName = getUsers().stream().map(BitbucketUser::getSlug).filter(s -> !usersByName.contains(s)).collect(Collectors.toSet());
        currentUser = findCurrentUser(usersAllExceptByName);
        if (currentUser.isPresent()) {
            return currentUser.get();
        }
    } catch (ScmBadRequestException | ScmItemNotFoundException scmException) {
        throw new ScmCommunicationException(scmException.getMessage(), scmException);
    }
    throw new ScmItemNotFoundException("Current user not found. That is possible only if user are not authorized against " + serverUri);
}
Also used : ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) HTTP_BAD_REQUEST(java.net.HttpURLConnection.HTTP_BAD_REQUEST) ScmCommunicationException(org.eclipse.che.api.factory.server.scm.exception.ScmCommunicationException) LoggerFactory(org.slf4j.LoggerFactory) Duration.ofSeconds(java.time.Duration.ofSeconds) Function(java.util.function.Function) OAuthAuthenticator(org.eclipse.che.security.oauth1.OAuthAuthenticator) HttpRequest(java.net.http.HttpRequest) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) EnvironmentContext(org.eclipse.che.commons.env.EnvironmentContext) HttpHeaders(com.google.common.net.HttpHeaders) TypeFactory(com.fasterxml.jackson.databind.type.TypeFactory) CharStreams(com.google.common.io.CharStreams) Subject(org.eclipse.che.commons.subject.Subject) Duration(java.time.Duration) HttpClient(java.net.http.HttpClient) JavaType(com.fasterxml.jackson.databind.JavaType) URI(java.net.URI) LoggingUncaughtExceptionHandler(org.eclipse.che.commons.lang.concurrent.LoggingUncaughtExceptionHandler) HttpResponse(java.net.http.HttpResponse) Charsets(com.google.common.base.Charsets) ScmBadRequestException(org.eclipse.che.api.factory.server.scm.exception.ScmBadRequestException) Logger(org.slf4j.Logger) HTTP_UNAUTHORIZED(java.net.HttpURLConnection.HTTP_UNAUTHORIZED) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ScmItemNotFoundException(org.eclipse.che.api.factory.server.scm.exception.ScmItemNotFoundException) Set(java.util.Set) OAuthAuthenticationException(org.eclipse.che.security.oauth1.OAuthAuthenticationException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) ScmUnauthorizedException(org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException) UncheckedIOException(java.io.UncheckedIOException) List(java.util.List) MediaType(jakarta.ws.rs.core.MediaType) Optional(java.util.Optional) HTTP_NOT_FOUND(java.net.HttpURLConnection.HTTP_NOT_FOUND) InputStream(java.io.InputStream) ScmItemNotFoundException(org.eclipse.che.api.factory.server.scm.exception.ScmItemNotFoundException) ScmCommunicationException(org.eclipse.che.api.factory.server.scm.exception.ScmCommunicationException) ScmBadRequestException(org.eclipse.che.api.factory.server.scm.exception.ScmBadRequestException)

Example 5 with ScmUnauthorizedException

use of org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException in project devspaces-images by redhat-developer.

the class GithubPersonalAccessTokenFetcher method fetchPersonalAccessToken.

@Override
public PersonalAccessToken fetchPersonalAccessToken(Subject cheSubject, String scmServerUrl) throws ScmUnauthorizedException, ScmCommunicationException {
    OAuthToken oAuthToken;
    if (githubApiClient == null || !githubApiClient.isConnected(scmServerUrl)) {
        LOG.debug("not a  valid url {} for current fetcher ", scmServerUrl);
        return null;
    }
    try {
        oAuthToken = oAuthAPI.getToken(OAUTH_PROVIDER_NAME);
        // Find the user associated to the OAuth token by querying the GitHub API.
        GithubUser user = githubApiClient.getUser(oAuthToken.getToken());
        PersonalAccessToken token = new PersonalAccessToken(scmServerUrl, cheSubject.getUserId(), user.getLogin(), Long.toString(user.getId()), NameGenerator.generate(OAUTH_2_PREFIX, 5), NameGenerator.generate("id-", 5), oAuthToken.getToken());
        Optional<Boolean> valid = isValid(token);
        if (valid.isEmpty()) {
            throw new ScmCommunicationException("Unable to verify if current token is a valid GitHub token.  Token's scm-url needs to be '" + GithubApiClient.GITHUB_SERVER + "' and was '" + token.getScmProviderUrl() + "'");
        } else if (!valid.get()) {
            throw new ScmCommunicationException("Current token doesn't have the necessary privileges. Please make sure Che app scopes are correct and containing at least: " + DEFAULT_TOKEN_SCOPES.toString());
        }
        return token;
    } catch (UnauthorizedException e) {
        throw new ScmUnauthorizedException(cheSubject.getUserName() + " is not authorized in " + OAUTH_PROVIDER_NAME + " OAuth provider.", OAUTH_PROVIDER_NAME, "2.0", getLocalAuthenticateUrl());
    } catch (NotFoundException | ServerException | ForbiddenException | BadRequestException | ScmItemNotFoundException | ScmBadRequestException | ConflictException e) {
        LOG.error(e.getMessage());
        throw new ScmCommunicationException(e.getMessage(), e);
    }
}
Also used : ForbiddenException(org.eclipse.che.api.core.ForbiddenException) ScmItemNotFoundException(org.eclipse.che.api.factory.server.scm.exception.ScmItemNotFoundException) ServerException(org.eclipse.che.api.core.ServerException) ConflictException(org.eclipse.che.api.core.ConflictException) ScmCommunicationException(org.eclipse.che.api.factory.server.scm.exception.ScmCommunicationException) ScmItemNotFoundException(org.eclipse.che.api.factory.server.scm.exception.ScmItemNotFoundException) NotFoundException(org.eclipse.che.api.core.NotFoundException) ScmBadRequestException(org.eclipse.che.api.factory.server.scm.exception.ScmBadRequestException) OAuthToken(org.eclipse.che.api.auth.shared.dto.OAuthToken) PersonalAccessToken(org.eclipse.che.api.factory.server.scm.PersonalAccessToken) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) ScmUnauthorizedException(org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException) ScmBadRequestException(org.eclipse.che.api.factory.server.scm.exception.ScmBadRequestException) BadRequestException(org.eclipse.che.api.core.BadRequestException) ScmUnauthorizedException(org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException)

Aggregations

ScmUnauthorizedException (org.eclipse.che.api.factory.server.scm.exception.ScmUnauthorizedException)12 ScmCommunicationException (org.eclipse.che.api.factory.server.scm.exception.ScmCommunicationException)10 ScmBadRequestException (org.eclipse.che.api.factory.server.scm.exception.ScmBadRequestException)8 ScmItemNotFoundException (org.eclipse.che.api.factory.server.scm.exception.ScmItemNotFoundException)8 UnauthorizedException (org.eclipse.che.api.core.UnauthorizedException)6 PersonalAccessToken (org.eclipse.che.api.factory.server.scm.PersonalAccessToken)6 OAuthToken (org.eclipse.che.api.auth.shared.dto.OAuthToken)4 BadRequestException (org.eclipse.che.api.core.BadRequestException)4 ConflictException (org.eclipse.che.api.core.ConflictException)4 ForbiddenException (org.eclipse.che.api.core.ForbiddenException)4 NotFoundException (org.eclipse.che.api.core.NotFoundException)4 ServerException (org.eclipse.che.api.core.ServerException)4 IOException (java.io.IOException)3 List (java.util.List)3 Optional (java.util.Optional)3 Set (java.util.Set)3 Collectors (java.util.stream.Collectors)3 DevfileException (org.eclipse.che.api.workspace.server.devfile.exception.DevfileException)3 EnvironmentContext (org.eclipse.che.commons.env.EnvironmentContext)3 Subject (org.eclipse.che.commons.subject.Subject)3