<commit_before>package org.dataportabilityproject.serviceProviders.google;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.dataportabilityproject.serviceProviders.google.GoogleStaticObjects.JSON_FACTORY;

import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.BearerToken;
import com.google.api.client.auth.oauth2.ClientParametersAuthentication;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import java.io.IOException;
import java.util.List;
import javax.annotation.Nullable;
import org.dataportabilityproject.shared.IOInterface;
import org.dataportabilityproject.shared.auth.AuthData;
import org.dataportabilityproject.shared.auth.OfflineAuthDataGenerator;
import org.dataportabilityproject.shared.auth.OnlineAuthDataGenerator;

/**
 * A generator of Google {@link Credential}
 */
class CredentialGenerator implements OfflineAuthDataGenerator, OnlineAuthDataGenerator {
  /** Port in the "Callback URL". */
  private static final int PORT = 8080;
  private static final String CALLBACK_URL = "http://localhost:8080/callback/google";

  /** Domain name in the "Callback URL". */
  private static final String DOMAIN = "127.0.0.1";

  private final String clientId;
  private final String apiSecret;
  private final List<String> scopes;

  CredentialGenerator(String clientId, String apiSecret, List<String> scopes) {
      this.clientId = checkNotNull(clientId);
      this.apiSecret = checkNotNull(apiSecret);
    this.scopes = scopes;
  }

  @Override
  public AuthData generateAuthData(IOInterface ioInterface) throws IOException {
    Credential c = authorize();
    return toAuthData(c);
  }

  @Override
  public String generateAuthUrl(String id) throws IOException {
    return createFlow(clientId, apiSecret, scopes)
        .newAuthorizationUrl()
        .setRedirectUri(CALLBACK_URL)
        .setState(id) // TODO: Encrypt
        .build();

  }

  @Override
  public AuthData generateAuthData(String authCode, String id) throws IOException {
    AuthorizationCodeFlow flow = createFlow(clientId, apiSecret, scopes);
    TokenResponse response = flow
        .newTokenRequest(authCode)
        .setRedirectUri("http://localhost:3000/import") //TODO(chuy): Parameterize
        .execute();
    // Figure out storage
    Credential credential = flow.createAndStoreCredential(response, id);
    // Extract the Google User ID from the ID token in the auth response
    // GoogleIdToken.Payload payload = ((GoogleTokenResponse) response).parseIdToken().getPayload();
    return toAuthData(credential);
  }



  Credential getCredential(AuthData authData) {
    checkArgument(authData instanceof GoogleTokenData,
        "authData expected to be TokenSecretAuthData not %s",
        authData.getClass().getCanonicalName());
    GoogleTokenData tokenData = (GoogleTokenData) authData;

    return new Credential.Builder(BearerToken.authorizationHeaderAccessMethod())
        .setTransport(GoogleStaticObjects.getHttpTransport())
        .setJsonFactory(JSON_FACTORY)
        .setClientAuthentication(new ClientParametersAuthentication(clientId, apiSecret))
        .setTokenServerEncodedUrl(tokenData.tokenServerEncodedUrl())
        .build()
        .setAccessToken(tokenData.accessToken())
        .setRefreshToken(tokenData.refreshToken())
        .setExpiresInSeconds(0L);
  }

  private AuthData toAuthData(Credential credential) {
    return GoogleTokenData.create(
        credential.getAccessToken(),
        credential.getRefreshToken(),<commit_msg>Fix callback url.<commit_after>package org.dataportabilityproject.serviceProviders.google;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.dataportabilityproject.serviceProviders.google.GoogleStaticObjects.JSON_FACTORY;

import com.google.api.client.auth.oauth2.AuthorizationCodeFlow;
import com.google.api.client.auth.oauth2.BearerToken;
import com.google.api.client.auth.oauth2.ClientParametersAuthentication;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import java.io.IOException;
import java.util.List;
import javax.annotation.Nullable;
import org.dataportabilityproject.shared.IOInterface;
import org.dataportabilityproject.shared.auth.AuthData;
import org.dataportabilityproject.shared.auth.OfflineAuthDataGenerator;
import org.dataportabilityproject.shared.auth.OnlineAuthDataGenerator;

/**
 * A generator of Google {@link Credential}
 */
class CredentialGenerator implements OfflineAuthDataGenerator, OnlineAuthDataGenerator {
  /** Port in the "Callback URL". */
  private static final int PORT = 8080;
  private static final String CALLBACK_URL = "http://localhost:8080/callback/google";

  /** Domain name in the "Callback URL". */
  private static final String DOMAIN = "127.0.0.1";

  private final String clientId;
  private final String apiSecret;
  private final List<String> scopes;

  CredentialGenerator(String clientId, String apiSecret, List<String> scopes) {
      this.clientId = checkNotNull(clientId);
      this.apiSecret = checkNotNull(apiSecret);
    this.scopes = scopes;
  }

  @Override
  public AuthData generateAuthData(IOInterface ioInterface) throws IOException {
    Credential c = authorize();
    return toAuthData(c);
  }

  @Override
  public String generateAuthUrl(String id) throws IOException {
    return createFlow(clientId, apiSecret, scopes)
        .newAuthorizationUrl()
        .setRedirectUri(CALLBACK_URL)
        .setState(id) // TODO: Encrypt
        .build();

  }

  @Override
  public AuthData generateAuthData(String authCode, String id) throws IOException {
    AuthorizationCodeFlow flow = createFlow(clientId, apiSecret, scopes);
    String redirectAfterToken = "http://localhost:8080/callback/google";
    System.out.println("redirectAfterToken: " + redirectAfterToken);
    TokenResponse response = flow
        .newTokenRequest(authCode)
        .setRedirectUri(redirectAfterToken) //TODO(chuy): Parameterize
        .execute();
    // Figure out storage
    Credential credential = flow.createAndStoreCredential(response, id);
    // Extract the Google User ID from the ID token in the auth response
    // GoogleIdToken.Payload payload = ((GoogleTokenResponse) response).parseIdToken().getPayload();
    return toAuthData(credential);
  }



  Credential getCredential(AuthData authData) {
    checkArgument(authData instanceof GoogleTokenData,
        "authData expected to be TokenSecretAuthData not %s",
        authData.getClass().getCanonicalName());
    GoogleTokenData tokenData = (GoogleTokenData) authData;

    return new Credential.Builder(BearerToken.authorizationHeaderAccessMethod())
        .setTransport(GoogleStaticObjects.getHttpTransport())
        .setJsonFactory(JSON_FACTORY)
        .setClientAuthentication(new ClientParametersAuthentication(clientId, apiSecret))
        .setTokenServerEncodedUrl(tokenData.tokenServerEncodedUrl())
        .build()
        .setAccessToken(tokenData.accessToken())
        .setRefreshToken(tokenData.refreshToken())
        .setExpiresInSeconds(0L);
  }

  private AuthData toAuthData(Credential credential) {
    return GoogleTokenData.create(
        credential.getAccessToken(),
        credential.getRefreshToken(),
{'fraction_non_alphanumeric': 0.09424147108637794, 'fraction_numerical': 0.007258649891120251, 'mean_word_length': 4.721107266435986, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5112627', 'n_tokens_mistral': 2343, 'n_tokens_neox': 2274, 'n_words': 456}