Search in sources :

Example 1 with OAuthToken

use of org.eclipse.che.api.auth.shared.dto.OAuthToken in project che by eclipse.

the class GitHubKeyUploader method uploadKey.

@Override
public void uploadKey(String publicKey) throws IOException, UnauthorizedException {
    final OAuthToken token = tokenProvider.getToken("github", EnvironmentContext.getCurrent().getSubject().getUserId());
    if (token == null || token.getToken() == null) {
        LOG.debug("Token not found, user need to authorize to upload key.");
        throw new UnauthorizedException("To upload SSH key you need to authorize.");
    }
    StringBuilder answer = new StringBuilder();
    final String url = String.format("https://api.github.com/user/keys?access_token=%s", token.getToken());
    final List<GitHubKey> gitHubUserPublicKeys = getUserPublicKeys(url, answer);
    for (GitHubKey gitHubUserPublicKey : gitHubUserPublicKeys) {
        if (publicKey.startsWith(gitHubUserPublicKey.getKey())) {
            return;
        }
    }
    final Map<String, String> postParams = new HashMap<>(2);
    postParams.put("title", "IDE SSH Key (" + new SimpleDateFormat().format(new Date()) + ")");
    postParams.put("key", new String(publicKey.getBytes()));
    final String postBody = JsonHelper.toJson(postParams);
    LOG.debug("Upload public key: {}", postBody);
    int responseCode;
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.setRequestMethod(HttpMethod.POST);
        conn.setRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
        conn.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
        conn.setRequestProperty(HttpHeaders.CONTENT_LENGTH, String.valueOf(postBody.length()));
        conn.setDoOutput(true);
        try (OutputStream out = conn.getOutputStream()) {
            out.write(postBody.getBytes());
        }
        responseCode = conn.getResponseCode();
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    LOG.debug("Upload key response code: {}", responseCode);
    if (responseCode != HttpURLConnection.HTTP_CREATED) {
        throw new IOException(String.format("%d: Failed to upload public key to https://github.com/", responseCode));
    }
}
Also used : HashMap(java.util.HashMap) OutputStream(java.io.OutputStream) IOException(java.io.IOException) Date(java.util.Date) URL(java.net.URL) OAuthToken(org.eclipse.che.api.auth.shared.dto.OAuthToken) HttpURLConnection(java.net.HttpURLConnection) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) GitHubKey(org.eclipse.che.plugin.github.shared.GitHubKey) SimpleDateFormat(java.text.SimpleDateFormat)

Example 2 with OAuthToken

use of org.eclipse.che.api.auth.shared.dto.OAuthToken in project che by eclipse.

the class GitHubOAuthAuthenticator method getToken.

@Override
public OAuthToken getToken(String userId) throws IOException {
    final OAuthToken token = super.getToken(userId);
    if (!(token == null || token.getToken() == null || token.getToken().isEmpty())) {
        // Need to check if token which stored is valid for requests, then if valid - we returns it to caller
        String tokenVerifyUrl = "https://api.github.com/?access_token=" + token.getToken();
        HttpURLConnection http = null;
        try {
            http = (HttpURLConnection) new URL(tokenVerifyUrl).openConnection();
            http.setInstanceFollowRedirects(false);
            http.setRequestMethod("GET");
            http.setRequestProperty("Accept", "application/json");
            if (http.getResponseCode() == 401) {
                return null;
            }
        } finally {
            if (http != null) {
                http.disconnect();
            }
        }
        return token;
    }
    return null;
}
Also used : OAuthToken(org.eclipse.che.api.auth.shared.dto.OAuthToken) HttpURLConnection(java.net.HttpURLConnection) URL(java.net.URL)

Example 3 with OAuthToken

use of org.eclipse.che.api.auth.shared.dto.OAuthToken in project che by eclipse.

the class OAuthAuthenticator method getToken.

/**
     * Return authorization token by userId.
     * <p/>
     * WARN!!!. DO not use it directly.
     *
     * @param userId
     *         user identifier
     * @return token value or {@code null}. When user have valid token then it will be returned,
     * when user have expired token and it can be refreshed then refreshed value will be returned,
     * when none token found for user then {@code null} will be returned,
     * when user have expired token and it can't be refreshed then {@code null} will be returned
     * @throws IOException
     *         when error occurs during token loading
     * @see org.eclipse.che.api.auth.oauth.OAuthTokenProvider#getToken(String, String)
     */
