Example usage for android.accounts AccountManager peekAuthToken

List of usage examples for android.accounts AccountManager peekAuthToken

Introduction

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

Prototype

public String peekAuthToken(final Account account, final String authTokenType) 

Source Link

Document

Gets an auth token from the AccountManager's cache.

Usage

From source file:Main.java

public static String getSessionKey(AccountManager paramAccountManager, Account paramAccount) {
    return paramAccountManager.peekAuthToken(paramAccount, "co.vine.android.basic_auth.token.secret");
}

From source file:Main.java

/**
 * Check if exist auth token for specified account
 * @param context context/*from w  w w.j  a  v  a  2s .  com*/
 * @param account account to check
 * @param authTokenType auth token type
 * @return <code>true</code> if authToken for this account exist
 */
public static boolean isAccountEnabled(Context context, Account account, String authTokenType) {
    if (account == null)
        return false;
    final AccountManager accountManager = AccountManager.get(context);
    String authToken = accountManager.peekAuthToken(account, authTokenType);
    if (TextUtils.isEmpty(authToken)) {
        return false;
    } else {
        return true;
    }
}

From source file:Main.java

/**
 * Invalidate auth token for specified account
 * @param account account to invalidate auth token
 * @param authTokenType auth token type//w  w w . j a va  2s .  c o  m
 * @param requiredFeatures requiredFeatures, could be <code>null</code>
 * @param options options, could be <code>null</code>
 * @param activity activity (cannot be <code>null</code>)
 */
public static void invalidateAuthToken(Account account, String authTokenType, String[] requiredFeatures,
        Bundle options, Activity activity) {
    if (activity == null) {
        throw new IllegalArgumentException("activity cannot be null");
    }
    if (account == null) {
        throw new IllegalArgumentException("account cannot be null");
    }
    Context context = activity.getApplicationContext();
    final AccountManager am = AccountManager.get(context);
    String authToken = am.peekAuthToken(account, authTokenType);
    if (!TextUtils.isEmpty(authToken)) {
        am.invalidateAuthToken(account.type, authToken);
    }
    am.addAccount(account.type, authTokenType, requiredFeatures, options, activity, null, null);
}

From source file:cc.vileda.sipgatesync.contacts.SipgateContactSyncAdapter.java

