Search in sources :

Example 11 with AuthenticatorException

use of android.accounts.AuthenticatorException in project Resurrection_packages_apps_Settings by ResurrectionRemix.

the class ProtectedAccountView method asyncCheckPassword.

private void asyncCheckPassword() {
    final String login = mLogin.getText().toString();
    final String password = mPassword.getText().toString();
    Account account = findIntendedAccount(login);
    if (account == null) {
        postOnCheckPasswordResult(false);
        return;
    }
    getProgressDialog().show();
    Bundle options = new Bundle();
    options.putString(AccountManager.KEY_PASSWORD, password);
    AccountManager.get(mContext).confirmCredentialsAsUser(account, options, null, /* activity */
    new AccountManagerCallback<Bundle>() {

        public void run(AccountManagerFuture<Bundle> future) {
            try {
                final Bundle result = future.getResult();
                final boolean verified = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
                postOnCheckPasswordResult(verified);
            } catch (OperationCanceledException e) {
                postOnCheckPasswordResult(false);
            } catch (IOException e) {
                postOnCheckPasswordResult(false);
            } catch (AuthenticatorException e) {
                postOnCheckPasswordResult(false);
            } finally {
                mLogin.post(new Runnable() {

                    public void run() {
                        getProgressDialog().hide();
                    }
                });
            }
        }
    }, null, /* handler */
    new UserHandle(ActivityManager.getCurrentUser()));
}
Also used : Account(android.accounts.Account) Bundle(android.os.Bundle) OperationCanceledException(android.accounts.OperationCanceledException) UserHandle(android.os.UserHandle) AuthenticatorException(android.accounts.AuthenticatorException) IOException(java.io.IOException)

Example 12 with AuthenticatorException

use of android.accounts.AuthenticatorException in project apps-android-commons by commons-app.

the class ModificationsSyncAdapter method onPerformSync.

@Override
public void onPerformSync(Account account, Bundle bundle, String s, ContentProviderClient contentProviderClient, SyncResult syncResult) {
    // This code is fraught with possibilities of race conditions, but lalalalala I can't hear you!
    Cursor allModifications;
    try {
        allModifications = contentProviderClient.query(ModificationsContentProvider.BASE_URI, null, null, null, null);
    } catch (RemoteException e) {
        throw new RuntimeException(e);
    }
    // Exit early if nothing to do
    if (allModifications == null || allModifications.getCount() == 0) {
        Timber.d("No modifications to perform");
        return;
    }
    String authCookie;
    try {
        authCookie = AccountManager.get(getContext()).blockingGetAuthToken(account, "", false);
    } catch (OperationCanceledException | AuthenticatorException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Timber.d("Could not authenticate :(");
        return;
    }
    if (Utils.isNullOrWhiteSpace(authCookie)) {
        Timber.d("Could not authenticate :(");
        return;
    }
    MWApi api = CommonsApplication.getInstance().getMWApi();
    api.setAuthCookie(authCookie);
    String editToken;
    ApiResult requestResult, responseResult;
    try {
        editToken = api.getEditToken();
    } catch (IOException e) {
        Timber.d("Can not retreive edit token!");
        return;
    }
    allModifications.moveToFirst();
    Timber.d("Found %d modifications to execute", allModifications.getCount());
    ContentProviderClient contributionsClient = null;
    try {
        contributionsClient = getContext().getContentResolver().acquireContentProviderClient(ContributionsContentProvider.AUTHORITY);
        while (!allModifications.isAfterLast()) {
            ModifierSequence sequence = ModifierSequence.fromCursor(allModifications);
            sequence.setContentProviderClient(contentProviderClient);
            Contribution contrib;
            Cursor contributionCursor;
            try {
                contributionCursor = contributionsClient.query(sequence.getMediaUri(), null, null, null, null);
            } catch (RemoteException e) {
                throw new RuntimeException(e);
            }
            contributionCursor.moveToFirst();
            contrib = Contribution.fromCursor(contributionCursor);
            if (contrib.getState() == Contribution.STATE_COMPLETED) {
                try {
                    requestResult = api.action("query").param("prop", "revisions").param("rvprop", "timestamp|content").param("titles", contrib.getFilename()).get();
                } catch (IOException e) {
                    Timber.d("Network fuckup on modifications sync!");
                    continue;
                }
                Timber.d("Page content is %s", Utils.getStringFromDOM(requestResult.getDocument()));
                String pageContent = requestResult.getString("/api/query/pages/page/revisions/rev");
                String processedPageContent = sequence.executeModifications(contrib.getFilename(), pageContent);
                try {
                    responseResult = api.action("edit").param("title", contrib.getFilename()).param("token", editToken).param("text", processedPageContent).param("summary", sequence.getEditSummary()).post();
                } catch (IOException e) {
                    Timber.d("Network fuckup on modifications sync!");
                    continue;
                }
                Timber.d("Response is %s", Utils.getStringFromDOM(responseResult.getDocument()));
                String result = responseResult.getString("/api/edit/@result");
                if (!result.equals("Success")) {
                    // FIXME: Log this somewhere else
                    Timber.d("Non success result! %s", result);
                } else {
                    sequence.delete();
                }
            }
            allModifications.moveToNext();
        }
    } finally {
        if (contributionsClient != null) {
            contributionsClient.release();
        }
    }
}
Also used : OperationCanceledException(android.accounts.OperationCanceledException) AuthenticatorException(android.accounts.AuthenticatorException) IOException(java.io.IOException) Cursor(android.database.Cursor) ApiResult(org.mediawiki.api.ApiResult) MWApi(fr.free.nrw.commons.MWApi) RemoteException(android.os.RemoteException) ContentProviderClient(android.content.ContentProviderClient) Contribution(fr.free.nrw.commons.contributions.Contribution)

