Search in sources :

Example 6 with HttpStatusException

use of org.edx.mobile.http.HttpStatusException in project edx-app-android by openedx.

the class OauthRefreshTokenAuthenticator method authenticate.

@Override
public synchronized Request authenticate(Route route, final Response response) throws IOException {
    logger.warn(response.toString());
    final AuthResponse currentAuth = loginPrefs.get().getCurrentAuth();
    if (null == currentAuth || null == currentAuth.refresh_token) {
        return null;
    }
    String errorCode = getErrorCode(response.peekBody(200).string());
    if (errorCode != null) {
        switch(errorCode) {
            case TOKEN_EXPIRED_ERROR_MESSAGE:
                final AuthResponse refreshedAuth;
                try {
                    refreshedAuth = refreshAccessToken(currentAuth);
                } catch (HttpStatusException e) {
                    return null;
                }
                return response.request().newBuilder().header("Authorization", refreshedAuth.token_type + " " + refreshedAuth.access_token).build();
            case TOKEN_NONEXISTENT_ERROR_MESSAGE:
            case TOKEN_INVALID_GRANT_ERROR_MESSAGE:
                // one call succeeds but the other fails. https://github.com/edx/edx-app-android/pull/834
                if (!response.request().headers().get("Authorization").split(" ")[1].equals(currentAuth.access_token)) {
                    return response.request().newBuilder().header("Authorization", currentAuth.token_type + " " + currentAuth.access_token).build();
                }
            case DISABLED_USER_ERROR_MESSAGE:
                // If the user is logged-in & marked as disabled then on the next server response
                // app will force the user to logout and navigate it to the launcher screen.
                EventBus.getDefault().post(new LogoutEvent());
                break;
        }
    }
    return null;
}
Also used : LogoutEvent(org.edx.mobile.event.LogoutEvent) HttpStatusException(org.edx.mobile.http.HttpStatusException) AuthResponse(org.edx.mobile.authentication.AuthResponse)

Example 7 with HttpStatusException

use of org.edx.mobile.http.HttpStatusException in project edx-app-android by openedx.

the class ErrorHandlingOkCallback method onResponse.

/**
 * The original callback method invoked by OkHttp upon receiving an HTTP response. This method
 * definition provides extra information that's not needed by most individual callback
 * implementations, and is also invoked when HTTP error status codes are encountered (forcing
 * the implementation to manually check for success in each case). Therefore this implementation
 * delegates to {@link #onResponse(T)} in the case where it receives a successful HTTP status
 * code, and to {@link #onFailure(Throwable)} otherwise, passing an instance of
 * {@link HttpStatusException} with the relevant error status code. This method is declared as
 * final, as subclasses are meant to be implementing the abstract {@link #onResponse(T)} method
 * instead of this one.
 * <p>
 * This implementation takes care of delivering the appropriate error message to it's registered
 * callback, and invoking the callback for request process completion.
 *
 * @param call     The Call object that was used to enqueue the request.
 * @param response The HTTP response data.
 */
@Override
public final void onResponse(@NonNull Call call, @NonNull final Response response) {
    if (!response.isSuccessful()) {
        deliverFailure(new HttpStatusException(response));
    } else {
        final String responseBodyString;
        try {
            responseBodyString = response.body().string();
        } catch (IOException error) {
            deliverFailure(error);
            return;
        }
        final T responseBody = gson.fromJson(responseBodyString, responseBodyType);
        handler.post(new Runnable() {

            @Override
            public void run() {
                if (progressCallback != null) {
                    progressCallback.finishProcess();
                }
                onResponse(responseBody);
                // Show SnackBar if user is seeing cached content while being offline.
                if (response.networkResponse() == null && !NetworkUtil.isConnected(context)) {
                    if (snackbarErrorNotification != null && refreshListener != null) {
                        snackbarErrorNotification.showError(R.string.offline_text, R.drawable.ic_wifi, R.string.lbl_reload, new View.OnClickListener() {

                            @Override
                            public void onClick(View v) {
                                if (NetworkUtil.isConnected(context)) {
                                    refreshListener.onRefresh();
                                    snackbarErrorNotification.hideError();
                                }
                            }
                        });
                    }
                }
                onFinish();
            }
        });
    }
}
Also used : HttpStatusException(org.edx.mobile.http.HttpStatusException) IOException(java.io.IOException) View(android.view.View)

Example 8 with HttpStatusException

use of org.edx.mobile.http.HttpStatusException in project edx-app-android by openedx.

the class LoginAPI method register.

