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:com.xiaomi.account.utils.SysHelper.java

public static HashMap<String, String> querySnsInfoFromServer(Context context, Account account) {
    if (account == null) {
        Log.w(TAG, "no Xiaomi account, skip to querySnsInfoFromServer");
        return null;
    }/*from  w  w w .j a v a  2s .  c om*/
    String userId = account.name;
    AccountManager am = AccountManager.get(context);
    int count = 0;
    while (count < 2) {
        String authToken = getAuthToken(am, account, Constants.PASSPORT_API_SID);
        ExtendedAuthToken extendedAuthToken = ExtendedAuthToken.parse(authToken);
        if (extendedAuthToken != null) {
            String serviceToken = extendedAuthToken.authToken;
            String security = extendedAuthToken.security;
            if (serviceToken == null || security == null) {
                break;
            }
            String encryptedUserId = am.getUserData(account, Constants.KEY_ENCRYPTED_USER_ID);
            try {
                HashMap<String, String> data = Maps.newHashMap();
                data.put(com.xiaomi.account.Constants.EXTRA_SINA_WEIBO_ACCESSTOKEN,
                        CloudHelper.getBindedAccessToken(userId, encryptedUserId,
                                com.xiaomi.account.Constants.SINA_WEIBO_SNS_TYPE, serviceToken, security));
                data.put(com.xiaomi.account.Constants.EXTRA_QQ_ACCESSTOKEN,
                        CloudHelper.getBindedAccessToken(userId, encryptedUserId,
                                com.xiaomi.account.Constants.QQ_SNS_TYPE, serviceToken, security));
                if (!Build.IS_INTERNATIONAL_BUILD) {
                    return data;
                }
                data.put(com.xiaomi.account.Constants.EXTRA_FACEBOOK_ACCESSTOKEN,
                        CloudHelper.getBindedAccessToken(userId, encryptedUserId,
                                com.xiaomi.account.Constants.FACEBOOK_SNS_TYPE, serviceToken, security));
                return data;
            } catch (InvalidResponseException e) {
                Log.e(TAG, "invalid response when get user info", e);
            } catch (CipherException e2) {
                Log.e(TAG, "CipherException when get user info", e2);
            } catch (IOException e3) {
                Log.e(TAG, "IOException when get user info", e3);
            } catch (AuthenticationFailureException e4) {
                Log.e(TAG, "auth failure when get user info", e4);
                am.invalidateAuthToken(account.type, authToken);
                count++;
            } catch (AccessDeniedException e5) {
                Log.e(TAG, "access denied when get user info", e5);
            }
        } else {
            break;
        }
    }
    return null;
}

From source file:vn.mbm.phimp.me.gallery3d.picasa.PicasaApi.java

public int getAlbumPhotos(AccountManager accountManager, SyncResult syncResult, AlbumEntry album,
        GDataParser.EntryHandler handler) {
    // Construct the query URL for user albums.
    StringBuilder builder = new StringBuilder(BASE_URL);
    builder.append("user/");
    builder.append(Uri.encode(mAuth.user));
    builder.append("/albumid/");
    builder.append(album.id);/*from w w w. jav  a2s  . com*/
    builder.append(BASE_QUERY_STRING);
    builder.append("&kind=photo");
    try {
        // Send the request.
        synchronized (mOperation) {
            GDataClient.Operation operation = mOperation;
            operation.inOutEtag = album.photosEtag;
            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:
                    // We need to reset the authtoken and retry only once.
                    if (!retry) {
                        retry = true;
                        accountManager.invalidateAuthToken(PicasaService.SERVICE_NAME, mAuth.authToken);
                    }
                    if (numRetries == 0) {
                        ++syncResult.stats.numAuthExceptions;
                    }
                    break;
                default:
                    Log.e(TAG, "getAlbumPhotos: " + builder.toString() + ", unexpected status code "
                            + operation.outStatus);
                    ++syncResult.stats.numIoExceptions;
                    return RESULT_ERROR;
                }
                --numRetries;
            } while (retry && numRetries >= 0);

            // Store the new ETag for the album/photos feed.
            album.photosEtag = operation.inOutEtag;

            // Parse the response.
            synchronized (mParser) {
                GDataParser parser = mParser;
                parser.setEntry(mPhotoInstance);
                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, "getAlbumPhotos: " + e);
        ++syncResult.stats.numIoExceptions;
        e.printStackTrace();
    } catch (SAXException e) {
        Log.e(TAG, "getAlbumPhotos: " + e);
        ++syncResult.stats.numParseExceptions;
        e.printStackTrace();
    }
    return RESULT_ERROR;
}

