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:org.cloudfoundry.android.cfdroid.CloudFoundry.java

/**
 * Makes sure that we have a reference to a non-null
 * {@link CloudFoundryClient} object./*from  w  ww .  j a v a2  s .  c  o m*/
 * 
 */
private void ensureClient() {
    if (cache.client != null) {
        return;
    }
    try {
        AccountManagerFuture<Bundle> future = accountManager.getAuthTokenByFeatures(Accounts.ACCOUNT_TYPE,
                Accounts.ACCOUNT_TYPE, new String[0], activity, null, null, null, null);
        Bundle bundle = future.getResult();
        String targetURL = Accounts.extractTarget(bundle.getString(AccountManager.KEY_ACCOUNT_NAME));
        cache.token = bundle.getString(AccountManager.KEY_AUTHTOKEN);

        cache.client = new CloudFoundryClient(cache.token, targetURL);
    } catch (Exception e) {
        Ln.e(e, "Logged from here");
    }
}

From source file:be.evias.cloudLogin.cloudLoginMainActivity.java

private void logoutAccount(final Account account) {
    final AccountManagerFuture<Bundle> future = mAccountManager.getAuthToken(account,
            AccountBase.AUTHTOKEN_TYPE_FULL_ACCESS, null, this, null, null);

    new Thread(new Runnable() {
        @Override//from   ww w  . ja  va  2s .co m
        public void run() {
            try {
                Bundle bnd = future.getResult();

                final String authtoken = bnd.getString(AccountManager.KEY_AUTHTOKEN);
                mAccountManager.invalidateAuthToken(account.type, authtoken);

                processLogoutServerSide(account);
            } catch (Exception e) {
                e.printStackTrace();
                showMessage(e.getMessage(), Toast.LENGTH_LONG);
            }
        }
    }).start();
}

From source file:com.android.browser.GoogleAccountLogin.java

@Override
public void run(AccountManagerFuture<Bundle> value) {
    try {/*from  ww w .j  ava 2 s . co  m*/
        String id = value.getResult().getString(AccountManager.KEY_AUTHTOKEN);
        switch (mState) {
        default:
        case 0:
            throw new IllegalStateException("Impossible to get into this state");
        case 1:
            mSid = id;
            mState = 2; // LSID
            AccountManager.get(mActivity).getAuthToken(mAccount, "LSID", null, mActivity, this, null);
            break;
        case 2:
            mLsid = id;
            new Thread(this).start();
            break;
        }
    } catch (Exception e) {
        Log.d(LOGTAG, "LOGIN_FAIL: Exception in state " + mState + " " + e);
        // For all exceptions load the original signin page.
        // TODO: toast login failed?
        done();
    }
}

From source file:org.voidsink.anewjkuapp.activity.KusssAuthenticatorActivity.java

private void submit() {
    mSubmit.setEnabled(false);/*from www.  ja va2s .com*/

    final String userName = ((TextView) findViewById(R.id.accountName)).getText().toString();
    final String userPass = ((TextView) findViewById(R.id.accountPassword)).getText().toString();

    final String accountType = getIntent().getStringExtra(KusssAuthenticator.ARG_ACCOUNT_TYPE);

    new AsyncTask<String, Void, Intent>() {
        private ProgressDialog progressDialog;
        private Context mContext;

        @Override
        protected void onPreExecute() {
            mContext = KusssAuthenticatorActivity.this;

            progressDialog = ProgressDialog.show(KusssAuthenticatorActivity.this,
                    mContext.getString(R.string.progress_title), mContext.getString(R.string.progress_login),
                    true);
        }

        @Override
        protected Intent doInBackground(String... params) {
            Bundle data = new Bundle();
            try {
                final String authtoken = KusssHandler.getInstance().login(KusssAuthenticatorActivity.this,
                        userName, userPass);

                KusssHandler.getInstance().logout(KusssAuthenticatorActivity.this);

                data.putString(AccountManager.KEY_ACCOUNT_NAME, userName);
                data.putString(AccountManager.KEY_ACCOUNT_TYPE, accountType);
                data.putString(AccountManager.KEY_AUTHTOKEN, authtoken);
                data.putString(PARAM_USER_PASS, userPass);

            } catch (Exception e) {
                data.putString(KEY_ERROR_MESSAGE, e.getMessage());
            }

            final Intent res = new Intent();
            res.putExtras(data);
            return res;
        }

        @Override
        protected void onPostExecute(Intent intent) {
            if (intent.hasExtra(KEY_ERROR_MESSAGE)) {
                Toast.makeText(getBaseContext(), intent.getStringExtra(KEY_ERROR_MESSAGE), Toast.LENGTH_SHORT)
                        .show();
            } else if (intent.hasExtra(AccountManager.KEY_AUTHTOKEN)) {
                String authToken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
                if ((authToken != null) && !TextUtils.isEmpty(authToken)) {
                    finishLogin(intent);
                } else {
                    Toast.makeText(getBaseContext(),
                            mContext.getString(R.string.account_login_failed_wrong_pwd), Toast.LENGTH_SHORT)
                            .show();
                }
            } else {
                Toast.makeText(getBaseContext(),
                        mContext.getString(R.string.account_login_failed_wrong_auth_token), Toast.LENGTH_SHORT)
                        .show();
            }

            progressDialog.dismiss();

            mSubmit.setEnabled(true);

            mContext = null;
        }
    }.execute();
}