public OAuthToken getToken(String userId) throws IOException {
    if (!isConfigured()) {
        throw new IOException("Authenticator is not configured");
    }
    Credential credential = flow.loadCredential(userId);
    if (credential == null) {
        return null;
    }
    final Long expirationTime = credential.getExpiresInSeconds();
    if (expirationTime != null && expirationTime < 0) {
        boolean tokenRefreshed;
        try {
            tokenRefreshed = credential.refreshToken();
        } catch (IOException ioEx) {
            tokenRefreshed = false;
        }
        if (tokenRefreshed) {
            credential = flow.loadCredential(userId);
        } else {
            // and null result should be returned
            try {
                invalidateToken(userId);
            } catch (IOException ignored) {
            }
            return null;
        }
    }
    return newDto(OAuthToken.class).withToken(credential.getAccessToken());
}
Also used : OAuthToken(org.eclipse.che.api.auth.shared.dto.OAuthToken) Credential(com.google.api.client.auth.oauth2.Credential) IOException(java.io.IOException)

Example 4 with OAuthToken

use of org.eclipse.che.api.auth.shared.dto.OAuthToken in project che by eclipse.

the class RemoteOAuthTokenProviderTest method shouldConstructCorrectUrl.

@Test
public void shouldConstructCorrectUrl() throws Exception {
    //given
    OAuthToken expected = DtoFactory.newDto(OAuthToken.class).withScope("scope").withToken("token");
    when(httpJsonResponse.asDto(any(Class.class))).thenReturn(expected);
    when(httpJsonRequest.request()).thenReturn(httpJsonResponse);
    //when
    tokenProvider.getToken("google", "id");
    //then
    ArgumentCaptor<Link> argumentCaptor = ArgumentCaptor.forClass(Link.class);
    verify(httpJsonRequestFactory).fromLink(argumentCaptor.capture());
    Link link = argumentCaptor.getValue();
    assertEquals(link.getMethod(), "GET");
    assertEquals(link.getHref(), "http://dev.box.com/api/oauth/token?oauth_provider=google");
    assertEquals(link.getParameters().size(), 0);
}
Also used : OAuthToken(org.eclipse.che.api.auth.shared.dto.OAuthToken) Link(org.eclipse.che.api.core.rest.shared.dto.Link) Test(org.testng.annotations.Test)

Example 5 with OAuthToken

use of org.eclipse.che.api.auth.shared.dto.OAuthToken in project che by eclipse.

the class GitHubFactory method getToken.

private String getToken() throws ServerException, UnauthorizedException {
    OAuthToken token;
    try {
        token = oauthTokenProvider.getToken("github", EnvironmentContext.getCurrent().getSubject().getUserId());
    } catch (IOException e) {
        throw new ServerException(e.getMessage());
    }
    String oauthToken = token != null ? token.getToken() : null;
    if (oauthToken == null || oauthToken.isEmpty()) {
        throw new UnauthorizedException("User doesn't have access token to github");
    }
    return oauthToken;
}
Also used : OAuthToken(org.eclipse.che.api.auth.shared.dto.OAuthToken) ServerException(org.eclipse.che.api.core.ServerException) UnauthorizedException(org.eclipse.che.api.core.UnauthorizedException) IOException(java.io.IOException)

Aggregations

OAuthToken (org.eclipse.che.api.auth.shared.dto.OAuthToken)9 IOException (java.io.IOException)4 HttpURLConnection (java.net.HttpURLConnection)2 URL (java.net.URL)2 ServerException (org.eclipse.che.api.core.ServerException)2 UnauthorizedException (org.eclipse.che.api.core.UnauthorizedException)2 Test (org.testng.annotations.Test)2 OAuthCredentialsResponse (com.google.api.client.auth.oauth.OAuthCredentialsResponse)1 Credential (com.google.api.client.auth.oauth2.Credential)1 OutputStream (java.io.OutputStream)1 SimpleDateFormat (java.text.SimpleDateFormat)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 GET (javax.ws.rs.GET)1 Path (javax.ws.rs.Path)1 Produces (javax.ws.rs.Produces)1 NotFoundException (org.eclipse.che.api.core.NotFoundException)1 Link (org.eclipse.che.api.core.rest.shared.dto.Link)1 Subject (org.eclipse.che.commons.subject.Subject)1 GitHubKey (org.eclipse.che.plugin.github.shared.GitHubKey)1