Search in sources :

Example 86 with AccountManager

use of android.accounts.AccountManager in project WordPress-Android by wordpress-mobile.

the class UserEmailUtils method getPrimaryEmail.

/**
     * Get primary account and return its name if it matches the email address pattern.
     *
     * @return primary account email address if it can be found or empty string else.
     */
public static String getPrimaryEmail(Context context) {
    try {
        AccountManager accountManager = AccountManager.get(context);
        if (accountManager == null)
            return "";
        Account[] accounts = accountManager.getAccounts();
        Pattern emailPattern = Patterns.EMAIL_ADDRESS;
        for (Account account : accounts) {
            // make sure account.name is an email address before adding to the list
            if (emailPattern.matcher(account.name).matches()) {
                return account.name;
            }
        }
        return "";
    } catch (SecurityException e) {
        // exception will occur if app doesn't have GET_ACCOUNTS permission
        AppLog.e(T.UTILS, "SecurityException - missing GET_ACCOUNTS permission");
        return "";
    }
}
Also used : Account(android.accounts.Account) Pattern(java.util.regex.Pattern) AccountManager(android.accounts.AccountManager)

Example 87 with AccountManager

use of android.accounts.AccountManager in project 360-Engine-for-Android by 360.

the class NativeContactsApiTestHelper2 method wipeNabAccounts.

@Override
public void wipeNabAccounts() {
    // TODO Auto-generated method stub
    AccountManager accountMan = AccountManager.get(mContext);
    android.accounts.Account[] accounts = accountMan.getAccountsByType(PEOPLE_ACCOUNT_TYPE);
    if (accounts != null && accounts.length > 0) {
        int numAccounts = accounts.length;
        while (numAccounts-- > 0) {
            accountMan.removeAccount(accounts[numAccounts], null, null);
            threadWait(5000);
        }
    }
}
Also used : Account(android.accounts.Account) AccountManager(android.accounts.AccountManager)

Example 88 with AccountManager

use of android.accounts.AccountManager in project ETSMobile-Android2 by ApplETS.

the class ApplicationManager method onCreate.

@Override
public void onCreate() {
    super.onCreate();
    AnalyticsHelper.getInstance(this);
    createDatabaseTables();
    //        SupportKit.init(this, getString(R.string.credentials_supportkit));
    //        Fabric.with(this, new Crashlytics());
    AccountManager accountManager = AccountManager.get(this);
    Account[] accounts = accountManager.getAccountsByType(Constants.ACCOUNT_TYPE);
    String username = "", password = "";
    if (accounts.length > 0) {
        username = accounts[0].name;
        password = accountManager.getPassword(accounts[0]);
    }
    if (username.length() > 0 && password.length() > 0) {
        userCredentials = new UserCredentials(username, password);
    }
    SecurePreferences securePreferences = new SecurePreferences(this);
    int typeUsagerId = securePreferences.getInt(Constants.TYPE_USAGER_ID, -1);
    String domaine = securePreferences.getString(Constants.DOMAINE, "");
    if (typeUsagerId != -1 && !TextUtils.isEmpty(domaine)) {
        ApplicationManager.typeUsagerId = typeUsagerId;
        ApplicationManager.domaine = domaine;
    }
}
Also used : Account(android.accounts.Account) AccountManager(android.accounts.AccountManager) UserCredentials(ca.etsmtl.applets.etsmobile.model.UserCredentials) SecurePreferences(ca.etsmtl.applets.etsmobile.util.SecurePreferences)

Example 89 with AccountManager

use of android.accounts.AccountManager in project ETSMobile-Android2 by ApplETS.

the class ETSMobileAuthenticator method getAuthToken.