From source file:cl.chileagil.agileday2012.fragment.MainFragment.java

void gotAccount() {
    Account account = accountManager.getAccountByName(accountName);
    if (account == null) {
        chooseAccount();// ww  w  .j  av  a 2  s.com
        return;
    }
    if (authToken != null) {
        //Ya tengo elegido mi cuenta.
        //Solo si no tengo datos en la DB, lo pido, sino cargo lo que hay
        //y actualizo solo a peticion del usuario
        DatabaseAdapter dbAdapter = null;
        try {
            dbAdapter = new DatabaseAdapter(this);
            dbAdapter.open();
            if (dbAdapter.fetchCountEvents() <= 0) {
                onAuthToken();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbAdapter.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return;
    }
    accountManager.getAccountManager().getAuthToken(account, AUTH_TOKEN_TYPE, true,
            new AccountManagerCallback<Bundle>() {

                public void run(AccountManagerFuture<Bundle> future) {
                    try {
                        Bundle bundle = future.getResult();
                        if (bundle.containsKey(AccountManager.KEY_INTENT)) {
                            Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
                            intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivityForResult(intent, REQUEST_AUTHENTICATE);
                        } else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
                            setAuthToken(bundle.getString(AccountManager.KEY_AUTHTOKEN));
                            onAuthToken();
                        }
                    } catch (Exception e) {
                        Log.e(TAG, e.getMessage(), e);
                    }
                }
            }, null);
}

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

@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType,
        Bundle loginOptions) throws NetworkErrorException {

    // Extract the email and refresh_token from the Account Manager, and ask
    // the server for a new refresh_token.
    String authToken = am.peekAuthToken(account, authTokenType);

    // Lets give another try to authenticate the user
    AccessToken token = null;//from w w  w.j  a v a2s. c  om
    UserRecoverableAuthException userRecoverableAuthException = null;

    if (TextUtils.isEmpty(authToken)) {
        final String refreshToken = am.getPassword(account);
        Log.i(TAG, "Auth token is null");
        if (refreshToken != null) {
            Log.i(TAG, "Refresh Token");
            try {
                // If the account credentials have not gone to the server yet we saved the
                // password for the user
                if (Boolean.parseBoolean(am.getUserData(account, USE_PASSWORD))) {
                    token = ohmageService.getAccessToken(account.name, refreshToken);
                    if (token != null) {
                        am.setUserData(account, Authenticator.USE_PASSWORD, String.valueOf(false));
                        am.setUserData(account, Authenticator.USER_ID, token.getUserId());
                    }
                } else {
                    // refresh token
                    if (Ohmage.USE_DSU_DATAPOINTS_API) {

                        Log.i(TAG, "Refresh Token with DSU");
                        token = ohmageService.refreshAccessToken(refreshToken, "refresh_token");
                    } else {
                        token = ohmageService.getAccessToken(refreshToken);
                    }
                }
            } catch (AuthenticationException e) {
                // This will happen if the refresh token was already used, or it was
                // invalidated or something

                // We can try getting the token from google
                String googleAccount = am.getUserData(account, USER_DATA_GOOGLE_ACCOUNT);
                if (googleAccount != null) {
                    try {
                        token = getTokenFromGoogle(googleAccount);
                        Log.i(TAG, token.toString());
                    } catch (UserRecoverableAuthException e1) {
                        userRecoverableAuthException = e1;
                    }
                }
            } catch (RetrofitError e) {
                if (e.getResponse() != null && e.getResponse().getStatus() == 409) {
                    // The user hasn't activated their account by clicking the link
                    final Bundle bundle = new Bundle();
                    bundle.putString(AccountManager.KEY_AUTH_FAILED_MESSAGE,
                            Ohmage.app().getString(R.string.account_not_activated));
                    bundle.putParcelable(AccountManager.KEY_INTENT,
                            new Intent(mContext, AccountNotActivatedDialog.class));
                    return bundle;
                } else {
                    throw new NetworkErrorException();
                }
            } catch (Exception e) {
                Log.e(TAG, "", e);
            }
        }
    }

    // If we get an authToken - we return it
    if (token != null) {
        am.setPassword(account, token.getRefreshToken());
        authToken = token.getAccessToken();
    }

    if (!TextUtils.isEmpty(authToken)) {
        final Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
        result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
        result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
        return result;
    }

    // If we get here, then we couldn't access the user's password - so we
    // need to re-prompt them for their credentials. We do that by creating
    // an intent to display our AuthenticatorActivity.
    final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
    intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
    intent.putExtra(AuthenticatorActivity.EXTRA_FROM_AUTHENTICATOR, true);
    intent.putExtra(AuthenticatorActivity.EXTRA_HANDLE_USER_RECOVERABLE_ERROR, userRecoverableAuthException);
    final Bundle bundle = new Bundle();
    bundle.putParcelable(AccountManager.KEY_INTENT, intent);
    return bundle;
}

