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));
}
}
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;
}
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());
}
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);
}
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;
}
Aggregations