From source file:com.ocp.picasa.PicasaApi.java

public int getAlbumPhotos(AccountManager accountManager, SyncResult syncResult, AlbumEntry album,
        GDataParser.EntryHandler handler) {
    // Construct the query URL for user albums.
    StringBuilder builder = new StringBuilder(BASE_URL);
    builder.append("user/");
    builder.append(Uri.encode(mAuth.user));
    builder.append("/albumid/");
    builder.append(album.id);//from w  w w. ja v a 2  s  .c o m
    builder.append(BASE_QUERY_STRING);
    builder.append("&kind=photo");
    try {
        // Send the request.
        synchronized (mOperation) {
            GDataClient.Operation operation = mOperation;
            operation.inOutEtag = album.photosEtag;
            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:
                    // We need to reset the authtoken and retry only once.
                    if (!retry) {
                        retry = true;
                        accountManager.invalidateAuthToken(PicasaService.SERVICE_NAME, mAuth.authToken);
                    }
                    if (numRetries == 0) {
                        ++syncResult.stats.numAuthExceptions;
                    }
                    break;
                default:
                    Log.e(Gallery.TAG, TAG + ": " + "getAlbumPhotos: " + builder.toString()
                            + ", unexpected status code " + operation.outStatus);
                    ++syncResult.stats.numIoExceptions;
                    return RESULT_ERROR;
                }
                --numRetries;
            } while (retry && numRetries >= 0);

            // Store the new ETag for the album/photos feed.
            album.photosEtag = operation.inOutEtag;

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

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

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

    try {
        ServerConnection.addSongToActivePlaylist(playerId, libId, authToken);
    } catch (JSONException e) {
        alertAddSongException(account, originalIntent);
        Log.e(TAG, "JSON exception when adding to playist");
    } catch (ParseException e) {
        alertAddSongException(account, originalIntent);
        Log.e(TAG, "Parse exception when adding to playist");
    } catch (IOException e) {
        alertAddSongException(account, originalIntent);
        Log.e(TAG, "IO exception when adding to playist");
        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 adding to playist");
        } else {
            alertAddSongException(account, originalIntent);
            Log.e(TAG, "Hard Authentication exception when adding to playist");
        }
    } catch (PlayerInactiveException e) {
        Log.e(TAG, "Event over exceptoin when retreiving playlist");
        Utils.handleInactivePlayer(this, account);
    } catch (NoLongerInPlayerException e) {
        Utils.handleNoLongerInPlayer(this, account);
    } catch (KickedException e) {
        Utils.handleKickedFromPlayer(this, account);
    }

}

From source file:com.myandroidremote.AccountsActivity.java

