Search in sources :

Example 81 with Credentials

use of okhttp3.Credentials in project materialistic by hidroh.

the class UserServicesClient method submit.

@Override
public void submit(Context context, String title, String content, boolean isUrl, Callback callback) {
    Pair<String, String> credentials = AppUtils.getCredentials(context);
    if (credentials == null) {
        callback.onDone(false);
        return;
    }
    /*
          The flow:
          POST /submit with acc, pw
           if 302 to /login, considered failed
          POST /r with fnid, fnop, title, url or text
           if 302 to /newest, considered successful
           if 302 to /x, considered error, maybe duplicate or invalid input
           if 200 or anything else, considered error
         */
    // fetch submit page with given credentials
    execute(postSubmitForm(credentials.first, credentials.second)).flatMap(response -> response.code() != HttpURLConnection.HTTP_MOVED_TEMP ? Observable.just(response) : Observable.error(new IOException())).flatMap(response -> {
        try {
            return Observable.just(new String[] { response.header(HEADER_SET_COOKIE), response.body().string() });
        } catch (IOException e) {
            return Observable.error(e);
        } finally {
            response.close();
        }
    }).map(array -> {
        array[1] = getInputValue(array[1], SUBMIT_PARAM_FNID);
        return array;
    }).flatMap(array -> !TextUtils.isEmpty(array[1]) ? Observable.just(array) : Observable.error(new IOException())).flatMap(array -> execute(postSubmit(title, content, isUrl, array[0], array[1]))).flatMap(response -> response.code() == HttpURLConnection.HTTP_MOVED_TEMP ? Observable.just(Uri.parse(response.header(HEADER_LOCATION))) : Observable.error(new IOException())).flatMap(uri -> TextUtils.equals(uri.getPath(), DEFAULT_SUBMIT_REDIRECT) ? Observable.just(true) : Observable.error(buildException(uri))).observeOn(AndroidSchedulers.mainThread()).subscribe(callback::onDone, callback::onError);
}
Also used : HttpURLConnection(java.net.HttpURLConnection) Context(android.content.Context) Request(okhttp3.Request) Uri(android.net.Uri) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) TextUtils(android.text.TextUtils) IOException(java.io.IOException) Scheduler(rx.Scheduler) Observable(rx.Observable) Inject(javax.inject.Inject) AppUtils(io.github.hidroh.materialistic.AppUtils) Matcher(java.util.regex.Matcher) FormBody(okhttp3.FormBody) R(io.github.hidroh.materialistic.R) Toast(android.widget.Toast) Pair(androidx.core.util.Pair) Response(okhttp3.Response) Call(okhttp3.Call) Pattern(java.util.regex.Pattern) HttpUrl(okhttp3.HttpUrl) IOException(java.io.IOException)

Example 82 with Credentials

use of okhttp3.Credentials in project PokeGOAPI-Java by Grover-c13.

the class GoogleCredentialProvider method refreshToken.

/**
 * Given the refresh token fetches a new access token and returns AuthInfo.
 *
 * @param refreshToken Refresh token persisted by the user after initial login
 * @throws LoginFailedException if an exception occurs while attempting to log in
 * @throws InvalidCredentialsException if invalid credentials are used
 */
public void refreshToken(String refreshToken) throws LoginFailedException, InvalidCredentialsException {
    HttpUrl url = HttpUrl.parse(OAUTH_TOKEN_ENDPOINT).newBuilder().addQueryParameter("client_id", CLIENT_ID).addQueryParameter("client_secret", SECRET).addQueryParameter("refresh_token", refreshToken).addQueryParameter("grant_type", "refresh_token").build();
    // Empty request body
    RequestBody reqBody = RequestBody.create(null, new byte[0]);
    Request request = new Request.Builder().url(url).method("POST", reqBody).build();
    Response response = null;
    try {
        response = client.newCall(request).execute();
    } catch (IOException e) {
        throw new LoginFailedException("Network Request failed to fetch refreshed tokenId", e);
    }
    Moshi moshi = new Moshi.Builder().build();
    GoogleAuthTokenJson googleAuthTokenJson = null;
    try {
        googleAuthTokenJson = moshi.adapter(GoogleAuthTokenJson.class).fromJson(response.body().string());
        Log.d(TAG, "" + googleAuthTokenJson.expiresIn);
    } catch (IOException e) {
        throw new LoginFailedException("Failed to unmarshal the Json response to fetch refreshed tokenId", e);
    }
    if (googleAuthTokenJson.error != null) {
        throw new InvalidCredentialsException(googleAuthTokenJson.error);
    } else {
        Log.d(TAG, "Refreshed Token " + googleAuthTokenJson.idToken);
        expiresTimestamp = System.currentTimeMillis() + (googleAuthTokenJson.expiresIn * 1000 - REFRESH_TOKEN_BUFFER_TIME);
        tokenId = googleAuthTokenJson.idToken;
    }
}
Also used : Response(okhttp3.Response) LoginFailedException(com.pokegoapi.exceptions.request.LoginFailedException) Moshi(com.squareup.moshi.Moshi) InvalidCredentialsException(com.pokegoapi.exceptions.request.InvalidCredentialsException) Request(okhttp3.Request) IOException(java.io.IOException) HttpUrl(okhttp3.HttpUrl) RequestBody(okhttp3.RequestBody)

Example 83 with Credentials

use of okhttp3.Credentials in project PokeGOAPI-Java by Grover-c13.

the class GoogleUserCredentialProvider method refreshToken.

/**
 * Given the refresh token fetches a new access token and returns AuthInfo.
 *
 * @param refreshToken Refresh token persisted by the user after initial login
 * @throws LoginFailedException if an exception occurs while attempting to log in
 * @throws InvalidCredentialsException if invalid credentials are used
 */
