Search in sources :

Example 1 with AuthResponse

use of org.edx.mobile.authentication.AuthResponse in project edx-app-android by edx.

the class LoginActivity method callServerForLogin.

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 (activityLoginBinding.emailEt != null && emailStr.length() == 0) {
        showAlertDialog(getString(R.string.login_error), getString(R.string.error_enter_email));
        activityLoginBinding.emailEt.requestFocus();
    } else if (activityLoginBinding.passwordEt != null && passwordStr.length() == 0) {
        showAlertDialog(getString(R.string.login_error), getString(R.string.error_enter_password));
        activityLoginBinding.passwordEt.requestFocus();
    } else {
        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
            public void onSuccess(@NonNull AuthResponse result) {
                onUserLoginSuccess(result.profile);
            }

            @Override
            public void onException(Exception ex) {
                if (ex instanceof HttpStatusException && ((HttpStatusException) ex).getStatusCode() == HttpStatus.UNAUTHORIZED) {
                    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)

Example 2 with AuthResponse

use of org.edx.mobile.authentication.AuthResponse in project edx-app-android by edx.

the class OauthRefreshTokenAuthenticator method refreshAccessToken.

@NonNull
private AuthResponse refreshAccessToken(AuthResponse currentAuth) throws IOException, HttpStatusException {
    // RoboGuice doesn't seem to allow this to be injected via annotation at initialization
    // time. TODO: Investigate whether this is a bug in RoboGuice.
    LoginService loginService = RoboGuice.getInjector(context).getInstance(RetrofitProvider.class).getNonOAuthBased().create(LoginService.class);
    AuthResponse refreshTokenData = executeStrict(loginService.refreshAccessToken("refresh_token", config.getOAuthClientId(), currentAuth.refresh_token));
    loginPrefs.storeRefreshTokenResponse(refreshTokenData);
    return refreshTokenData;
}
Also used : LoginService(org.edx.mobile.authentication.LoginService) AuthResponse(org.edx.mobile.authentication.AuthResponse) NonNull(android.support.annotation.NonNull)

Example 3 with AuthResponse

use of org.edx.mobile.authentication.AuthResponse in project edx-app-android by edx.

the class HttpBaseTestCase method login.

/**
 * Utility method to be used as a prerequisite for testing most API
 *
 * @throws Exception If an exception was encountered during login or
 *                   verification
 */
protected void login() throws Exception {
    // The credentials given here don't matter, we will always get the same mock response
    AuthResponse res = loginAPI.logInUsingEmail("example@example.com", "password");
    assertNotNull(res);
    assertNotNull(res.access_token);
    assertNotNull(res.token_type);
    assertNotNull(res.refresh_token);
    print(res.toString());
    assertNotNull(res.profile);
}
Also used : AuthResponse(org.edx.mobile.authentication.AuthResponse)

Example 4 with AuthResponse

use of org.edx.mobile.authentication.AuthResponse in project edx-app-android by edx.

the class RegisterActivity method createAccount.

private void createAccount() {
    boolean hasError = false;
    // prepare query (POST body)
    Bundle parameters = new Bundle();
    for (IRegistrationFieldView v : mFieldViews) {
        if (v.isValidInput()) {
            if (v.hasValue()) {
                // we submit the field only if it provides a value
                parameters.putString(v.getField().getName(), v.getCurrentValue().getAsString());
            }
        } else {
            if (!hasError) {
                // this is the first input field with error,
                // so focus on it after showing the popup
                showErrorPopup(v.getOnErrorFocusView());
            }
            hasError = true;
        }
    }
    // set honor_code and terms_of_service to true
    parameters.putString("honor_code", "true");
    parameters.putString("terms_of_service", "true");
    // set parameter required by social registration
    final String access_token = loginPrefs.getSocialLoginAccessToken();
    final String provider = loginPrefs.getSocialLoginProvider();
    boolean fromSocialNet = !TextUtils.isEmpty(access_token);
    if (fromSocialNet) {
        parameters.putString("access_token", access_token);
        parameters.putString("provider", provider);
        parameters.putString("client_id", environment.getConfig().getOAuthClientId());
    }
    // do NOT proceed if validations are failed
    if (hasError) {
        return;
    }
    // Send analytics event for Create Account button click
    final String appVersion = String.format("%s v%s", getString(R.string.android), BuildConfig.VERSION_NAME);
    environment.getAnalyticsRegistry().trackCreateAccountClicked(appVersion, provider);
    showProgress();
    final SocialFactory.SOCIAL_SOURCE_TYPE backsourceType = SocialFactory.SOCIAL_SOURCE_TYPE.fromString(provider);
    final RegisterTask task = new RegisterTask(this, parameters, access_token, backsourceType) {

        @Override
        public void onSuccess(AuthResponse auth) {
            environment.getAnalyticsRegistry().trackRegistrationSuccess(appVersion, provider);
            onUserLoginSuccess(auth.profile);
        }

        @Override
        public void onException(Exception ex) {
            hideProgress();
            if (ex instanceof LoginAPI.RegistrationException) {
                final FormFieldMessageBody messageBody = ((LoginAPI.RegistrationException) ex).getFormErrorBody();
                boolean errorShown = false;
                for (String key : messageBody.keySet()) {
                    if (key == null)
                        continue;
                    for (IRegistrationFieldView fieldView : mFieldViews) {
                        if (key.equalsIgnoreCase(fieldView.getField().getName())) {
                            List<RegisterResponseFieldError> error = messageBody.get(key);
                            showErrorOnField(error, fieldView);
                            if (!errorShown) {
                                // this is the first input field with error,
                                // so focus on it after showing the popup
                                showErrorPopup(fieldView.getOnErrorFocusView());
                                errorShown = true;
                            }
                            break;
                        }
                    }
                }
                if (errorShown) {
                    // Return here to avoid falling back to the generic error handler.
                    return;
                }
            }
            // If app version is un-supported
            if (ex instanceof HttpStatusException && ((HttpStatusException) ex).getStatusCode() == HttpStatus.UPGRADE_REQUIRED) {
                RegisterActivity.this.showAlertDialog(null, getString(R.string.app_version_unsupported_register_msg), getString(R.string.label_update), new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        AppStoreUtils.openAppInAppStore(RegisterActivity.this);
                    }
                }, getString(android.R.string.cancel), null);
            } else {
                RegisterActivity.this.showAlertDialog(null, ErrorUtils.getErrorMessage(ex, RegisterActivity.this));
            }
        }
    };
    task.execute();
}
Also used : DialogInterface(android.content.DialogInterface) Bundle(android.os.Bundle) RegisterTask(org.edx.mobile.task.RegisterTask) HttpStatusException(org.edx.mobile.http.HttpStatusException) IRegistrationFieldView(org.edx.mobile.module.registration.view.IRegistrationFieldView) HttpStatusException(org.edx.mobile.http.HttpStatusException) AuthResponse(org.edx.mobile.authentication.AuthResponse) RegisterResponseFieldError(org.edx.mobile.model.api.RegisterResponseFieldError) FormFieldMessageBody(org.edx.mobile.model.api.FormFieldMessageBody) SocialFactory(org.edx.mobile.social.SocialFactory)

