Example usage for android.accounts AccountManager KEY_AUTHTOKEN

List of usage examples for android.accounts AccountManager KEY_AUTHTOKEN

Introduction

In this page you can find the example usage for android.accounts AccountManager KEY_AUTHTOKEN.

Prototype

String KEY_AUTHTOKEN

To view the source code for android.accounts AccountManager KEY_AUTHTOKEN.

Click Source Link

Document

Bundle key used for the auth token value in results from #getAuthToken and friends.

Usage

From source file:com.sharpcart.android.wizardpager.SharpCartLoginActivity.java

private void createAccount(final String mUsername, final String mPassword) {
    final Account account = new Account(mUsername, PARAM_ACCOUNT_TYPE);

    if (mRequestNewAccount) {
        mAccountManager.addAccountExplicitly(account, mPassword, null);

        /*//  ww  w. j ava 2 s .c  o  m
         * Turn on periodic syncing. I need to add randomness to the sync interval to make sure 
         * that not all users sync at the same time, which will overload the server.
         */

        final Bundle extras = new Bundle();
        final long random = (long) (Math.random() * 1000L);

        ContentResolver.addPeriodicSync(account, SharpCartContentProvider.AUTHORITY, extras,
                (8 * SYNC_INTERVAL) + random);

        //Will run the syncadapter everytime we get a network tinkle
        //ContentResolver.setSyncAutomatically(account,SharpCartContentProvider.AUTHORITY, true);

        //initiate a sync
        SharpCartUtilities.getInstance().syncFromServer(account);

    } else {
        mAccountManager.setPassword(account, mPassword);
    }

    final Intent intent = new Intent();
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, PARAM_ACCOUNT_TYPE);

    if (mAuthTokenType != null && mAuthTokenType.equals(PARAM_AUTHTOKEN_TYPE)) {
        intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthToken);
    }

    setResult(RESULT_OK, intent);

    finish();
}

From source file:org.ohmage.authenticator.AuthenticatorActivity.java

/**
 * Called when response is received from the server for authentication
 * request. See onAuthenticationResult(). Sets the
 * AccountAuthenticatorResult which is sent back to the caller. Also sets
 * the authToken in AccountManager for this account.
 * //from  w w  w .ja  va  2 s .c  o m
 * @param the confirmCredentials result.
 */

protected void createAccount() {
    Log.v(TAG, "finishLogin()");
    final Account account = new Account(mUsername, OhmageApplication.ACCOUNT_TYPE);
    Bundle userData = new Bundle();
    userData.putString(KEY_OHMAGE_SERVER, ConfigHelper.serverUrl());
    mAuthtoken = mHashedPassword;

    if (TextUtils.isEmpty(mAuthtoken)) {
        Log.w(TAG, "Trying to create account with empty password");
        return;
    }

    if (mRequestNewAccount) {
        mAccountManager.addAccountExplicitly(account, mPassword, userData);
        mAccountManager.setAuthToken(account, OhmageApplication.AUTHTOKEN_TYPE, mAuthtoken);
        // Set sync for this account.
        ContentResolver.setIsSyncable(account, DbContract.CONTENT_AUTHORITY, 1);
        ContentResolver.setSyncAutomatically(account, DbContract.CONTENT_AUTHORITY, true);
        ContentResolver.addPeriodicSync(account, DbContract.CONTENT_AUTHORITY, new Bundle(), 3600);
    } else {
        mAccountManager.setPassword(account, mPassword);
    }
    final Intent intent = new Intent();
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, OhmageApplication.ACCOUNT_TYPE);
    if (mAuthtokenType != null && mAuthtokenType.equals(OhmageApplication.AUTHTOKEN_TYPE)) {
        intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthtoken);
    }
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);

    mPreferencesHelper.edit().putLoginTimestamp(System.currentTimeMillis()).commit();

    if (UserPreferencesHelper.isSingleCampaignMode()) {
        // Download the single campaign
        showDialog(DIALOG_DOWNLOADING_CAMPAIGNS);
        getSupportLoaderManager().restartLoader(0, null, this);
    } else {
        finishLogin();
    }
}

From source file:io.tehtotalpwnage.musicphp_android.NavigationActivity.java

private void getListing(Item item, int id, final VolleyCallback callback) {
    String sAddress = getSharedPreferences("Prefs", 0).getString("server", null);
    StringRequest req = new StringRequest(Request.Method.GET,
            sAddress + "/api/" + item + "/" + (id == 0 ? "" : id), new Response.Listener<String>() {
                @Override//ww  w  . j ava  2 s  .  c  o m
                public void onResponse(String response) {
                    Log.d("Music.php-Android", "Server response: " + response);
                    try {
                        JSONArray array = new JSONArray(response);
                        Log.d("Music.php-Android",
                                "JSON contains " + String.valueOf(array.length()) + " objects");
                        callback.onSuccess(array);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.v(TAG, "failure");
                }
            }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("Accept", "application/json");
            params.put("Authorization", "Bearer " + getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN));
            return params;
        }
    };
    VolleySingleton.getInstance(this).addToRequestQueue(req);
}