Example 13 with AuthenticatorException

use of android.accounts.AuthenticatorException in project httpclient by pixmob.

the class AbstractAccountAuthenticator method generateAuthToken.

/**
 * Generate an authentication token. The user must grant credential access
 * when an application is using it for the first time. In this case,
 * {@link UserInteractionRequiredException} is thrown, the
 * {@link UserInteractionRequiredException#getUserIntent()} must be used
 * with <code>startActivityForResult</code> to start a system activity, in
 * order to get access to user credential. The user is free to deny
 * credential access. If credential access is granted, the next call to this
 * method should not throw any error.
 * @see UserInteractionRequiredException#getUserIntent()
 * @throws UserInteractionRequiredException
 *             if user interaction is required in order to perform
 *             authentication
 * @throws HttpClientException
 *             if authentication failed (network error, bad credentials,
 *             etc...)
 */
protected final String generateAuthToken(String authTokenType) throws HttpClientException {
    // Get an authentication token from the AccountManager:
    // this call is asynchronous, as the user may not respond immediately.
    final AccountManager am = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
    final AccountManagerFuture<Bundle> authResultFuture;
    // Ice Cream Sandwich.
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        authResultFuture = GetTokenLegacy.INSTANCE.get(am, account, authTokenType);
    } else {
        authResultFuture = GetTokenICS.INSTANCE.get(am, account, authTokenType);
    }
    final Bundle authResult;
    try {
        authResult = authResultFuture.getResult();
    } catch (OperationCanceledException e) {
        throw new HttpClientException("Authentication failed: canceled by user", e);
    } catch (AuthenticatorException e) {
        throw new HttpClientException("Authentication failed", e);
    } catch (IOException e) {
        throw new HttpClientException("Authentication failed: network error", e);
    }
    if (authResult == null) {
        throw new HttpClientException("Authentication failed");
    }
    final String authToken = authResult.getString(AccountManager.KEY_AUTHTOKEN);
    if (authToken == null) {
        // No authentication token found:
        // the user must allow this application to use his account.
        final Intent authPermIntent = (Intent) authResult.get(AccountManager.KEY_INTENT);
        int flags = authPermIntent.getFlags();
        flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
        authPermIntent.setFlags(flags);
        // The request is aborted: the application should retry later.
        throw new UserInteractionRequiredException(authPermIntent);
    }
    return authToken;
}
Also used : Bundle(android.os.Bundle) OperationCanceledException(android.accounts.OperationCanceledException) AuthenticatorException(android.accounts.AuthenticatorException) AccountManager(android.accounts.AccountManager) Intent(android.content.Intent) IOException(java.io.IOException)

Aggregations

AuthenticatorException (android.accounts.AuthenticatorException)13 OperationCanceledException (android.accounts.OperationCanceledException)10 IOException (java.io.IOException)10 Bundle (android.os.Bundle)8 Account (android.accounts.Account)6 AccountManager (android.accounts.AccountManager)4 Intent (android.content.Intent)3 Test (org.junit.Test)3 UserHandle (android.os.UserHandle)2 GoogleHeaders (com.google.api.client.googleapis.GoogleHeaders)2 HttpRequest (com.google.api.client.http.HttpRequest)2 AtomParser (com.google.api.client.xml.atom.AtomParser)2 PendingIntent (android.app.PendingIntent)1 ContentProviderClient (android.content.ContentProviderClient)1 Cursor (android.database.Cursor)1 RemoteException (android.os.RemoteException)1 NotificationCompat (android.support.v4.app.NotificationCompat)1 NotificationManagerCompat (android.support.v4.app.NotificationManagerCompat)1 ListView (android.widget.ListView)1 JsonNode (com.fasterxml.jackson.databind.JsonNode)1