public void sendResult() { IAccountManagerResponse response = getResponseAndClose(); if (response != null) { try { Account[] accounts = new Account[mAccountsWithFeatures.size()]; for (int i = 0; i < accounts.length; i++) { accounts[i] = mAccountsWithFeatures.get(i); } if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response " + response); } Bundle result = new Bundle(); result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts); response.onResult(result); } catch (RemoteException e) { // if the caller is dead then there is no one to care about remote exceptions Log.v(TAG, "failure while notifying response", e); } } }
public void checkAccount() { if (mCurrentAccount >= mAccountsOfType.length) { sendResult(); return; } final IAccountAuthenticator accountAuthenticator = mAuthenticator; if (accountAuthenticator == null) { // It is possible that the authenticator has died, which is indicated by // mAuthenticator being set to null. If this happens then just abort. // There is no need to send back a result or error in this case since // that already happened when mAuthenticator was cleared. Log.v(TAG, "checkAccount: aborting session since we are no longer" + " connected to the authenticator, " + toDebugString()); return; } try { accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures); } catch (RemoteException e) { onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception"); } }
@SuppressWarnings("deprecation") @Override public String getAuthToken() throws AuthFailureError { AccountManagerFuture<Bundle> future = mAccountManager.getAuthToken(mAccount, mAuthTokenType, mNotifyAuthFailure, null, null); Bundle result; try { result = future.getResult(); } catch (Exception e) { throw new AuthFailureError("Error while retrieving auth token", e); } String authToken = null; if (future.isDone() && !future.isCancelled()) { if (result.containsKey(AccountManager.KEY_INTENT)) { Intent intent = result.getParcelable(AccountManager.KEY_INTENT); throw new AuthFailureError(intent); } authToken = result.getString(AccountManager.KEY_AUTHTOKEN); } if (authToken == null) { throw new AuthFailureError("Got null auth token for type: " + mAuthTokenType); } return authToken; }
void bind() { Log.v(TAG, "initiating bind to authenticator type " + mAuthenticatorInfo.desc.type); Intent intent = new Intent(); intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT); intent.setClassName(mAuthenticatorInfo.serviceInfo.packageName, mAuthenticatorInfo.serviceInfo.name); intent.putExtra("_VA_|_user_id_", mUserId); if (!mContext.bindService(intent, this, Context.BIND_AUTO_CREATE)) { Log.d(TAG, "bind attempt failed for " + toDebugString()); onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure"); } }
private void createAuthNotification() { NotificationCompat.Builder builder = new NotificationCompat.Builder(getContext(), AuthenticatorActivity.AUTH_NOTIFICATION_CHANNEL_ID) .setContentTitle(getContext().getString(R.string.sync_ntf_needs_reauthentication_title)) .setContentText(getContext().getString(R.string.sync_ntf_needs_reauthentication_description)) .setSmallIcon(R.mipmap.ic_launcher) .setAutoCancel(true); Intent intent = new Intent(getContext(), AuthenticatorActivity.class); intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, getContext().getString(R.string.account_type)); intent.putExtra(AuthenticatorActivity.ARG_AUTH_TOKEN_TYPE, AuthenticatorActivity.ARG_AUTH_TOKEN_TYPE); intent.putExtra(AuthenticatorActivity.ARG_IS_ADDING_NEW_ACCOUNT, false); TaskStackBuilder stackBuilder = TaskStackBuilder.create(getContext()); stackBuilder.addParentStack(AuthenticatorActivity.class); stackBuilder.addNextIntent(intent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(resultPendingIntent); NotificationManager ntfMgr = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE); ntfMgr.notify(AuthenticatorActivity.AUTH_NOTIFICATION_ID, builder.build()); }
public static String getUsername(Context c) { AccountManager manager = AccountManager.get(c); Account[] accounts = manager.getAccountsByType("com.google"); List<String> possibleEmails = new LinkedList<String>(); for (Account account : accounts) { // TODO: Check possibleEmail against an email regex or treat // account.name as an email address only for certain account.type values. possibleEmails.add(account.name); } if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) { String email = possibleEmails.get(0); String[] parts = email.split("@"); if (parts.length > 1) return parts[0]; } return null; }
private String getName() { AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) { return null; } Account[] list = manager.getAccounts(); for (Account account : list) { if (account.type.equalsIgnoreCase("com.google")) { return account.name; } } return null; }
private ArrayList<String> getUserEmail(){ ArrayList<String> email = new ArrayList<String>(); Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+ Account[] accounts = AccountManager.get(VerifyOTP.this).getAccounts(); for (Account account : accounts) { if (emailPattern.matcher(account.name).matches()) { String possibleEmail = account.name; if(possibleEmail != null) if(possibleEmail.length() !=0 ){ email.add(possibleEmail); } } } return email; }
protected void init() { initCrypto(); accountManager = AccountManager.get(getBaseContext()); serverHandler = new AuthServerHandlerImpl(); userName = (EditText) findViewById(R.id.user_name); password = (EditText) findViewById(R.id.password); signIn = (Button) findViewById(R.id.signin_button); progressLayout = findViewById(R.id.progress_layout); Intent intent = getIntent(); authTokenType = getIntent().getStringExtra(GlobalConstant.AUTH_TYPE); if (authTokenType == null) { authTokenType = GlobalConstant.AUTHTOKEN_TYPE_FULL_ACCESS; } isNewAccount = intent.getBooleanExtra(GlobalConstant.IS_ADDING_NEW_ACCOUNT, true); if (!isNewAccount) { // existing account String accountName = getIntent().getStringExtra(GlobalConstant.ACCOUNT_NAME); userName.setText(accountName); } signIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { login(); } }); }
/** * Pass the data from server to authenticator class * * @param intent the intent contain data from user and server {@link AccountManager#KEY_ACCOUNT_NAME}, * {@link AccountManager#KEY_AUTHTOKEN}, {@link AccountManager#KEY_ACCOUNT_TYPE} and * {@link GlobalConstant#PARAM_USER_PASS} * @throws NoSuchPaddingException * @throws InvalidAlgorithmParameterException * @throws NoSuchAlgorithmException * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws InvalidKeyException * @throws UnsupportedEncodingException * @throws SignInException */ private void passDataToAuthenticator(Intent intent) throws NoSuchPaddingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, UnsupportedEncodingException, SignInException { if (intent.hasExtra(SIGNIN_ERROR)) throw new SignInException(); String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME); String accountPassword = intent.getStringExtra(GlobalConstant.PARAM_USER_PASS); accountPassword = Crypto.armorEncrypt(accountPassword.getBytes("UTF-8"), this); final Account account = new Account(accountName, authTokenType); if (isNewAccount) { String iCalId = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN); String authtoken = intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE); // encrypt user id and pass it to intent iCalId = Crypto.armorEncrypt(iCalId.getBytes("UTF-8"), this); intent.putExtra(AccountManager.KEY_AUTHTOKEN, iCalId); final Bundle extraData = new Bundle(); extraData.putString(PARAM_PRINCIPAL, iCalId); accountManager.addAccountExplicitly(account, accountPassword, extraData); accountManager.setAuthToken(account, authtoken, iCalId); } else { accountManager.setPassword(account, accountPassword); } // encrypt password and pass it to intent intent.putExtra(GlobalConstant.PARAM_USER_PASS, accountPassword); setAccountAuthenticatorResult(intent.getExtras()); setResult(RESULT_OK, intent); finish(); }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login_activity); mAccountManager = AccountManager.get(getBaseContext()); findViewById(R.id.submit) .setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { addAccount(); } }); }
@Override public Bundle getResult() throws OperationCanceledException, IOException, AuthenticatorException { Bundle bundle = mFuture.getResult(); String accountName = bundle.getString(AccountManager.KEY_ACCOUNT_NAME); String accountType = bundle.getString(AccountManager.KEY_ACCOUNT_TYPE); if (isAccountAllowed(accountName, accountType, mUid)) return bundle; else throw new OperationCanceledException("XPrivacy"); }
private void populateAccountTextView() { AccountManager am = AccountManager.get(this); Account[] accounts = am.getAccountsByType(ACCOUNT_TYPE); String accountString = "Accounts of type " + ACCOUNT_TYPE + " are : \n"; if (accounts.length != 0) { for (Account account : accounts) { accountString += "Account:" + account.name + "\n"; } } else { accountString = "No Accounts of type " + ACCOUNT_TYPE + " found. Please add accounts before exporting."; mAccountTextView.setTextColor(Color.RED); } mAccountTextView.setText(accountString); }
private void setResultAndFinish(final String type) { Bundle bundle = new Bundle(); bundle.putString(AccountManager.KEY_ACCOUNT_TYPE, type); setResult(Activity.RESULT_OK, new Intent().putExtras(bundle)); VLog.v(TAG, "ChooseAccountTypeActivity.setResultAndFinish: " + "selected account type " + type); finish(); }
@TargetApi(Build.VERSION_CODES.LOLLIPOP) public AccountSettings(@NonNull Context context, @NonNull Account account) throws InvalidAccountException { this.context = context; this.account = account; accountManager = AccountManager.get(context); }
public void refreshAuthenticatorCache(String packageName) { cache.authenticators.clear(); Intent intent = new Intent(AccountManager.ACTION_AUTHENTICATOR_INTENT); if (packageName != null) { intent.setPackage(packageName); } generateServicesMap( VPackageManagerService.get().queryIntentServices(intent, null, PackageManager.GET_META_DATA, 0), cache.authenticators, new AppAccountParser()); }
public static final String getXiaomiUserId(Context context) { Account[] accounts = AccountManager.get(context).getAccounts(); for (int i = 0; i < accounts.length; i++) { if (accounts[i].type.equals("com.xiaomi")) { String str = accounts[i].name; if (!str.trim().isEmpty()) { return str; } } } return null; }
public static String getDeviceEmailAddress(Activity activity) { Pattern emailPattern = Patterns.EMAIL_ADDRESS; if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) { return ""; } Account[] accounts = AccountManager.get(activity).getAccounts(); for (Account account : accounts) { if (emailPattern.matcher(account.name).matches()) { return account.name; } } return ""; }
@Override protected void onPostExecute(final Intent intent) { mAuthTask = null; showProgress(false); if (!intent.hasExtra(AccountManager.KEY_ERROR_MESSAGE)) { finishLogin(intent); } else { mPasswordView.setError(getString(R.string.error_incorrect_password)); mPasswordView.requestFocus(); } }
@Override public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException { Log.d(TAG, "addAccount: called."); final Intent intent = new Intent(mContext, AuthenticatorActivity.class); intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType); intent.putExtra(AuthenticatorActivity.ARG_IS_ADDING_NEW_ACCOUNT, true); intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response); final Bundle bundle = new Bundle(); bundle.putParcelable(AccountManager.KEY_INTENT, intent); return bundle; }
@Override public IBinder onBind(Intent intent) { if (intent.getAction().equals(AccountManager.ACTION_AUTHENTICATOR_INTENT)) { return getAuthenticator().getIBinder(); } else { return null; } }
/** * Tests the behavior of {@link HttpNegotiateAuthenticator.GetTokenCallback} when the result it * receives contains an intent rather than a token directly. */ @Test public void testGetTokenCallbackWithIntent() { String type = "Dummy_Account"; HttpNegotiateAuthenticator authenticator = createWithoutNative(type); RequestData requestData = new RequestData(); requestData.nativeResultObject = 42; requestData.authTokenType = "foo"; requestData.account = new Account("a", type); requestData.accountManager = sMockAccountManager; Bundle b = new Bundle(); b.putParcelable(AccountManager.KEY_INTENT, new Intent()); authenticator.new GetTokenCallback(requestData).run(makeFuture(b)); verifyZeroInteractions(sMockAccountManager); // Verify that the broadcast receiver is registered Intent intent = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION); ShadowApplication shadowApplication = Robolectric.getShadowApplication(); List<BroadcastReceiver> receivers = shadowApplication.getReceiversForIntent(intent); assertThat("There is one registered broadcast receiver", receivers.size(), equalTo(1)); // Send the intent to the receiver. BroadcastReceiver receiver = receivers.get(0); receiver.onReceive(Robolectric.getShadowApplication().getApplicationContext(), intent); // Verify that the auth token is properly requested from the account manager. verify(sMockAccountManager).getAuthToken( eq(new Account("a", type)), eq("foo"), isNull(Bundle.class), eq(true), any(HttpNegotiateAuthenticator.GetTokenCallback.class), any(Handler.class)); }
static Account getSyncAccount(Context context, int syncInterval, int syncFlexTime) { // Get an instance of the Android account manager AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE); // Create the account type and default account Account newAccount = new Account(context.getString(R.string.app_name), context.getString(R.string.rnsb_sync_account_type)); // If the password doesn't exist, the account doesn't exist if (null == accountManager.getPassword(newAccount)) { /* * Add the account and account type, no password or user data * If successful, return the Account object, otherwise report an error. */ if (!accountManager.addAccountExplicitly(newAccount, "", null)) { return null; } /* * If you don't set android:syncable="true" in * in your <provider> element in the manifest, * then call ContentResolver.setIsSyncable(account, AUTHORITY, 1) * here. */ onAccountCreated(newAccount, context, syncInterval, syncFlexTime); } return newAccount; }
@Override public void getAuthTokenLabel(int userId, IAccountManagerResponse response, final String accountType, final String authTokenType) { if (accountType == null) throw new IllegalArgumentException("accountType is null"); if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null"); AuthenticatorInfo info = getAuthenticatorInfo(accountType); if(info == null) { try { response.onError(ERROR_CODE_BAD_ARGUMENTS, "account.type does not exist"); } catch (RemoteException e) { e.printStackTrace(); } return; } new Session(response, userId, info, false, false, null) { @Override public void run() throws RemoteException { mAuthenticator.getAuthTokenLabel(this, authTokenType); } @Override public void onResult(Bundle result) throws RemoteException { if (result != null) { String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL); Bundle bundle = new Bundle(); bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label); super.onResult(bundle); } else { super.onResult(null); } } }.bind(); }
public AccountSnippet() { Context context = InstrumentationRegistry.getContext(); mAccountManager = AccountManager.get(context); mSyncStatusObserverHandles = new LinkedList<>(); mSyncWhitelist = new HashMap<>(); mLock = new ReentrantReadWriteLock(); }
/** * Helper method to get the fake account to be used with SyncAdapter, or make a new one * if the fake account doesn't exist yet. If we make a new account, we call the * onAccountCreated method so we can initialize things. * * @param context The context used to access the account service * @return a fake account. */ public static Account getSyncAccount(Context context) { // Get an instance of the Android account manager AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE); // Create the account type and default account Account newAccount = new Account( context.getString(R.string.app_name), context.getString(R.string.sync_account_type)); // If the password doesn't exist, the account doesn't exist if ( null == accountManager.getPassword(newAccount) ) { /* * Add the account and account type, no password or user data * If successful, return the Account object, otherwise report an error. */ if (!accountManager.addAccountExplicitly(newAccount, "", null)) { return null; } /* * If you don't set android:syncable="true" in * in your <provider> element in the manifest, * then call ContentResolver.setIsSyncable(account, AUTHORITY, 1) * here. */ onAccountCreated(newAccount, context); } return newAccount; }
/** * An AccountManagerFuture represents the result of an asynchronous AccountManager call. * The result can only be retrieved using method get when the call has completed, * blocking if necessary until it is ready. * * @param activity * @param credential * @param authTokenType * @return a Bundle containing the result of the call, possibly null */ private AccountManagerFuture<Bundle> getAccountManagerResult(Activity activity, GoogleCredential credential, String authTokenType, String accountName) { AccountManagerFuture<Bundle> future = null; GoogleAccountManager accountManager = new GoogleAccountManager(activity); // Force the return of fresh token by invalidating the current token // Doing this on every OAuth request, avoids the need to determine whether the // authToken has expired, usually after 1 hour, and then getting // another one using the refresh token. accountManager.invalidateAuthToken(credential.getAccessToken()); AccountManager.get(activity).invalidateAuthToken(authTokenType, null); // Try to get the user's account by account name. Might return null Account account = accountManager.getAccountByName(accountName); // Here is where AccountManager may prompt user to select an account if (account != null) { // We have the user's account at this point, so AccountManager simply returns the token Log.i(TAG, "Getting token by account"); future = accountManager.getAccountManager().getAuthToken(account, authTokenType, true, null, null); } else { // AccountManager uses 'features' to get the authToken, possibly prompting the user to choose an account Log.i(TAG, "Getting token by features, possibly prompting user to select an account"); future = accountManager.getAccountManager().getAuthTokenByFeatures(GoogleAccountManager.ACCOUNT_TYPE, authTokenType, null, activity, null, null, null, null); } // Return the whole bundle containing the authToken, account name, and other data. return future; }
AndroidAuthenticator(AccountManager accountManager, Account account, String authTokenType, boolean notifyAuthFailure) { mAccountManager = accountManager; mAccount = account; mAuthTokenType = authTokenType; mNotifyAuthFailure = notifyAuthFailure; }
@Before public void setUp() { mAccountManager = mock(AccountManager.class); mFuture = mock(AccountManagerFuture.class); mAccount = new Account("coolperson", "cooltype"); mAuthenticator = new AndroidAuthenticator(mAccountManager, mAccount, "cooltype", false); }
@Test(expected = AuthFailureError.class) public void resultContainsIntent() throws Exception { Intent intent = new Intent(); Bundle bundle = new Bundle(); bundle.putParcelable(AccountManager.KEY_INTENT, intent); when(mAccountManager.getAuthToken(mAccount, "cooltype", false, null, null)).thenReturn(mFuture); when(mFuture.getResult()).thenReturn(bundle); when(mFuture.isDone()).thenReturn(true); when(mFuture.isCancelled()).thenReturn(false); mAuthenticator.getAuthToken(); }
@Test public void goodToken() throws Exception { Bundle bundle = new Bundle(); bundle.putString(AccountManager.KEY_AUTHTOKEN, "monkey"); when(mAccountManager.getAuthToken(mAccount, "cooltype", false, null, null)).thenReturn(mFuture); when(mFuture.getResult()).thenReturn(bundle); when(mFuture.isDone()).thenReturn(true); when(mFuture.isCancelled()).thenReturn(false); Assert.assertEquals("monkey", mAuthenticator.getAuthToken()); }
public void showLogon4Inlay() { this.accountManager = AccountManager.get(this.context); if (!hasLetvAuthenticator()) { return; } if (isLetvLogined()) { syncLogon4LetvPhone(); } else { addAccount((Activity) this.context, new LogonCallBack()); } }
public AccountChooser(Activity activity, String service, String title, String key) { this.activity = activity; this.service = service; this.chooseAccountPrompt = title; this.preferencesKey = key; this.accountManager = AccountManager.get(activity); }
public void showEmailInput(View view){ // email suggestion from registered accounts ArrayList<String> emails = new ArrayList<>(0); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && view != null) { requestPermissions(new String[]{Manifest.permission.GET_ACCOUNTS}, REQUEST_ACCOUNTS_PERMISSION); return; } } else { Account[] accounts = AccountManager.get(this).getAccounts(); for (Account account : accounts) { if (Patterns.EMAIL_ADDRESS.matcher(account.name).matches()) { emails.add(account.name); } } } SimpleFormDialog.build() .fields(Input.email(EMAIL) .required() .suggest(emails) .text(emails.size() > 0 ? emails.get(0) : null) ) .show(this, EMAIL_DIALOG); /** Results: {@link MainActivity#onResult} **/ }