Example usage for android.accounts AccountManager invalidateAuthToken

List of usage examples for android.accounts AccountManager invalidateAuthToken

Introduction

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

Prototype

public void invalidateAuthToken(final String accountType, final String authToken) 

Source Link

Document

Removes an auth token from the AccountManager's cache.

Usage

From source file:org.klnusbaum.udj.network.PlaylistSyncService.java

private void setCurrentSong(Account account, String playerId, String libId, boolean attemptReauth,
        Intent originalIntent) {/* w w w  . ja v  a  2  s.c o  m*/
    String authToken = "";
    AccountManager am = AccountManager.get(this);
    try {
        authToken = am.blockingGetAuthToken(account, "", true);
    } catch (AuthenticatorException e) {
        alertSetSongException(account, originalIntent);
        Log.e(TAG, "Authentication exception when setting song");
    } catch (OperationCanceledException e) {
        alertSetSongException(account, originalIntent);
        Log.e(TAG, "Op Canceled exception when setting song");
    } catch (IOException e) {
        alertSetSongException(account, originalIntent);
        Log.e(TAG, "IO exception when geting authtoken for setting song");
        Log.e(TAG, e.getMessage());
    }

    try {
        ServerConnection.setCurrentSong(playerId, libId, authToken);
        Intent setCurrentComplete = new Intent(Constants.BROADCAST_SET_CURRENT_COMPLETE);
        this.sendBroadcast(setCurrentComplete);
    } catch (IOException e) {
        alertSetSongException(account, originalIntent);
        Log.e(TAG, "IO exception when setting song");
        Log.e(TAG, e.getMessage());
    } catch (AuthenticationException e) {
        if (attemptReauth) {
            am.invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken);
            addSongToPlaylist(account, playerId, libId, false, originalIntent);
            Log.e(TAG, "Soft Authentication exception when setting song");
        } else {
            alertSetSongException(account, originalIntent);
            Log.e(TAG, "Hard Authentication exception when setting song");
        }
    } catch (PlayerInactiveException e) {
        Log.e(TAG, "Event over exceptoin when setting song");
        Utils.handleInactivePlayer(this, account);
    } catch (NoLongerInPlayerException e) {
        Utils.handleNoLongerInPlayer(this, account);
    } catch (KickedException e) {
        Utils.handleKickedFromPlayer(this, account);
    }
}

From source file:com.example.simba.myapplicationnote.gtask.remote.GTaskClient.java

private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
    String authToken;// w  ww  .j  a v a  2s.  c  om
    AccountManager accountManager = AccountManager.get(activity);
    Account[] accounts = accountManager.getAccountsByType("com.google");

    if (accounts.length == 0) {
        Log.e(TAG, "there is no available google account");
        return null;
    }

    String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
    Account account = null;
    for (Account a : accounts) {
        if (a.name.equals(accountName)) {
            account = a;
            break;
        }
    }
    if (account != null) {
        mAccount = account;
    } else {
        Log.e(TAG, "unable to get an account with the same name in the settings");
        return null;
    }

    // get the token now
    AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account, "goanna_mobile",
            null, activity, null, null);
    try {
        Bundle authTokenBundle = accountManagerFuture.getResult();
        authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
        if (invalidateToken) {
            accountManager.invalidateAuthToken("com.google", authToken);
            loginGoogleAccount(activity, false);
        }
    } catch (Exception e) {
        Log.e(TAG, "get auth token failed");
        authToken = null;
    }

    return authToken;
}

From source file:com.samsung.android.remindme.jsonrpc.AuthenticatedJsonRpcJavaClient.java