@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {//ww w  . j a  v a 2s . c  o m
    Log.d("SipgateContactSyncAdapt", "onPerformSync()");
    AccountManager accountManager = AccountManager.get(getContext());
    final String oauth = accountManager.peekAuthToken(account, "oauth");
    Log.d("SipgateContactSyncAdapt", oauth == null ? "NO oauth!" : "Got token");
    final JSONArray users = SipgateApi.getContacts(oauth);
    assert users != null;

    Log.d("SipgateContactSyncAdapt", String.format("fetched %d contacts", users.length()));

    Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon()
            .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, account.name)
            .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, account.type).build();
    Cursor c1 = mContentResolver.query(rawContactUri, null, null, null, null);
    Map<String, Boolean> localContacts = new HashMap<>();
    while (c1 != null && c1.moveToNext()) {
        localContacts.put(c1.getString(c1.getColumnIndex(ContactsContract.RawContacts.SOURCE_ID)), false);
    }

    for (int i = 0; i < users.length(); i++) {
        try {
            final JSONObject user = users.getJSONObject(i);
            final String id = user.getString("uuid");
            if (localContacts.containsKey(id)) {
                localContacts.put(id, true);
                continue;
            }
            final String firstname = user.getString("firstname");

            final JSONArray emails = user.getJSONArray("emails");
            final JSONArray mobile = user.getJSONArray("mobile");
            final JSONArray landline = user.getJSONArray("landline");
            final JSONArray fax = user.getJSONArray("fax");

            Log.d("SipgateContactSyncAdapt", String.format("adding id: %s %s", id, firstname));

            ContactManager.addContact(id, firstname, user.getString("lastname"), jsonArrayToList(emails),
                    jsonArrayToList(mobile), jsonArrayToList(landline), jsonArrayToList(fax), mContentResolver,
                    account.name);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    for (Map.Entry<String, Boolean> contact : localContacts.entrySet()) {
        if (!contact.getValue()) {
            ContactManager.deleteContact(contact.getKey(), mContentResolver, account.name);
        }
    }
}

From source file:org.ohmage.app.OhmageErrorHandler.java

@Override
public Throwable handleError(RetrofitError cause) {

    Response r = cause.getResponse();
    if (r != null && r.getStatus() == 401) {
        // invalidate the access token
        AccountManager accountManager = AccountManager.get(Ohmage.app());
        Account[] accounts = accountManager.getAccountsByType(AuthUtil.ACCOUNT_TYPE);
        if (accounts.length != 0) {
            String token = accountManager.peekAuthToken(accounts[0], AuthUtil.AUTHTOKEN_TYPE);
            if (token != null) {
                accountManager.invalidateAuthToken(AuthUtil.ACCOUNT_TYPE, token);
                Log.e(TAG, "Invalidated " + token);
            }//from   w ww.j  av  a2s  . co m
        }
        return new AuthenticationException("Error authenticating with ohmage", cause);
    }

    return cause;
}

From source file:pt.up.mobile.authenticator.Authenticator.java

@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType,
        Bundle loginOptions) throws NetworkErrorException {
    Log.v(TAG, "getAuthToken()");

    // If the caller requested an authToken type we don't support, then
    // return an error
    if (!authTokenType.equals(Constants.AUTHTOKEN_TYPE)) {
        final Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ERROR_MESSAGE, "invalid authTokenType");
        return result;
    }//w w w .java2  s.  c o m
    try {
        final AccountManager am = AccountManager.get(mContext);
        final String peek = am.peekAuthToken(account, authTokenType);
        if (peek != null) {
            final Bundle result = new Bundle();
            result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
            result.putString(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
            result.putString(AccountManager.KEY_AUTHTOKEN, peek);
            return result;
        }
        // Extract the username and password from the Account Manager, and
        // ask
        // the server for an appropriate AuthToken.
        final String password = am.getPassword(account);
        if (password != null) {
            String[] reply;

            reply = SifeupAPI.authenticate(account.name, password, mContext);
            final String authToken = reply[1];
            if (!TextUtils.isEmpty(authToken)) {
                final Bundle result = new Bundle();
                result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
                result.putString(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
                result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
                return result;
            }
        }

    } catch (AuthenticationException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
        throw new NetworkErrorException();
    }
    // 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 panel.
    final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
    intent.putExtra(AuthenticatorActivity.PARAM_CONFIRM_CREDENTIALS, true);
    intent.putExtra(AuthenticatorActivity.PARAM_USERNAME, account.name);
    intent.putExtra(AuthenticatorActivity.PARAM_AUTHTOKEN_TYPE, authTokenType);
    intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
    final Bundle bundle = new Bundle();
    bundle.putParcelable(AccountManager.KEY_INTENT, intent);
    return bundle;
}

From source file:eu.trentorise.smartcampus.ac.authenticator.AMSCAccessProvider.java

@Override
public String readToken(Context ctx, String inAuthority) {
    final String authority = inAuthority == null ? Constants.AUTHORITY_DEFAULT : inAuthority;
    AccountManager am = AccountManager.get(ctx);
    return am.peekAuthToken(new Account(Constants.getAccountName(ctx), Constants.getAccountType(ctx)),
            authority);/*from   w w  w.jav a  2 s  .  c o  m*/
}

From source file:eu.trentorise.smartcampus.ac.authenticator.AMSCAccessProvider.java

@Override
public String getAuthToken(final Activity activity, String inAuthority)
        throws OperationCanceledException, AuthenticatorException, IOException {
    final String authority = inAuthority == null ? Constants.AUTHORITY_DEFAULT : inAuthority;
    final AccountManager am = AccountManager.get(activity);
    String token = am.peekAuthToken(
            new Account(Constants.getAccountName(activity), Constants.getAccountType(activity)), authority);
    if (token == null) {
        final Account a = new Account(Constants.getAccountName(activity), Constants.getAccountType(activity));
        Account[] accounts = am.getAccountsByType(Constants.getAccountType(activity));
        if (accounts == null || accounts.length == 0) {
            am.addAccount(Constants.getAccountType(activity), authority, null, null, null,
                    new Callback(authority, activity), null);
        } else {//w ww . j a v  a 2 s. c om
            am.getAuthToken(a, authority, null, null, new Callback(authority, activity), null);
        }
        return null;
    }
    return token;

}

From source file:com.ubuntuone.android.files.fragment.SignInFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    // If we have a token cached, first check if it is still valid.
    final AccountManager accountManager = AccountManager.get(getActivity());
    final Account account = Preferences.getAccount(accountManager);
    if (account != null) {
        usernameEditText.setText(account.name);
        passwordEditText.requestFocusFromTouch();
        final String oauthData = accountManager.peekAuthToken(account, Constants.AUTH_TOKEN_TYPE);
        if (oauthData != null) {
            checkOAuthTokenAsync(oauthData);
        }/*from   w w  w  .ja  va  2s.c  o  m*/
    }
}

From source file:com.ubuntuone.android.files.activity.LoginActivity.java

/**
 * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
 *///from www .jav a2 s  . c o  m
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.fragment_content);

    final Intent intent = getIntent();
    if (intent == null) {
        Log.e(TAG, "This activity intended to be instantiated via an Intent.");
        finish();
        return;
    }

    mAccountAuthenticatorResponse = intent
            .getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
    if (mAccountAuthenticatorResponse != null) {
        mAccountAuthenticatorResponse.onRequestContinued();
    }

    int fragmentToShow = FRAGMENT_SIGN_IN_OR_UP;

    final String action = intent.getAction();
    if (ACTION_VALIDATE.equals(action) && savedInstanceState == null) {
        showValidateFragment(true);
        return;
    }

    final AccountManager accountManager = AccountManager.get(this);
    final Account account = Preferences.getAccount(accountManager);
    if (account != null && savedInstanceState == null) {
        fragmentToShow = FRAGMENT_SIGN_IN;
        final String hint = accountManager.getUserData(account, Constants.KEY_AUTHTOKEN_HINT);
        final String oauthData = accountManager.peekAuthToken(account, Constants.AUTH_TOKEN_TYPE);
        if (oauthData == null && hint != null) {
            fragmentToShow = FRAGMENT_VALIDATE;
        } else if (oauthData != null && mAccountAuthenticatorResponse != null) {
            UIUtil.showToast(this, R.string.sso_only_one_supported, true);
            finish();
            return;
        }
    }

    if (savedInstanceState != null) {
        // Android will re-add the fragment automatically.
        return;
    }

    switch (fragmentToShow) {
    case FRAGMENT_VALIDATE:
        showValidateFragment(false);
        break;
    case FRAGMENT_SIGN_IN_OR_UP:
        showSignInOrUpFragment();
        break;
    case FRAGMENT_SIGN_IN:
        ChangeLogUtils.maybeShowChangelog(this);
        showSignInFragment(false);
        break;

    default:
        break;
    }
}