List of usage examples for android.accounts AccountManager invalidateAuthToken
public void invalidateAuthToken(final String accountType, final String authToken)
From source file:io.tehtotalpwnage.musicphp_android.NavigationActivity.java
@Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { // Handle navigation view item clicks here. int id = item.getItemId(); if (id == R.id.nav_camera) { // Everything after this point is actually my code. StringRequest req = new StringRequest(Request.Method.GET, UrlGenerator.getServerUrl(this) + "/api/user", new Response.Listener<String>() { @Override// w w w. j a v a 2 s. c o m public void onResponse(String response) { TextView view = new TextView(getApplicationContext()); view.setText(response); FrameLayout layout = (FrameLayout) findViewById(R.id.navFrame); layout.removeAllViews(); layout.addView(view); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.v(TAG, "Connection error"); TextView view = new TextView(getApplicationContext()); view.setText(getResources().getString(R.string.error_connection)); FrameLayout layout = (FrameLayout) findViewById(R.id.navFrame); layout.removeAllViews(); layout.addView(view); NetworkResponse networkResponse = error.networkResponse; if (networkResponse != null && networkResponse.statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) { Log.v(TAG, "Request was unauthorized, meaning that a new token is needed"); AccountManager manager = AccountManager.get(getApplicationContext()); manager.invalidateAuthToken(MusicPhpAccount.ACCOUNT_TYPE, getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN)); Intent intent = new Intent(NavigationActivity.this, MainActivity.class); startActivity(intent); } } }) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("Accept", "application/json"); params.put("Authorization", "Bearer " + getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN)); return params; } }; VolleySingleton.getInstance(this).addToRequestQueue(req); } else if (id == R.id.nav_gallery) { final Context context = this; getListing(Item.albums, 0, new VolleyCallback() { @Override public void onSuccess(JSONArray result) { Log.d(TAG, "Volley callback reached"); String albums[][] = new String[result.length()][3]; for (int i = 0; i < result.length(); i++) { try { JSONObject object = result.getJSONObject(i); albums[i][0] = object.getString("name"); albums[i][1] = object.getJSONObject("artist").getString("name"); albums[i][2] = object.getString("id"); } catch (Exception e) { e.printStackTrace(); } } AlbumListingAdapter adapter = new AlbumListingAdapter(context, albums, getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN)); GridView view = new GridView(context); view.setLayoutParams(new DrawerLayout.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); view.setNumColumns(GridView.AUTO_FIT); view.setColumnWidth((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 148, getResources().getDisplayMetrics())); view.setStretchMode(GridView.STRETCH_SPACING_UNIFORM); view.setAdapter(adapter); view.setVerticalSpacing((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics())); FrameLayout layout = (FrameLayout) findViewById(R.id.navFrame); layout.removeAllViews(); layout.addView(view); Log.d(TAG, "Adapter setup complete"); } }); } else if (id == R.id.nav_slideshow) { getListing(Item.artists, 0, new VolleyCallback() { @Override public void onSuccess(JSONArray result) { } }); } else if (id == R.id.nav_manage) { getListing(Item.tracks, 0, new VolleyCallback() { @Override public void onSuccess(JSONArray result) { } }); } else if (id == R.id.nav_share) { Log.d(TAG, "Queue contains " + queue.size() + " items. Displaying queue..."); ListView view = new ListView(this); view.setLayoutParams(new DrawerLayout.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); String tracks[][] = new String[queue.size()][2]; for (int i = 0; i < queue.size(); i++) { MediaSessionCompat.QueueItem queueItem = queue.get(i); tracks[i][0] = queueItem.getDescription().getMediaId(); tracks[i][1] = (String) queueItem.getDescription().getTitle(); } AlbumAdapter adapter = new AlbumAdapter(this, tracks, getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN), this); view.setAdapter(adapter); view.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // String sAddress = getApplicationContext().getSharedPreferences("Prefs", 0).getString("server", null); // Bundle bundle = new Bundle(); // bundle.putString("Authorization", "Bearer " + token); // bundle.putString("Title", tracks[position][1]); // bundle.putString("art", getIntent().getStringExtra("art")); // bundle.putString("ID", tracks[position][0]); // MediaControllerCompat.getMediaController(AlbumActivity.this).getTransportControls().playFromUri(Uri.parse(sAddress + "/api/tracks/" + tracks[position][0] + "/audio"), bundle); } }); FrameLayout layout = (FrameLayout) findViewById(R.id.navFrame); layout.removeAllViews(); layout.addView(view); } else if (id == R.id.nav_send) { String sAddress = getSharedPreferences("Prefs", 0).getString("server", null); StringRequest request = new StringRequest(Request.Method.POST, sAddress + "/api/logout", new Response.Listener<String>() { @Override public void onResponse(String response) { try { JSONObject object = new JSONObject(response); if (object.getString("status").equals("OK")) { Log.v(TAG, "Logged out successfully. Now redirecting to MainActivity..."); AccountManager manager = AccountManager.get(getApplicationContext()); Account accounts[] = manager.getAccountsByType(MusicPhpAccount.ACCOUNT_TYPE); int account = 0; for (int i = 0; i < accounts.length; i++) { if (accounts[i].name.equals( getIntent().getStringExtra(AccountManager.KEY_ACCOUNT_NAME))) { account = i; break; } } final AccountManagerFuture future; if (Build.VERSION.SDK_INT >= 22) { future = manager.removeAccount(accounts[account], NavigationActivity.this, new AccountManagerCallback<Bundle>() { @Override public void run(AccountManagerFuture<Bundle> future) { } }, null); } else { future = manager.removeAccount(accounts[account], new AccountManagerCallback<Boolean>() { @Override public void run(AccountManagerFuture<Boolean> future) { } }, null); } AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... params) { try { future.getResult(); Intent intent = new Intent(NavigationActivity.this, MainActivity.class); startActivity(intent); } catch (Exception e) { e.printStackTrace(); } return null; } }; task.execute(); } else { Log.v(TAG, "Issue with logging out..."); } } catch (JSONException e) { Log.e(TAG, "Issue with parsing JSON..."); e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Error on logging out..."); } }) { @Override public Map<String, String> getHeaders() { Map<String, String> params = new HashMap<>(); params.put("Accept", "application/json"); params.put("Authorization", "Bearer " + getIntent().getStringExtra(AccountManager.KEY_AUTHTOKEN)); return params; } }; VolleySingleton.getInstance(this).addToRequestQueue(request); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; }
From source file:com.mikecorrigan.bohrium.pubsub.RegistrationClient.java
@SafeVarargs private final void handleAuthToken(AccountManagerFuture<Bundle>... tokens) { Log.v(TAG, "handleAuthToken"); try {/*from w w w. j a v a2 s.c o m*/ Bundle result = tokens[0].getResult(); Intent intent = (Intent) result.get(AccountManager.KEY_INTENT); if (intent != null) { Log.i(TAG, "Launch activity before getting authToken: intent=" + intent); setStateAndNotify(REGISTRATION_STATE_REGISTERING, REGISTRATION_SUBSTATE_PROMPTING_USER); intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK); notifyLaunchIntent(intent); return; } String authToken = result.getString(AccountManager.KEY_AUTHTOKEN); if (mNeedInvalidate) { mNeedInvalidate = false; Log.i(TAG, "Invalidating token and starting over."); // Invalidate auth token. AccountManager mgr = AccountManager.get(this); mgr.invalidateAuthToken(mConfiguration.getString(ACCOUNT_TYPE, DEFAULT_ACCOUNT_TYPE), authToken); setStateAndNotify(REGISTRATION_STATE_REGISTERING, REGISTRATION_SUBSTATE_INVALIDATED_AUTH_TOKEN); // Initiate the request again. requestAuthToken(); return; } else { Log.i(TAG, "Received authToken=" + authToken); mConfiguration.putString(AUTH_TOKEN, authToken); setStateAndNotify(REGISTRATION_STATE_REGISTERING, REGISTRATION_SUBSTATE_HAVE_AUTH_TOKEN); // Move on to the next step, request auth cookie. requestAuthCookie(); return; } } catch (Exception e) { Log.e(TAG, "Exception " + e); Log.e(TAG, Log.getStackTraceString(e)); } setStateAndNotify(REGISTRATION_STATE_ERROR, REGISTRATION_SUBSTATE_ERROR_AUTH_TOKEN); }
From source file:com.xiaomi.account.utils.SysHelper.java
public static XiaomiUserInfo queryXiaomiUserInfo(Context context, Account account) { XiaomiUserInfo xiaomiUserInfo = null; if (account != null) { 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) { break; }//from w w w .ja v a 2 s. c o m String serviceToken = extendedAuthToken.authToken; String security = extendedAuthToken.security; if (serviceToken == null || security == null) { break; } try { xiaomiUserInfo = CloudHelper.getXiaomiUserInfo(userId, am.getUserData(account, Constants.KEY_ENCRYPTED_USER_ID), serviceToken, security); break; } 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 { Log.w(TAG, "no Xiaomi account, skip to query user info"); } return xiaomiUserInfo; }
From source file:com.xiaomi.account.utils.SysHelper.java
public static XiaomiUserProfile queryXiaomiUserProfile(Context context, Account account) { XiaomiUserProfile xiaomiUserProfile = null; if (account != null) { 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) { break; }// ww w .j a v a 2 s .c om String serviceToken = extendedAuthToken.authToken; String security = extendedAuthToken.security; if (serviceToken == null || security == null) { break; } try { xiaomiUserProfile = CloudHelper.getXiaomiUserProfile(account.name, am.getUserData(account, Constants.KEY_ENCRYPTED_USER_ID), serviceToken, security); break; } 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 { Log.w(TAG, "no Xiaomi account, skip to query user profile"); } return xiaomiUserProfile; }
From source file:com.cerema.cloud2.ui.activity.FileActivity.java
/** * Invalidates the credentials stored for the current OC account and requests new credentials to the user, * navigating to {@link AuthenticatorActivity} * * @param context Android Context needed to access the {@link AccountManager}. Received as a parameter * to make the method accessible to {@link android.content.BroadcastReceiver}s. *///from w w w. ja va 2 s .c o m protected void requestCredentialsUpdate(Context context) { try { /// step 1 - invalidate credentials of current account OwnCloudClient client; OwnCloudAccount ocAccount = new OwnCloudAccount(getAccount(), context); client = (OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(ocAccount)); if (client != null) { OwnCloudCredentials cred = client.getCredentials(); if (cred != null) { AccountManager am = AccountManager.get(context); if (cred.authTokenExpires()) { am.invalidateAuthToken(getAccount().type, cred.getAuthToken()); } else { am.clearPassword(getAccount()); } } } /// step 2 - request credentials to user Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class); updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount()); updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN); updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); startActivity(updateAccountCredentials); } catch (com.cerema.cloud2.lib.common.accounts.AccountUtils.AccountNotFoundException e) { Toast.makeText(context, R.string.auth_account_does_not_exist, Toast.LENGTH_SHORT).show(); } }
From source file:org.brussels.gtug.attendance.AccountsActivity.java
/** * Registers for C2DM messaging with the given account name. * //from www . j a v a2 s.com * @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)) { // 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, Constants.SENDER_ID); } }, null); } }, null); break; } } }
From source file:com.nest5.businessClient.AccountsActivity.java
/** * Registers for C2DM messaging with the given account name. * //from w ww . j a va 2 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)) { // 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.synox.android.ui.activity.FileActivity.java
/** * Invalidates the credentials stored for the current OC account and requests new credentials to the user, * navigating to {@link AuthenticatorActivity} * * @param context Android Context needed to access the {@link AccountManager}. Received as a parameter * to make the method accessible to {@link android.content.BroadcastReceiver}s. *//*from www . j ava2s . c o m*/ protected void requestCredentialsUpdate(Context context) { try { /// step 1 - invalidate credentials of current account OwnCloudClient client; OwnCloudAccount ocAccount = new OwnCloudAccount(getAccount(), context); client = (OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(ocAccount)); if (client != null) { OwnCloudCredentials cred = client.getCredentials(); if (cred != null) { AccountManager am = AccountManager.get(context); if (cred.authTokenExpires()) { am.invalidateAuthToken(getAccount().type, cred.getAuthToken()); } else { am.clearPassword(getAccount()); } } } /// step 2 - request credentials to user Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class); updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount()); updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN); updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); startActivity(updateAccountCredentials); } catch (com.synox.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) { Toast.makeText(context, R.string.auth_account_does_not_exist, Toast.LENGTH_SHORT).show(); } }
From source file:org.klnusbaum.udj.ArtistsLoader.java
private ArtistsResult attemptLoad(boolean attemptReauth) { AccountManager am = AccountManager.get(getContext()); String authToken = ""; try {/*from w ww.j a v a 2 s. c om*/ authToken = am.blockingGetAuthToken(account, "", true); } catch (IOException e) { //TODO this might actually be an auth error return new ArtistsResult(null, ArtistsError.AUTHENTICATION_ERROR); } catch (AuthenticatorException e) { return new ArtistsResult(null, ArtistsError.AUTHENTICATION_ERROR); } catch (OperationCanceledException e) { return new ArtistsResult(null, ArtistsError.AUTHENTICATION_ERROR); } try { String playerId = am.getUserData(account, Constants.LAST_PLAYER_ID_DATA); return getArtists(playerId, authToken); } catch (JSONException e) { return new ArtistsResult(null, ArtistsError.SERVER_ERROR); } catch (ParseException e) { return new ArtistsResult(null, ArtistsError.SERVER_ERROR); } catch (IOException e) { return new ArtistsResult(null, ArtistsError.SERVER_ERROR); } catch (AuthenticationException e) { if (attemptReauth) { Log.d(TAG, "soft auth failure"); am.invalidateAuthToken(Constants.ACCOUNT_TYPE, authToken); return attemptLoad(false); } else { Log.d(TAG, "hard auth failure"); return new ArtistsResult(null, ArtistsError.AUTHENTICATION_ERROR); } } catch (PlayerInactiveException e) { return new ArtistsResult(null, ArtistsError.PLAYER_INACTIVE_ERROR); } catch (NoLongerInPlayerException e) { return new ArtistsResult(null, ArtistsError.NO_LONGER_IN_PLAYER_ERROR); } catch (KickedException e) { return new ArtistsResult(null, ArtistsError.KICKED_ERROR); } }