public void blockingAuthenticateAccount(final Account account, final int needAuthAction,
        boolean forceReauthenticate) throws AuthenticationException, OperationCanceledException,
        RequestedUserAuthenticationException, InvalidAuthTokenException {

    String existingToken = mTokenStoreHelper.getToken(account);
    if (!forceReauthenticate && existingToken != null) {
        BasicClientCookie c = new BasicClientCookie("ACSID", existingToken);
        try {/*  w w w.  j a  va2 s .com*/
            c.setDomain(new URI(Config.SERVER_BASE_URL).getHost());
            mHttpClient.getCookieStore().addCookie(c);
            return;
        } catch (URISyntaxException e) {
        }
    }

    // Get an auth token for this account.
    AccountManager am = AccountManager.get(mContext);
    Bundle authBundle = null;
    String authToken = null;

    // Block on getting the auth token result.
    try {
        authBundle = am.getAuthToken(account, APPENGINE_SERVICE_NAME, needAuthAction == NEED_AUTH_NOTIFICATION,
                null, null).getResult();
    } catch (IOException e) {
        throw new AuthenticationException("IOException while getting auth token.", e);
    } catch (AuthenticatorException e) {
        throw new AuthenticationException("AuthenticatorException while getting auth token.", e);
    }

    if (authBundle.containsKey(AccountManager.KEY_INTENT) && needAuthAction == NEED_AUTH_INTENT) {
        Intent authRequestIntent = (Intent) authBundle.get(AccountManager.KEY_INTENT);
        mContext.startActivity(authRequestIntent);
        throw new RequestedUserAuthenticationException();
    } else if (authBundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
        authToken = authBundle.getString(AccountManager.KEY_AUTHTOKEN);
        System.out.println(authToken);
        System.out.println(AccountManager.KEY_AUTHTOKEN);
    }

    if (authToken == null) {
        throw new AuthenticationException("Retrieved auth token was null.");
    }

    try {
        blockingAuthenticateWithToken(account, authToken);
    } catch (InvalidAuthTokenException e) {
        am.invalidateAuthToken(account.type, authToken);
        throw e;
    }
}

From source file:com.cloudtask1.AccountsActivity.java

/**
 * Registers for C2DM messaging with the given account name.
 * /*from  www .j  a  v a2 s  . c o  m*/
 * @param accountName a String containing a Google account name
 */
private void register(final String accountName) {
    // Store the account name in shared preferences
    final SharedPreferences prefs = Util.getSharedPreferences(mContext);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(Util.ACCOUNT_NAME, accountName);
    editor.remove(Util.AUTH_COOKIE);
    editor.remove(Util.DEVICE_REGISTRATION_ID);
    editor.commit();

    // Obtain an auth token and register
    final AccountManager mgr = AccountManager.get(mContext);
    Account[] accts = mgr.getAccountsByType("com.google");
    for (Account acct : accts) {
        final Account account = acct;
        if (account.name.equals(accountName)) {
            if (Util.isDebug(mContext)) {
                // Use a fake cookie for the dev mode app engine server
                // The cookie has the form email:isAdmin:userId
                // We set the userId to be the same as the email
                String authCookie = "dev_appserver_login=" + accountName + ":false:" + accountName;
                prefs.edit().putString(Util.AUTH_COOKIE, authCookie).commit();
                C2DMessaging.register(mContext, Setup.SENDER_ID);
            } else {
                // Get the auth token from the AccountManager and convert
                // it into a cookie for the appengine server
                final Activity activity = this;
                mgr.getAuthToken(account, "ah", null, activity, new AccountManagerCallback<Bundle>() {
                    public void run(AccountManagerFuture<Bundle> future) {
                        String authToken = getAuthToken(future);
                        // Ensure the token is not expired by invalidating it and
                        // obtaining a new one
                        mgr.invalidateAuthToken(account.type, authToken);
                        mgr.getAuthToken(account, "ah", null, activity, new AccountManagerCallback<Bundle>() {
                            public void run(AccountManagerFuture<Bundle> future) {
                                String authToken = getAuthToken(future);
                                // Convert the token into a cookie for future use
                                String authCookie = getAuthCookie(authToken);
                                Editor editor = prefs.edit();
                                editor.putString(Util.AUTH_COOKIE, authCookie);
                                editor.commit();
                                C2DMessaging.register(mContext, Setup.SENDER_ID);
                            }
                        }, null);
                    }
                }, null);
            }
            break;
        }
    }
}

From source file:com.masteriti.manager.AccountsActivity.java

/**
 * Registers for C2DM messaging with the given account name.
 * //from w  w  w.j  av  a  2 s  .  c  om
 * @param accountName a String containing a Google account name
 */