/**
 * Registers for C2DM messaging with the given account name.
 * //  ww w. j a v 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.putString(Util.AUTH_COOKIE, null);
    editor.commit();

    // Obtain an auth token and register
    final AccountManager mgr = AccountManager.get(mContext);
    Account[] accts = mgr.getAccountsByType("com.google");
    for (Account acct : accts) {
        if (acct.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 account name
                String authCookie = "dev_appserver_login=" + accountName + ":false:" + accountName;
                boolean result = 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
                mgr.getAuthToken(acct, "ah", null, this, new AccountManagerCallback<Bundle>() {
                    public void run(AccountManagerFuture<Bundle> future) {
                        try {
                            Bundle authTokenBundle = future.getResult();
                            String authToken = authTokenBundle.get(AccountManager.KEY_AUTHTOKEN).toString();
                            String authCookie = getAuthCookie(authToken);
                            if (authCookie == null) {
                                mgr.invalidateAuthToken("com.google", authToken);
                            }
                            prefs.edit().putString(Util.AUTH_COOKIE, authCookie).commit();

                            C2DMessaging.register(mContext, Setup.SENDER_ID);
                        } catch (AuthenticatorException e) {
                            Log.w(TAG, "Got AuthenticatorException " + e);
                            Log.w(TAG, Log.getStackTraceString(e));
                        } catch (IOException e) {
                            Log.w(TAG, "Got IOException " + Log.getStackTraceString(e));
                            Log.w(TAG, Log.getStackTraceString(e));
                        } catch (OperationCanceledException e) {
                            Log.w(TAG, "Got OperationCanceledException " + e);
                            Log.w(TAG, Log.getStackTraceString(e));
                        }
                    }
                }, null);
            }
            break;
        }
    }
}

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

public int getAlbumPhotos(AccountManager accountManager, SyncResult syncResult, AlbumEntry album,
        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("/albumid/");
    builder.append(album.id);/*from  w w w.j  a va2 s.  c  o  m*/
    builder.append(BASE_QUERY_STRING);
    builder.append("&kind=photo");
    try {
        // Send the request.
        synchronized (mOperation) {
            GDataClient.Operation operation = mOperation;
            operation.inOutEtag = album.photosEtag;
            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:
                    // We need to reset the authtoken and retry only once.
                    if (!retry) {
                        retry = true;
                        accountManager.invalidateAuthToken(PicasaService.SERVICE_NAME, mAuth.authToken);
                    }
                    if (numRetries == 0) {
                        ++syncResult.stats.numAuthExceptions;
                    }
                    break;
                default:
                    Log.e(TAG, "getAlbumPhotos: " + builder.toString() + ", unexpected status code "
                            + operation.outStatus);
                    ++syncResult.stats.numIoExceptions;
                    return RESULT_ERROR;
                }
                --numRetries;
            } while (retry && numRetries >= 0);

            // Store the new ETag for the album/photos feed.
            album.photosEtag = operation.inOutEtag;

            // Parse the response.
            synchronized (mParser) {
                GDataParser parser = mParser;
                parser.setEntry(mPhotoInstance);
                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, "getAlbumPhotos: " + e);
        ++syncResult.stats.numIoExceptions;
        e.printStackTrace();
    } catch (SAXException e) {
        Log.e(TAG, "getAlbumPhotos: " + e);
        ++syncResult.stats.numParseExceptions;
        e.printStackTrace();
    }
    return RESULT_ERROR;
}

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

private void removeSongFromPlaylist(Account account, String playerId, String libId, boolean attemptReauth,
        Intent originalIntent) {//from  ww w . j av  a  2  s .  com
    String authToken = "";
    AccountManager am = AccountManager.get(this);
    try {
        authToken = am.blockingGetAuthToken(account, "", true);
    } catch (AuthenticatorException e) {
        alertRemoveSongException(account, originalIntent);
        Log.e(TAG, "Authentication exception when removing from playist");
    } catch (OperationCanceledException e) {
        alertRemoveSongException(account, originalIntent);
        Log.e(TAG, "Op Canceled exception when removing from playist");
    } catch (IOException e) {
        alertRemoveSongException(account, originalIntent);
        Log.e(TAG, "IO exception when removing from playist/getting authtoken");
        Log.e(TAG, e.getMessage());
    }

    try {
        Log.d(TAG, "Actually removing song");
        ServerConnection.removeSongFromActivePlaylist(playerId, libId, authToken);
        Intent removeSongComplete = new Intent(Constants.BROADCAST_REMOVE_SONG_COMPLETE);
        this.sendBroadcast(removeSongComplete);
    } catch (ParseException e) {
        alertRemoveSongException(account, originalIntent);
        Log.e(TAG, "Parse exception when removing from playist");
    } catch (IOException e) {
        alertRemoveSongException(account, originalIntent);
        Log.e(TAG, "IO exception when removing from playist");
        Log.e(TAG, e.getMessage());
    } catch (AuthenticationException e) {
        if (attemptReauth) {
            am.invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken);
            removeSongFromPlaylist(account, playerId, libId, false, originalIntent);
            Log.e(TAG, "Soft Authentication exception when removing from playist");
        } else {
            alertRemoveSongException(account, originalIntent);
            Log.e(TAG, "Hard Authentication exception when removing from playist");
        }
    } catch (PlayerInactiveException e) {
        Log.e(TAG, "Event over exceptoin when removing from playlist");
        Utils.handleInactivePlayer(this, account);
    } catch (NoLongerInPlayerException e) {
        Utils.handleNoLongerInPlayer(this, account);
    } catch (KickedException e) {
        Utils.handleKickedFromPlayer(this, account);
    }
}