private void refreshUsingAccountManager(String token, String name) throws TokenRefreshException { if (accountManager == null) throw new TokenRefreshException("account manager is null"); invalidateToken(token); try { Bundle bundle = getAuthToken(new Account(name, GOOGLE_TYPE)); if (bundle != null) { String newToken = bundle.getString(AccountManager.KEY_AUTHTOKEN); if (!isEmpty(newToken)) { authPreferences.setOauth2Token(name, newToken, null); } else { throw new TokenRefreshException("no new token obtained"); } } else { throw new TokenRefreshException("no bundle received from accountmanager"); } } catch (AccountsException e) { Log.w(TAG, e); throw new TokenRefreshException(e); } catch (IOException e) { Log.w(TAG, e); throw new TokenRefreshException(e); } }
private void refreshUsingOAuth2Client(String name, String refreshToken) throws TokenRefreshException { try { final OAuth2Token token = oauth2Client.refreshToken(refreshToken); authPreferences.setOauth2Token(name, token.accessToken, isEmpty(token.refreshToken) ? refreshToken : token.refreshToken); } catch (IOException e) { throw new TokenRefreshException(e); } } }
public void refreshOAuth2Token() throws TokenRefreshException{ final String token = authPreferences.getOauth2Token(); final String refreshToken = authPreferences.getOauth2RefreshToken(); final String name = authPreferences.getOauth2Username(); if (isEmpty(token)) { throw new TokenRefreshException("no current token set"); } if (!isEmpty(refreshToken)) { // user authenticated using webflow refreshUsingOAuth2Client(name, refreshToken); } else { refreshUsingAccountManager(token, name); } }
@Test public void shouldHandleAuthErrorAndTokenCannotBeRefreshed() throws Exception { mockFetch(SMS, 1); when(converter.convertMessages(any(Cursor.class), notNull(DataType.class))).thenReturn(result(SMS, 1)); XOAuth2AuthenticationFailedException exception = mock(XOAuth2AuthenticationFailedException.class); when(exception.getStatus()).thenReturn(400); when(store.getFolder(notNull(DataType.class), same(dataTypePreferences))).thenThrow(exception); doThrow(new TokenRefreshException("failed")).when(tokenRefresher).refreshOAuth2Token(); task.doInBackground(config); verify(tokenRefresher, times(1)).refreshOAuth2Token(); verify(service).transition(SmsSyncState.ERROR, exception); // make sure locks only get acquired+released once verify(service).acquireLocks(); verify(service).releaseLocks(); }