private void register(final String accountName) {
    // Store the account name in shared preferences
    final SharedPreferences prefs = Util.getSharedPreferences(mContext);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(Util.ACCOUNT_NAME, accountName);
    editor.remove(Util.AUTH_COOKIE);
    editor.remove(Util.DEVICE_REGISTRATION_ID);
    editor.commit();

    // Obtain an auth token and register
    final AccountManager mgr = AccountManager.get(mContext);
    Account[] accts = mgr.getAccountsByType("com.google");
    for (Account acct : accts) {
        final Account account = acct;
        if (account.name.equals(accountName)) {
            if (Util.isDebug(mContext)) {
                // Use a fake cookie for the dev mode app engine server
                // The cookie has the form email:isAdmin:userId
                // We set the userId to be the same as the email
                String authCookie = "dev_appserver_login=" + accountName + ":false:" + accountName;
                prefs.edit().putString(Util.AUTH_COOKIE, authCookie).commit();
                C2DMessaging.register(mContext, Setup.SENDER_ID);
            } else {
                // Get the auth token from the AccountManager and convert
                // it into a cookie for the appengine server
                final Activity activity = this;
                mgr.getAuthToken(account, "ah", null, activity, new AccountManagerCallback<Bundle>() {
                    @Override
                    public void run(AccountManagerFuture<Bundle> future) {
                        String authToken = getAuthToken(future);
                        // Ensure the token is not expired by invalidating it and
                        // obtaining a new one
                        mgr.invalidateAuthToken(account.type, authToken);
                        mgr.getAuthToken(account, "ah", null, activity, new AccountManagerCallback<Bundle>() {
                            @Override
                            public void run(AccountManagerFuture<Bundle> future) {
                                String authToken = getAuthToken(future);
                                // Convert the token into a cookie for future use
                                String authCookie = getAuthCookie(authToken);
                                Editor editor = prefs.edit();
                                editor.putString(Util.AUTH_COOKIE, authCookie);
                                editor.commit();
                                C2DMessaging.register(mContext, Setup.SENDER_ID);
                            }
                        }, null);
                    }
                }, null);
            }
            break;
        }
    }
}

From source file:com.timtory.wmgallery.picasa.PicasaApi.java

public int getAlbums(AccountManager accountManager, SyncResult syncResult, UserEntry user,
        GDataParser.EntryHandler handler) {
    // Construct the query URL for user albums.
    String baseUrl = Settings.Secure.getString(mContentResolver, SETTINGS_PICASA_GDATA_BASE_URL_KEY);
    StringBuilder builder = new StringBuilder(baseUrl != null ? baseUrl : DEFAULT_BASE_URL);
    builder.append("user/");
    builder.append(Uri.encode(mAuth.user));
    builder.append(BASE_QUERY_STRING);/* ww w .j av  a 2  s .  co m*/
    builder.append("&kind=album");
    try {
        // Send the request.
        synchronized (mOperation) {
            GDataClient.Operation operation = mOperation;
            operation.inOutEtag = user.albumsEtag;
            boolean retry = false;
            int numRetries = 1;
            do {
                retry = false;
                synchronized (mClient) {
                    mClient.get(builder.toString(), operation);
                }
                switch (operation.outStatus) {
                case HttpStatus.SC_OK:
                    break;
                case HttpStatus.SC_NOT_MODIFIED:
                    return RESULT_NOT_MODIFIED;
                case HttpStatus.SC_FORBIDDEN:
                case HttpStatus.SC_UNAUTHORIZED:
                    if (!retry) {
                        accountManager.invalidateAuthToken(PicasaService.ACCOUNT_TYPE, mAuth.authToken);
                        retry = true;
                    }
                    if (numRetries == 0) {
                        ++syncResult.stats.numAuthExceptions;
                    }
                default:
                    Log.i(TAG, "getAlbums uri " + builder.toString());
                    Log.e(TAG, "getAlbums: unexpected status code " + operation.outStatus + " data: "
                            + operation.outBody.toString());
                    ++syncResult.stats.numIoExceptions;
                    return RESULT_ERROR;
                }
                --numRetries;
            } while (retry && numRetries >= 0);

            // Store the new ETag for the user/albums feed.
            user.albumsEtag = operation.inOutEtag;

            // Parse the response.
            synchronized (mParser) {
                GDataParser parser = mParser;
                parser.setEntry(mAlbumInstance);
                parser.setHandler(handler);
                try {
                    Xml.parse(operation.outBody, Xml.Encoding.UTF_8, parser);
                } catch (SocketException e) {
                    Log.e(TAG, "getAlbumPhotos: " + e);
                    ++syncResult.stats.numIoExceptions;
                    e.printStackTrace();
                    return RESULT_ERROR;
                }
            }
        }
        return RESULT_OK;
    } catch (IOException e) {
        Log.e(TAG, "getAlbums: " + e);
        ++syncResult.stats.numIoExceptions;
    } catch (SAXException e) {
        Log.e(TAG, "getAlbums: " + e);
        ++syncResult.stats.numParseExceptions;
    }
    return RESULT_ERROR;
}