@NonNull
private void register(Bundle parameters) throws Exception {
    final Map<String, String> parameterMap = new HashMap<>();
    for (String key : parameters.keySet()) {
        parameterMap.put(key, parameters.getString(key));
    }
    final Response<ResponseBody> response = loginService.register(config.getApiUrlVersionConfig().getRegistrationApiVersion(), parameterMap).execute();
    if (!response.isSuccessful()) {
        final int errorCode = response.code();
        final String errorBody = response.errorBody().string();
        if ((errorCode == HttpStatus.BAD_REQUEST || errorCode == HttpStatus.CONFLICT) && !android.text.TextUtils.isEmpty(errorBody)) {
            try {
                final Type objectMapType = new TypeToken<HashMap<String, Object>>() {
                }.getType();
                final Type fieldErrorListType = new TypeToken<List<RegisterResponseFieldError>>() {
                }.getType();
                final HashMap<String, Object> body = gson.fromJson(errorBody, objectMapType);
                final FormFieldMessageBody errorResponse = new FormFieldMessageBody();
                for (String key : body.keySet()) {
                    final Object fieldError = body.get(key);
                    if (fieldError instanceof Collection<?>) {
                        /*
                            The conversion of the errorBody from JSON String to Map<String, Object>
                            malformed the JSON properties of key & value pairs inside it i.e.
                            removed the quotations encapsulating the key & value pairs.

                            Following code line is required to transform them back into valid JSON.
                            */
                        final String fieldErrorJson = gson.toJson(fieldError);
                        errorResponse.put(key, gson.fromJson(fieldErrorJson, fieldErrorListType));
                    }
                }
                if (errorResponse.size() > 0) {
                    throw new RegistrationException(errorResponse);
                }
            } catch (JsonSyntaxException ex) {
            // Looks like the response does not contain form validation errors.
            }
        }
        throw new HttpStatusException(response);
    }
}
Also used : HashMap(java.util.HashMap) HttpStatusException(org.edx.mobile.http.HttpStatusException) ResponseBody(okhttp3.ResponseBody) Type(java.lang.reflect.Type) JsonSyntaxException(com.google.gson.JsonSyntaxException) Collection(java.util.Collection) List(java.util.List) FormFieldMessageBody(org.edx.mobile.model.api.FormFieldMessageBody) NonNull(androidx.annotation.NonNull)

Example 9 with HttpStatusException

use of org.edx.mobile.http.HttpStatusException in project edx-app-android by openedx.

the class LoginActivity method callServerForLogin.

@SuppressLint("StaticFieldLeak")
public void callServerForLogin() {
    if (!NetworkUtil.isConnected(this)) {
        showAlertDialog(getString(R.string.no_connectivity), getString(R.string.network_not_connected));
        return;
    }
    final String emailStr = activityLoginBinding.emailEt.getText().toString().trim();
    final String passwordStr = activityLoginBinding.passwordEt.getText().toString().trim();
    if (passwordStr.length() == 0) {
        activityLoginBinding.passwordWrapper.setError(getString(R.string.error_enter_password));
        activityLoginBinding.passwordEt.requestFocus();
    }
    if (emailStr.length() == 0) {
        activityLoginBinding.usernameWrapper.setError(getString(R.string.error_enter_email));
        activityLoginBinding.emailEt.requestFocus();
    }
    if (emailStr.length() > 0 && passwordStr.length() > 0) {
        activityLoginBinding.emailEt.setEnabled(false);
        activityLoginBinding.passwordEt.setEnabled(false);
        activityLoginBinding.forgotPasswordTv.setEnabled(false);
        activityLoginBinding.endUserAgreementTv.setEnabled(false);
        LoginTask logintask = new LoginTask(this, activityLoginBinding.emailEt.getText().toString().trim(), activityLoginBinding.passwordEt.getText().toString()) {

            @Override
            protected void onPostExecute(AuthResponse result) {
                super.onPostExecute(result);
                if (result != null) {
                    onUserLoginSuccess(result.profile);
                }
            }

            @Override
            public void onException(Exception ex) {
                if (ex instanceof HttpStatusException && ((HttpStatusException) ex).getStatusCode() == HttpStatus.BAD_REQUEST) {
                    onUserLoginFailure(new LoginException(new LoginErrorMessage(getString(R.string.login_error), getString(R.string.login_failed))), null, null);
                } else {
                    onUserLoginFailure(ex, null, null);
                }
            }
        };
        tryToSetUIInteraction(false);
        logintask.setProgressDialog(activityLoginBinding.progress.progressIndicator);
        logintask.execute();
    }
}
Also used : LoginErrorMessage(org.edx.mobile.exception.LoginErrorMessage) LoginTask(org.edx.mobile.authentication.LoginTask) HttpStatusException(org.edx.mobile.http.HttpStatusException) LoginException(org.edx.mobile.exception.LoginException) LoginException(org.edx.mobile.exception.LoginException) HttpStatusException(org.edx.mobile.http.HttpStatusException) AuthResponse(org.edx.mobile.authentication.AuthResponse) SuppressLint(android.annotation.SuppressLint)