Example 5 with AuthResponse

use of org.edx.mobile.authentication.AuthResponse in project edx-app-android by edx.

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.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();
                }
        }
    }
    return null;
}
Also used : HttpStatusException(org.edx.mobile.http.HttpStatusException) AuthResponse(org.edx.mobile.authentication.AuthResponse)

Aggregations

AuthResponse (org.edx.mobile.authentication.AuthResponse)5 HttpStatusException (org.edx.mobile.http.HttpStatusException)3 DialogInterface (android.content.DialogInterface)1 Bundle (android.os.Bundle)1 NonNull (android.support.annotation.NonNull)1 LoginService (org.edx.mobile.authentication.LoginService)1 LoginTask (org.edx.mobile.authentication.LoginTask)1 LoginErrorMessage (org.edx.mobile.exception.LoginErrorMessage)1 LoginException (org.edx.mobile.exception.LoginException)1 FormFieldMessageBody (org.edx.mobile.model.api.FormFieldMessageBody)1 RegisterResponseFieldError (org.edx.mobile.model.api.RegisterResponseFieldError)1 IRegistrationFieldView (org.edx.mobile.module.registration.view.IRegistrationFieldView)1 SocialFactory (org.edx.mobile.social.SocialFactory)1 RegisterTask (org.edx.mobile.task.RegisterTask)1