From source file:org.voidsink.anewjkuapp.utils.AppUtils.java

public static String getAccountAuthToken(Context context, Account account) {
    if (account == null) {
        return null;
    }//from   www. j  a  va  2  s  .  c  om

    AccountManager am = AccountManager.get(context);
    AccountManagerFuture<Bundle> response = am.getAuthToken(account,
            KusssAuthenticator.AUTHTOKEN_TYPE_READ_ONLY, null, true, null, null);

    if (response == null)
        return null;

    try {
        return response.getResult().getString(AccountManager.KEY_AUTHTOKEN);
    } catch (OperationCanceledException | AuthenticatorException | IOException e) {
        Log.e(TAG, "getAccountAuthToken", e);
        return null;
    }
}

From source file:com.jdom.get.stuff.done.android.AndroidSyncStrategy.java

private String getToken() {
    long start = System.currentTimeMillis();
    SharedPreferences prefs = activity.getSharedPreferences(Constants.AUTH_TOKEN_TYPE, Activity.MODE_PRIVATE);
    String token = prefs.getString(Constants.AUTH_TOKEN_TYPE, null);
    long lastTokenRetrievalTime = prefs.getLong(Constants.TOKEN_RETRIEVAL_TIME, 0);

    long timeSinceRetrievedLastToken = System.currentTimeMillis() - lastTokenRetrievalTime;
    long timeStillValid = Constants.TOKEN_VALID_DURATION - timeSinceRetrievedLastToken;
    if (token == null || timeStillValid < 1) {
        long portionStart = System.currentTimeMillis();
        Log.d(CLASS_NAME, "Token is no longer valid.");
        GoogleAccountManager accountManager = new GoogleAccountManager(activity);
        Account account = getAccount();//  www .  ja va  2  s  .  c om

        accountManager.manager.invalidateAuthToken(account.type, token);
        AccountManagerFuture<Bundle> future = accountManager.manager.getAuthToken(account,
                Constants.AUTH_TOKEN_TYPE, null, activity, null, null);
        try {
            Bundle result = future.getResult();
            token = result.getString(AccountManager.KEY_AUTHTOKEN);

            Editor editor = prefs.edit();
            editor.putString(Constants.AUTH_TOKEN_TYPE, token);
            editor.putLong(Constants.TOKEN_RETRIEVAL_TIME, System.currentTimeMillis());
            editor.commit();

        } catch (Exception e) {
            handleException(e);
        }
        AndroidSyncStrategy.logTimeTaken("Retrieving new token", portionStart);
    } else {
        Log.d(CLASS_NAME, "Token is still valid for [" + timeStillValid + "] ms.");
    }

    AndroidSyncStrategy.logTimeTaken("Retrieving token", start);
    return token;
}

From source file:org.ohmage.auth.AuthenticatorActivity.java

private void finishAccountAdd(String accountName, String authToken, String password) {
    final Intent intent = new Intent();
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, accountName);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AuthUtil.ACCOUNT_TYPE);
    if (authToken != null)
        intent.putExtra(AccountManager.KEY_AUTHTOKEN, authToken);
    intent.putExtra(AccountManager.KEY_PASSWORD, password);
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);//from  www.  ja v  a2  s. co m
    finish();

    if (!calledByAuthenticator())
        startActivity(new Intent(getBaseContext(), MainActivity.class));
}

From source file:com.mikecorrigan.bohrium.pubsub.RegistrationClient.java

@SafeVarargs
private final void handleAuthToken(AccountManagerFuture<Bundle>... tokens) {
    Log.v(TAG, "handleAuthToken");

    try {/*from w  w w  . jav  a  2  s . c o m*/
        Bundle result = tokens[0].getResult();

        Intent intent = (Intent) result.get(AccountManager.KEY_INTENT);
        if (intent != null) {
            Log.i(TAG, "Launch activity before getting authToken: intent=" + intent);

            setStateAndNotify(REGISTRATION_STATE_REGISTERING, REGISTRATION_SUBSTATE_PROMPTING_USER);

            intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
            notifyLaunchIntent(intent);
            return;
        }

        String authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
        if (mNeedInvalidate) {
            mNeedInvalidate = false;

            Log.i(TAG, "Invalidating token and starting over.");

            // Invalidate auth token.
            AccountManager mgr = AccountManager.get(this);
            mgr.invalidateAuthToken(mConfiguration.getString(ACCOUNT_TYPE, DEFAULT_ACCOUNT_TYPE), authToken);

            setStateAndNotify(REGISTRATION_STATE_REGISTERING, REGISTRATION_SUBSTATE_INVALIDATED_AUTH_TOKEN);

            // Initiate the request again.
            requestAuthToken();
            return;
        } else {
            Log.i(TAG, "Received authToken=" + authToken);
            mConfiguration.putString(AUTH_TOKEN, authToken);
            setStateAndNotify(REGISTRATION_STATE_REGISTERING, REGISTRATION_SUBSTATE_HAVE_AUTH_TOKEN);

            // Move on to the next step, request auth cookie.
            requestAuthCookie();
            return;
        }
    } catch (Exception e) {
        Log.e(TAG, "Exception " + e);
        Log.e(TAG, Log.getStackTraceString(e));
    }

    setStateAndNotify(REGISTRATION_STATE_ERROR, REGISTRATION_SUBSTATE_ERROR_AUTH_TOKEN);
}