From source file:org.klnusbaum.udj.network.PlaylistSyncService.java

private void setPlayerVolume(Intent intent, Account account, String playerId, boolean attemptReauth) {
    AccountManager am = AccountManager.get(this);
    int desiredVolume = intent.getIntExtra(Constants.PLAYER_VOLUME_EXTRA, 0);
    Log.d(TAG, "proceeding to set volume of player to: " + String.valueOf(desiredVolume) + " on server");

    String authToken = "";
    try {//from w w  w . ja  v  a  2  s .co  m
        authToken = am.blockingGetAuthToken(account, "", true);
    } catch (OperationCanceledException e) {
        //TODO do something here?
        Log.e(TAG, "Operation canceled exception in set playback");
        return;
    } catch (AuthenticatorException e) {
        //TODO do something here?
        Log.e(TAG, "Authenticator exception in set playback");
        return;
    } catch (IOException e) {
        //TODO do something here?
        Log.e(TAG, "IO exception in set playback");
        return;
    }

    try {
        ServerConnection.setPlayerVolume(playerId, desiredVolume, authToken);
    } catch (IOException e) {
        Log.e(TAG, "IO exception in set volume");
        alertSetVolumeException(account, intent);
        return;
    } catch (AuthenticationException e) {
        if (attemptReauth) {
            Log.d(TAG, "Soft Authentication exception when setting volume");
            am.invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken);
            setPlayerVolume(intent, account, playerId, false);
        } else {
            Log.e(TAG, "Hard Authentication exception when setting volume");
            //TODO do something here?
        }
    } catch (PlayerInactiveException e) {
        Log.e(TAG, "Player inactive exception in set volume");
        Utils.handleInactivePlayer(this, account);
        return;
    } catch (NoLongerInPlayerException e) {
        Utils.handleNoLongerInPlayer(this, account);
        return;
    } catch (KickedException e) {
        Utils.handleKickedFromPlayer(this, account);
    }
}

From source file:com.capstonecontrol.AccountsActivity.java

/**
 * Registers for C2DM messaging with the given account name.
 * /* w  w  w . j  av a2  s. c o  m*/
 * @param accountName
 *            a String containing a Google account name
 */
private void register(final String accountName) {
    // Store the account name in shared preferences
    final SharedPreferences prefs = Util.getSharedPreferences(mContext);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(Util.ACCOUNT_NAME, accountName);
    editor.remove(Util.AUTH_COOKIE);
    editor.remove(Util.DEVICE_REGISTRATION_ID);
    editor.commit();

    // Obtain an auth token and register
    final AccountManager mgr = AccountManager.get(mContext);
    Account[] accts = mgr.getAccountsByType("com.google");
    for (Account acct : accts) {
        final Account account = acct;
        if (account.name.equals(accountName)) {
            if (Util.isDebug(mContext)) {
                // Use a fake cookie for the dev mode app engine server
                // The cookie has the form email:isAdmin:userId
                // We set the userId to be the same as the email
                String authCookie = "dev_appserver_login=" + accountName + ":false:" + accountName;
                prefs.edit().putString(Util.AUTH_COOKIE, authCookie).commit();
                C2DMessaging.register(mContext, Setup.SENDER_ID);
            } else {
                // Get the auth token from the AccountManager and convert
                // it into a cookie for the appengine server
                final Activity activity = this;
                mgr.getAuthToken(account, "ah", null, activity, new AccountManagerCallback<Bundle>() {
                    public void run(AccountManagerFuture<Bundle> future) {
                        String authToken = getAuthToken(future);
                        // Ensure the token is not expired by
                        // invalidating it and
                        // obtaining a new one
                        mgr.invalidateAuthToken(account.type, authToken);
                        mgr.getAuthToken(account, "ah", null, activity, new AccountManagerCallback<Bundle>() {
                            public void run(AccountManagerFuture<Bundle> future) {
                                String authToken = getAuthToken(future);
                                // Convert the token into a
                                // cookie for future use
                                String authCookie = getAuthCookie(authToken);
                                Editor editor = prefs.edit();
                                editor.putString(Util.AUTH_COOKIE, authCookie);
                                editor.commit();
                                C2DMessaging.register(mContext, Setup.SENDER_ID);
                            }
                        }, null);
                    }
                }, null);
            }
            break;
        }
    }
}