public void refreshToken(String refreshToken) throws LoginFailedException, InvalidCredentialsException {
    HttpUrl url = HttpUrl.parse(OAUTH_TOKEN_ENDPOINT).newBuilder().addQueryParameter("client_id", CLIENT_ID).addQueryParameter("client_secret", SECRET).addQueryParameter("refresh_token", refreshToken).addQueryParameter("grant_type", "refresh_token").build();
    // Empty request body
    RequestBody reqBody = RequestBody.create(null, new byte[0]);
    Request request = new Request.Builder().url(url).method("POST", reqBody).build();
    Response response = null;
    try {
        response = client.newCall(request).execute();
    } catch (IOException e) {
        throw new LoginFailedException("Network Request failed to fetch refreshed tokenId", e);
    }
    Moshi moshi = new Moshi.Builder().build();
    GoogleAuthTokenJson googleAuthTokenJson = null;
    try {
        googleAuthTokenJson = moshi.adapter(GoogleAuthTokenJson.class).fromJson(response.body().string());
        Log.d(TAG, "" + googleAuthTokenJson.expiresIn);
    } catch (IOException e) {
        throw new LoginFailedException("Failed to unmarshal the Json response to fetch refreshed tokenId", e);
    }
    if (googleAuthTokenJson.error != null) {
        throw new LoginFailedException(googleAuthTokenJson.error);
    } else {
        Log.d(TAG, "Refreshed Token " + googleAuthTokenJson.idToken);
        expiresTimestamp = time.currentTimeMillis() + (googleAuthTokenJson.expiresIn * 1000 - REFRESH_TOKEN_BUFFER_TIME);
        tokenId = googleAuthTokenJson.idToken;
    }
}
Also used : Response(okhttp3.Response) LoginFailedException(com.pokegoapi.exceptions.request.LoginFailedException) Moshi(com.squareup.moshi.Moshi) Request(okhttp3.Request) IOException(java.io.IOException) HttpUrl(okhttp3.HttpUrl) RequestBody(okhttp3.RequestBody)

Example 84 with Credentials

use of okhttp3.Credentials in project PokeGOAPI-Java by Grover-c13.

the class GoogleUserCredentialProvider method login.

/**
 * Uses an access code to login and get tokens
 *
 * @param authCode auth code to authenticate
 * @throws LoginFailedException if an exception occurs while attempting to log in
 * @throws InvalidCredentialsException if invalid credentials are used
 */
public void login(String authCode) throws LoginFailedException, InvalidCredentialsException {
    HttpUrl url = HttpUrl.parse(OAUTH_TOKEN_ENDPOINT).newBuilder().addQueryParameter("code", authCode).addQueryParameter("client_id", CLIENT_ID).addQueryParameter("client_secret", SECRET).addQueryParameter("grant_type", "authorization_code").addQueryParameter("scope", "openid email https://www.googleapis.com/auth/userinfo.email").addQueryParameter("redirect_uri", "urn:ietf:wg:oauth:2.0:oob").build();
    // Create empty body
    RequestBody reqBody = RequestBody.create(null, new byte[0]);
    Request request = new Request.Builder().url(url).method("POST", reqBody).build();
    Response response = null;
    try {
        response = client.newCall(request).execute();
    } catch (IOException e) {
        throw new LoginFailedException("Network Request failed to fetch tokenId", e);
    }
    Moshi moshi = new Moshi.Builder().build();
    GoogleAuthTokenJson googleAuth = null;
    try {
        googleAuth = moshi.adapter(GoogleAuthTokenJson.class).fromJson(response.body().string());
        Log.d(TAG, "" + googleAuth.expiresIn);
    } catch (IOException e) {
        throw new LoginFailedException("Failed to unmarshell the Json response to fetch tokenId", e);
    }
    Log.d(TAG, "Got token: " + googleAuth.accessToken);
    expiresTimestamp = time.currentTimeMillis() + (googleAuth.expiresIn * 1000 - REFRESH_TOKEN_BUFFER_TIME);
    tokenId = googleAuth.idToken;
    refreshToken = googleAuth.refreshToken;
    authbuilder = AuthInfo.newBuilder();
}
Also used : Response(okhttp3.Response) LoginFailedException(com.pokegoapi.exceptions.request.LoginFailedException) Moshi(com.squareup.moshi.Moshi) Request(okhttp3.Request) IOException(java.io.IOException) HttpUrl(okhttp3.HttpUrl) RequestBody(okhttp3.RequestBody)

Aggregations

Request (okhttp3.Request)39 Response (okhttp3.Response)29 OkHttpClient (okhttp3.OkHttpClient)22 IOException (java.io.IOException)20 Test (org.junit.Test)16 HttpUrl (okhttp3.HttpUrl)10 RequestBody (okhttp3.RequestBody)9 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)9 ResponseBody (okhttp3.ResponseBody)8 NonNull (androidx.annotation.NonNull)7 MockResponse (okhttp3.mockwebserver.MockResponse)7 BasicAuthenticator (com.burgstaller.okhttp.basic.BasicAuthenticator)6 CachingAuthenticator (com.burgstaller.okhttp.digest.CachingAuthenticator)6 Credentials (com.burgstaller.okhttp.digest.Credentials)6 DigestAuthenticator (com.burgstaller.okhttp.digest.DigestAuthenticator)6 Observable (rx.Observable)6 AuthenticationCacheInterceptor (com.burgstaller.okhttp.AuthenticationCacheInterceptor)5 CachingAuthenticatorDecorator (com.burgstaller.okhttp.CachingAuthenticatorDecorator)5 PokemonGo (com.pokegoapi.api.PokemonGo)5 PtcCredentialProvider (com.pokegoapi.auth.PtcCredentialProvider)5