From source file:mobisocial.musubi.ui.fragments.AccountLinkDialog.java

private static String blockForCachedGoogleToken(Context context, Account account, AccountManager accountManager)
        throws IOException {
    AccountManagerFuture<Bundle> future = accountManager.getAuthToken(account, GOOGLE_OAUTH_SCOPE, true, null,
            null);/*www .  ja va  2  s .c om*/
    if (future != null) {
        try {
            Bundle result = future.getResult();
            if (result.containsKey(AccountManager.KEY_AUTHTOKEN)) {
                String cachedGoogleToken = result.getString(AccountManager.KEY_AUTHTOKEN);
                return cachedGoogleToken;
            }
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
        }
    }
    return null;
}

From source file:com.microsoft.windowsazure.mobileservices.MobileServiceClient.java

/**
 * Invokes Microsoft Azure Mobile Service authentication using a the Google
 * account registered in the device//from  ww w.java 2  s  .  c om
 *
 * @param activity The activity that triggered the authentication
 * @param account  The account used for the login operation
 * @param scopes   The scopes used as authentication token type for login
 */
public ListenableFuture<MobileServiceUser> loginWithGoogleAccount(Activity activity, Account account,
        String scopes) {
    final SettableFuture<MobileServiceUser> future = SettableFuture.create();

    try {
        if (account == null) {
            throw new IllegalArgumentException("account");
        }

        final MobileServiceClient client = this;

        AccountManagerCallback<Bundle> authCallback = new AccountManagerCallback<Bundle>() {

            @Override
            public void run(AccountManagerFuture<Bundle> futureBundle) {
                try {
                    if (futureBundle.isCancelled()) {
                        future.setException(new MobileServiceException("User cancelled"));
                        // callback.onCompleted(null, new
                        // MobileServiceException("User cancelled"), null);
                    } else {
                        Bundle bundle = futureBundle.getResult();

                        String token = (String) (bundle.get(AccountManager.KEY_AUTHTOKEN));

                        JsonObject json = new JsonObject();
                        json.addProperty("access_token", token);

                        ListenableFuture<MobileServiceUser> loginFuture = client
                                .login(MobileServiceAuthenticationProvider.Google, json);

                        Futures.addCallback(loginFuture, new FutureCallback<MobileServiceUser>() {
                            @Override
                            public void onFailure(Throwable e) {
                                future.setException(e);
                            }

                            @Override
                            public void onSuccess(MobileServiceUser user) {
                                future.set(user);
                            }
                        });
                    }
                } catch (Exception e) {
                    future.setException(e);
                }
            }
        };

        AccountManager acMgr = AccountManager.get(activity.getApplicationContext());
        acMgr.getAuthToken(account, scopes, null, activity, authCallback, null);

    } catch (Exception e) {
        future.setException(e);
    }

    return future;
}

From source file:com.ntsync.android.sync.client.NetworkUtilities.java

/**
 * //  w ww  .java  2 s .c o m
 * @param acm
 * @param account
 * 
 * 
 * @param Activity
 *            if null show a notification when Login is needed otherwise
 *            show the Login-Activity in the context of the provided
 *            Activity. *
 * @return SessionId
 * @throws OperationCanceledException
 * @throws ServerException
 * @throws NetworkErrorException
 */
@SuppressWarnings("deprecation")
public static String blockingGetAuthToken(AccountManager acm, Account account, Activity activity)
        throws OperationCanceledException, ServerException, NetworkErrorException {
    String authToken = null;
    try {
        Bundle result;
        if (activity == null) {
            // New is available from API 14 -> use deprecated API
            result = acm.getAuthToken(account, Constants.AUTHTOKEN_TYPE, true, null, null).getResult();
        } else {
            result = acm.getAuthToken(account, Constants.AUTHTOKEN_TYPE, null, activity, null, null)
                    .getResult();
        }
        if (result != null) {
            if (result.containsKey(AccountManager.KEY_AUTHTOKEN)) {
                authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
            }
            if (result.containsKey(AccountManager.KEY_ERROR_CODE)) {
                int errorCode = result.getInt(AccountManager.KEY_ERROR_CODE, -1);
                String msg = result.getString(AccountManager.KEY_ERROR_MESSAGE);
                if (errorCode == Constants.AUTH_ERRORCODE_SERVEREXCEPTION) {
                    throw new ServerException(msg);
                } else {
                    LogHelper.logE(TAG,
                            "Authentification failed with unknown errorCode:" + errorCode + " Message:" + msg,
                            null);
                }
            }
        }
    } catch (AuthenticatorException e) {
        LogHelper.logE(TAG, "Authentification failed.", e);
        // Should not happen -> report error
        ErrorHandler.reportException(e);
    } catch (IOException ex) {
        throw new NetworkErrorException(ex);
    }
    return authToken;
}