From source file:falcofinder.android.fuehrerschein.chat.AccountsActivity.java

/**
 * Registers for C2DM messaging with the given account name.
 * /*from   w w  w  .  j av a 2  s .co  m*/
 * @param accountName a String containing a Google account name
 */
private void register(final String accountName) {
    // Store the account name in shared preferences
    final SharedPreferences prefs = Util.getSharedPreferences(mContext);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(Util.ACCOUNT_NAME, accountName);
    editor.remove(Util.AUTH_COOKIE);
    editor.remove(Util.DEVICE_REGISTRATION_ID);
    editor.commit();

    // Obtain an auth token and register
    final AccountManager mgr = AccountManager.get(mContext);
    Account[] accts = mgr.getAccountsByType("com.google");
    for (Account acct : accts) {
        final Account account = acct;
        if (account.name.equals(accountName)) {
            if (Util.isDebug(mContext)) {
                // Use a fake cookie for the dev mode app engine server
                // The cookie has the form email:isAdmin:userId
                // We set the userId to be the same as the email
                String authCookie = "dev_appserver_login=" + accountName + ":false:" + accountName;
                prefs.edit().putString(Util.AUTH_COOKIE, authCookie).commit();

                //commento c2dm non usato
                //C2DMessaging.register(mContext, Setup.SENDER_ID);

            } else {
                // Get the auth token from the AccountManager and convert
                // it into a cookie for the appengine server
                final Activity activity = this;
                mgr.getAuthToken(account, "ah", null, activity, new AccountManagerCallback<Bundle>() {
                    public void run(AccountManagerFuture<Bundle> future) {
                        String authToken = getAuthToken(future);
                        // Ensure the token is not expired by invalidating it and
                        // obtaining a new one
                        mgr.invalidateAuthToken(account.type, authToken);
                        mgr.getAuthToken(account, "ah", null, activity, new AccountManagerCallback<Bundle>() {
                            public void run(AccountManagerFuture<Bundle> future) {
                                String authToken = getAuthToken(future);
                                // Convert the token into a cookie for future use
                                String authCookie = getAuthCookie(authToken);
                                Editor editor = prefs.edit();
                                editor.putString(Util.AUTH_COOKIE, authCookie);
                                editor.commit();
                                //commento c2dm non usato
                                // C2DMessaging.register(mContext, Setup.SENDER_ID);
                            }
                        }, null);
                    }
                }, null);
            }
            break;
        }
    }
}

From source file:org.klnusbaum.udj.network.EventCommService.java

private void leaveEvent(AccountManager am, Account account, boolean attemptReauth) {
    Log.d(TAG, "In leave event");

    if (account == null) {
        //TODO handle error
        return;//www .j ava 2s .  co m
    }

    long userId;
    String authToken;
    try {
        userId = Long.valueOf(am.getUserData(account, Constants.USER_ID_DATA));
        //TODO handle if event id isn't provided
        authToken = am.blockingGetAuthToken(account, "", true);
    } catch (OperationCanceledException e) {
        Log.e(TAG, "Operation canceled exception in EventCommService");
        return;
    } catch (AuthenticatorException e) {
        Log.e(TAG, "Authenticator exception in EventCommService");
        return;
    } catch (IOException e) {
        Log.e(TAG, "IO exception in EventCommService");
        return;
    }

    try {
        long eventId = Long.valueOf(am.getUserData(account, Constants.LAST_EVENT_ID_DATA));
        if (eventId != Constants.NO_EVENT_ID) {
            ServerConnection.leaveEvent(eventId, Long.valueOf(userId), authToken);
            setNotInEvent(account);
            Intent leftEventIntent = new Intent(Constants.LEFT_EVENT_ACTION);
            sendBroadcast(leftEventIntent);
        }
    } catch (IOException e) {
        Log.e(TAG, "IO exception in EventCommService: " + e.getMessage());
    } catch (AuthenticationException e) {
        if (attemptReauth) {
            Log.e(TAG, "Soft Authentication exception in EventCommService");
            am.invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken);
            leaveEvent(am, account, false);
        } else {
            Log.e(TAG, "HARD Authentication exception in EventCommService");
        }
    } finally {
        //TODO potential this get's repeated because it's already called once
        //above. I'll deal with that fact later.
        setNotInEvent(account);
    }
    //TODO need to implement exponential back off when log out fails.
    // 1. This is just nice to the server
    // 2. If we don't log out, there could be problems on the next event joined
}