Example 10 with HttpStatusException

use of org.edx.mobile.http.HttpStatusException in project edx-app-android by edx.

the class LoginActivity method callServerForLogin.

@SuppressLint("StaticFieldLeak")
public void callServerForLogin() {
    if (!NetworkUtil.isConnected(this)) {
        showAlertDialog(getString(R.string.no_connectivity), getString(R.string.network_not_connected));
        return;
    }
    final String emailStr = activityLoginBinding.emailEt.getText().toString().trim();
    final String passwordStr = activityLoginBinding.passwordEt.getText().toString().trim();
    if (passwordStr.length() == 0) {
        activityLoginBinding.passwordWrapper.setError(getString(R.string.error_enter_password));
        activityLoginBinding.passwordEt.requestFocus();
    }
    if (emailStr.length() == 0) {
        activityLoginBinding.usernameWrapper.setError(getString(R.string.error_enter_email));
        activityLoginBinding.emailEt.requestFocus();
    }
    if (emailStr.length() > 0 && passwordStr.length() > 0) {
        activityLoginBinding.emailEt.setEnabled(false);
        activityLoginBinding.passwordEt.setEnabled(false);
        activityLoginBinding.forgotPasswordTv.setEnabled(false);
        activityLoginBinding.endUserAgreementTv.setEnabled(false);
        LoginTask logintask = new LoginTask(this, activityLoginBinding.emailEt.getText().toString().trim(), activityLoginBinding.passwordEt.getText().toString()) {

            @Override
            protected void onPostExecute(AuthResponse result) {
                super.onPostExecute(result);
                if (result != null) {
                    onUserLoginSuccess(result.profile);
                }
            }

            @Override
            public void onException(Exception ex) {
                if (ex instanceof HttpStatusException && ((HttpStatusException) ex).getStatusCode() == HttpStatus.BAD_REQUEST) {
                    onUserLoginFailure(new LoginException(new LoginErrorMessage(getString(R.string.login_error), getString(R.string.login_failed))), null, null);
                } else {
                    onUserLoginFailure(ex, null, null);
                }
            }
        };
        tryToSetUIInteraction(false);
        logintask.setProgressDialog(activityLoginBinding.progress.progressIndicator);
        logintask.execute();
    }
}
Also used : LoginErrorMessage(org.edx.mobile.exception.LoginErrorMessage) LoginTask(org.edx.mobile.authentication.LoginTask) HttpStatusException(org.edx.mobile.http.HttpStatusException) LoginException(org.edx.mobile.exception.LoginException) LoginException(org.edx.mobile.exception.LoginException) HttpStatusException(org.edx.mobile.http.HttpStatusException) AuthResponse(org.edx.mobile.authentication.AuthResponse) SuppressLint(android.annotation.SuppressLint)

Aggregations

HttpStatusException (org.edx.mobile.http.HttpStatusException)21 AuthResponse (org.edx.mobile.authentication.AuthResponse)9 View (android.view.View)8 IOException (java.io.IOException)5 FormFieldMessageBody (org.edx.mobile.model.api.FormFieldMessageBody)5 SocialFactory (org.edx.mobile.social.SocialFactory)5 SuppressLint (android.annotation.SuppressLint)4 NonNull (androidx.annotation.NonNull)4 AndroidEntryPoint (dagger.hilt.android.AndroidEntryPoint)4 LoginTask (org.edx.mobile.authentication.LoginTask)4 LoginErrorMessage (org.edx.mobile.exception.LoginErrorMessage)4 LoginException (org.edx.mobile.exception.LoginException)4 DialogInterface (android.content.DialogInterface)3 Bundle (android.os.Bundle)3 Request (okhttp3.Request)3 Activity (android.app.Activity)2 Intent (android.content.Intent)2 Editable (android.text.Editable)2 TextWatcher (android.text.TextWatcher)2 LinkMovementMethod (android.text.method.LinkMovementMethod)2