From source file:com.pindroid.authenticator.AuthenticatorActivity.java

/**
 * //from  w  w  w.  j a  v a 2s  .  c o m
 * 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.
 * 
 * @param the confirmCredentials result.
 */
protected void finishLogin(String authToken) {
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    final int synctime = Integer.parseInt(settings.getString("pref_synctime", "0"));

    final Account account = new Account(mUsername, Constants.ACCOUNT_TYPE);

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

        ContentResolver.setSyncAutomatically(account, BookmarkContentProvider.AUTHORITY, true);
        if (synctime != 0) {
            SyncUtils.addPeriodicSync(BookmarkContentProvider.AUTHORITY, Bundle.EMPTY, synctime, this);
        }
    }

    mAccountManager.setAuthToken(account, Constants.AUTHTOKEN_TYPE, authToken);

    final Intent intent = new Intent();

    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
    intent.putExtra(AccountManager.KEY_AUTHTOKEN, authToken);
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    finish();
}

From source file:org.pixmob.appengine.client.AppEngineClient.java

private String getAuthToken() throws AppEngineAuthenticationException {
    // get an authentication token from the AccountManager:
    // this call is asynchronous, as the user may not respond immediately
    final AccountManagerFuture<Bundle> futureBundle = accountManager.getAuthToken(account, "ah", true, null,
            null);/*from w  ww .j a  v a  2s. c  o  m*/
    final Bundle authBundle;
    try {
        authBundle = futureBundle.getResult();
    } catch (OperationCanceledException e) {
        throw new AppEngineAuthenticationException(AUTHENTICATION_UNAVAILABLE, e);
    } catch (AuthenticatorException e) {
        throw new AppEngineAuthenticationException(AUTHENTICATION_UNAVAILABLE, e);
    } catch (IOException e) {
        throw new AppEngineAuthenticationException(AUTHENTICATION_UNAVAILABLE, e);
    }

    final String authToken = authBundle.getString(AccountManager.KEY_AUTHTOKEN);
    if (authToken == null) {
        // no authentication token was given: the user should give its
        // permission through an item in the notification bar
        Log.i(TAG, "Authentication permission is required");

        final Intent authPermIntent = (Intent) authBundle.get(AccountManager.KEY_INTENT);
        int flags = authPermIntent.getFlags();
        flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
        authPermIntent.setFlags(flags);

        throw new AppEngineAuthenticationException(AUTHENTICATION_PENDING, authPermIntent);
    }

    return authToken;
}

From source file:com.google.wireless.speed.speedometer.AccountSelector.java

private void getAuthToken(AccountManagerFuture<Bundle> result) {
    Log.i(SpeedometerApp.TAG, "getAuthToken() called, result " + result);
    String errMsg = "Failed to get login cookie. ";
    Bundle bundle;/*from   w  w w .j a  v a  2s . c o m*/
    try {
        bundle = result.getResult();
        Intent intent = (Intent) bundle.get(AccountManager.KEY_INTENT);
        if (intent != null) {
            // User input required. (A UI will pop up for user's consent to allow
            // this app access account information.)
            Log.i(SpeedometerApp.TAG, "Starting account manager activity");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } else {
            Log.i(SpeedometerApp.TAG, "Executing getCookie task");
            synchronized (this) {
                this.authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                this.checkinFuture = checkinExecutor.submit(new GetCookieTask());
            }
        }
    } catch (OperationCanceledException e) {
        Log.e(SpeedometerApp.TAG, errMsg, e);
        throw new RuntimeException("Can't get login cookie", e);
    } catch (AuthenticatorException e) {
        Log.e(SpeedometerApp.TAG, errMsg, e);
        throw new RuntimeException("Can't get login cookie", e);
    } catch (IOException e) {
        Log.e(SpeedometerApp.TAG, errMsg, e);
        throw new RuntimeException("Can't get login cookie", e);
    }
}

From source file:com.newtifry.android.remote.BackendClient.java

private String getAuthToken(Context context, Account account) throws PendingAuthException {
    String authToken = null;// w  ww . j  a va  2  s.  c o m
    AccountManager accountManager = AccountManager.get(context);
    try {
        AccountManagerFuture<Bundle> future = accountManager.getAuthToken(account, "ah", false, null, null);
        Bundle bundle = future.getResult();
        authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
        // User will be asked for "App Engine" permission.
        if (authToken == null) {
            // No authorization token - will need to ask permission from user.
            Intent intent = (Intent) bundle.get(AccountManager.KEY_INTENT);
            if (intent != null) {
                // User input required
                context.startActivity(intent);
                throw new PendingAuthException("Asking user for permission.");
            }
        }
    } catch (OperationCanceledException e) {
        Log.d(TAG, e.getMessage());
    } catch (AuthenticatorException e) {
        Log.d(TAG, e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, e.getMessage());
    }

    return authToken;
}