@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException {
    // Extract the username and password from the Account Manager, and ask
    // the server for an appropriate AuthToken.
    final AccountManager am = AccountManager.get(mContext);
    String authToken = am.peekAuthToken(account, authTokenType);
    SecurePreferences securePreferences = new SecurePreferences(mContext);
    Date expirationDate = Utility.getDate(securePreferences, Constants.EXP_DATE_COOKIE, new Date());
    Date now = new Date();
    // Lets give another try to authenticate the user
    if (TextUtils.isEmpty(authToken) || expirationDate.before(now)) {
        final String password = am.getPassword(account);
        final String username = account.name;
        if (password != null) {
            OkHttpClient client = new OkHttpClient();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "{\n  \"Username\": \"" + username + "\",\n  \"Password\": \"" + password + "\"\n}");
            Request request = new Request.Builder().url(mContext.getString(R.string.portail_api_authentification_url)).post(body).addHeader("content-type", "application/json").addHeader("cache-control", "no-cache").build();
            Response httpResponse = null;
            try {
                httpResponse = client.newCall(request).execute();
                if (httpResponse.code() == 200) {
                    authToken = httpResponse.header("Set-Cookie");
                    Utility.saveCookieExpirationDate(authToken, securePreferences);
                    JSONObject jsonResponse = new JSONObject(httpResponse.body().string());
                    int typeUsagerId = jsonResponse.getInt("TypeUsagerId");
                    String domaine = jsonResponse.getString("Domaine");
                    securePreferences.edit().putInt(Constants.TYPE_USAGER_ID, typeUsagerId).commit();
                    securePreferences.edit().putString(Constants.DOMAINE, domaine).commit();
                    ApplicationManager.domaine = domaine;
                    ApplicationManager.typeUsagerId = typeUsagerId;
                    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
                    boolean isTokenSent = sharedPreferences.getBoolean(Constants.IS_GCM_TOKEN_SENT_TO_SERVER, false);
                    if (!isTokenSent) {
                        Intent intent = new Intent(mContext, RegistrationIntentService.class);
                        mContext.startService(intent);
                    }
                } else {
                    Log.e("Erreur Portail", httpResponse.toString());
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    // If we get an authToken - we return it
    if (!TextUtils.isEmpty(authToken)) {
        final Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
        result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
        result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
        return result;
    } else {
        final Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
        result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
        result.putString(AccountManager.KEY_AUTHTOKEN, null);
        return result;
    }
// If we get here, then we couldn't access the user's password - so we
// need to re-prompt them for their credentials. We do that by creating
// an intent to display our AuthenticatorActivity.
/*
        final Intent intent = new Intent(mContext, LoginActivity.class);
        intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
        intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, account.type);
        intent.putExtra(Constants.KEY_AUTH_TYPE, authTokenType);
        final Bundle bundle = new Bundle();
        bundle.putParcelable(AccountManager.KEY_INTENT, intent);
        return bundle;
        */
}
Also used : OkHttpClient(com.squareup.okhttp.OkHttpClient) SharedPreferences(android.content.SharedPreferences) Bundle(android.os.Bundle) Request(com.squareup.okhttp.Request) JSONException(org.json.JSONException) Intent(android.content.Intent) IOException(java.io.IOException) Date(java.util.Date) AccountAuthenticatorResponse(android.accounts.AccountAuthenticatorResponse) Response(com.squareup.okhttp.Response) JSONObject(org.json.JSONObject) MediaType(com.squareup.okhttp.MediaType) AccountManager(android.accounts.AccountManager) RequestBody(com.squareup.okhttp.RequestBody)

Example 90 with AccountManager

use of android.accounts.AccountManager in project newsrob by marianokamp.

the class AccountManagementUtilsImplementation method getAuthToken.

public void getAuthToken(final Activity waitingActivity, Handler handler, final IAuthenticationCallback callback, String googleAccount) {
    PL.log("AMU.getAuthToken for " + googleAccount + ".", waitingActivity);
    AccountManager accountManager = AccountManager.get(waitingActivity);
    // find the selected account
    Account selectedAccount = findAccountByGoogleAccountId(waitingActivity, accountManager, googleAccount);
    if (selectedAccount == null)
        throw new RuntimeException("No account found for " + googleAccount + ".");
    final Account selAccount = selectedAccount;
    if (false)
        accountManager.getAuthTokenByFeatures(GOOGLE_ACCOUNT_TYPE, "reader", GOOGLE_ACCOUNT, waitingActivity, new Bundle(), null, new AccountManagerCallback<Bundle>() {

            public void run(android.accounts.AccountManagerFuture<Bundle> f) {
                try {
                    Bundle b = f.getResult();
                    for (String key : b.keySet()) System.out.println("key " + key + " value " + b.getByte(key));
                    String authToken = f.getResult().getString(AccountManager.KEY_AUTHTOKEN);
                    if (authToken == null)
                        throw new RuntimeException("AuthToken was null.");
                    callback.onAuthTokenReceived(selAccount.name, authToken);
                } catch (Exception e) {
                    e.printStackTrace();
                    if (e instanceof OperationCanceledException)
                        e = new Exception("Operation canceled by user.");
                    callback.onError(e);
                }
            }
        }, handler);
    if (true)
        accountManager.getAuthToken(selectedAccount, AUTH_TOKEN_TYPE_READER, null, waitingActivity, new AccountManagerCallback<Bundle>() {

            public void run(android.accounts.AccountManagerFuture<Bundle> f) {
                try {
                    String authToken = f.getResult().getString(AccountManager.KEY_AUTHTOKEN);
                    if (authToken == null)
                        throw new RuntimeException("AuthToken was null.");
                    PL.log("AMU.getAuthToken for " + selAccount.name + "received token=" + authToken.substring(0, 4) + "(2).", waitingActivity);
                    callback.onAuthTokenReceived(selAccount.name, authToken);
                } catch (Exception e) {
                    e.printStackTrace();
                    if (e instanceof OperationCanceledException)
                        e = new Exception("Operation canceled by user.");
                    callback.onError(e);
                }
            }
        }, handler);
}
Also used : Account(android.accounts.Account) AccountManagerCallback(android.accounts.AccountManagerCallback) Bundle(android.os.Bundle) OperationCanceledException(android.accounts.OperationCanceledException) AccountManager(android.accounts.AccountManager) OperationCanceledException(android.accounts.OperationCanceledException) IOException(java.io.IOException) AuthenticatorException(android.accounts.AuthenticatorException)

Aggregations

AccountManager (android.accounts.AccountManager)105 Account (android.accounts.Account)76 Bundle (android.os.Bundle)14 IOException (java.io.IOException)11 Intent (android.content.Intent)10 OperationCanceledException (android.accounts.OperationCanceledException)7 AuthenticatorException (android.accounts.AuthenticatorException)5 View (android.view.View)5 TextView (android.widget.TextView)5 HashSet (java.util.HashSet)5 SharedPreferences (android.content.SharedPreferences)4 AccountManagerCallback (android.accounts.AccountManagerCallback)3 Paint (android.graphics.Paint)3 JSONException (org.json.JSONException)3 AccountsException (android.accounts.AccountsException)2 TargetApi (android.annotation.TargetApi)2 AlertDialog (android.app.AlertDialog)2 Context (android.content.Context)2 DialogInterface (android.content.DialogInterface)2 OperationApplicationException (android.content.OperationApplicationException)2