Example usage for android.accounts AccountManager KEY_AUTHTOKEN

List of usage examples for android.accounts AccountManager KEY_AUTHTOKEN

Introduction

In this page you can find the example usage for android.accounts AccountManager KEY_AUTHTOKEN.

Prototype

String KEY_AUTHTOKEN

To view the source code for android.accounts AccountManager KEY_AUTHTOKEN.

Click Source Link

Document

Bundle key used for the auth token value in results from #getAuthToken and friends.

Usage

From source file:com.murrayc.galaxyzoo.app.LoginUtils.java

/**
 * This returns null if there is no account (not even an anonymous account).
 * Don't call this from the main thread - use an AsyncTask, for instance.
 *
 * @param context/*from w w w  .j a v  a  2  s  . c  o m*/
 * @return
 */
@Nullable
public static LoginDetails getAccountLoginDetails(final Context context) {
    final AccountManager mgr = AccountManager.get(context);
    if (mgr == null) {
        Log.error(
                "getAccountLoginDetails(): getAccountLoginDetails() failed because AccountManager.get() returned null.");
        return null;
    }

    final Account account = getAccount(mgr);
    if (account == null) {
        Log.error(
                "getAccountLoginDetails(): getAccountLoginDetails() failed because getAccount() returned null. ");
        return null;
    }

    //Make sure that this has not been unset somehow:
    setAutomaticAccountSync(context, account);

    final LoginDetails result = new LoginDetails();

    //Avoid showing our anonymous account name in the UI.
    //Also, an anonymous account never has an auth_api_key.
    result.isAnonymous = TextUtils.equals(account.name, ACCOUNT_NAME_ANONYMOUS);
    if (result.isAnonymous) {
        return result; //Return a mostly-empty empty (but not null) LoginDetails.
    }

    result.name = account.name;

    //Note that this requires the USE_CREDENTIALS permission on
    //SDK <=22.
    final AccountManagerFuture<Bundle> response = mgr.getAuthToken(account, ACCOUNT_AUTHTOKEN_TYPE, null, null,
            null, null);
    try {
        final Bundle bundle = response.getResult();
        if (bundle == null) {
            //TODO: Let the caller catch this?
            Log.error(
                    "getAccountLoginDetails(): getAccountLoginDetails() failed because getAuthToken() returned a null response result bundle.");
            return null;
        }

        result.authApiKey = bundle.getString(AccountManager.KEY_AUTHTOKEN);
        return result;
    } catch (final OperationCanceledException e) {
        //TODO: Let the caller catch this?
        Log.error("getAccountLoginDetails(): getAccountLoginDetails() failed", e);
        return null;
    } catch (final AuthenticatorException e) {
        //TODO: Let the caller catch this?
        Log.error("getAccountLoginDetails(): getAccountLoginDetails() failed", e);
        return null;
    } catch (final IOException e) {
        //TODO: Let the caller catch this?
        Log.error("getAccountLoginDetails(): getAccountLoginDetails() failed", e);
        return null;
    }
}

From source file:com.pindroid.authenticator.AuthenticatorActivity.java

/**
 * Called when response is received from the server for confirm credentials
 * request. See onAuthenticationResult(). Sets the
 * AccountAuthenticatorResult which is sent back to the caller.
 * //  w w w .j a v a2s .  c  o  m
 * @param the confirmCredentials result.
 */
protected void finishConfirmCredentials(String authToken) {
    Log.i(TAG, "finishConfirmCredentials()");
    final Account account = new Account(mUsername, Constants.ACCOUNT_TYPE);
    mAccountManager.setAuthToken(account, Constants.AUTHTOKEN_TYPE, authToken);
    final Intent intent = new Intent();
    intent.putExtra(AccountManager.KEY_BOOLEAN_RESULT, authToken != null);
    intent.putExtra(AccountManager.KEY_AUTHTOKEN, authToken);
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    finish();
}

From source file:com.flowzr.budget.holo.export.flowzr.FlowzrBillTask.java

protected void onGetAuthToken(Bundle bundle) {
    String auth_token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
    new GetCookieTask().execute(auth_token);
}

From source file:com.example.jumpnote.android.jsonrpc.AuthenticatedJsonRpcJavaClient.java

public static void ensureHasTokenWithUI(Activity activity, Account account,
        final EnsureHasTokenWithUICallback callback) {
    AccountManager am = AccountManager.get(activity);
    am.getAuthToken(account, APPENGINE_SERVICE_NAME, null, activity, new AccountManagerCallback<Bundle>() {
        public void run(AccountManagerFuture<Bundle> authBundleFuture) {
            Bundle authBundle = null;//from www.ja  v a 2s  .  c om
            try {
                authBundle = authBundleFuture.getResult();
            } catch (OperationCanceledException e) {
                callback.onAuthDenied();
                return;
            } catch (AuthenticatorException e) {
                callback.onError(e);
                return;
            } catch (IOException e) {
                callback.onError(e);
                return;
            }

            if (authBundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
                callback.onHasToken((String) authBundle.get(AccountManager.KEY_AUTHTOKEN));
            } else {
                callback.onError(
                        new IllegalStateException("No auth token available, but operation not canceled."));
            }
        }
    }, null);
}

From source file:org.creativecommons.thelist.fragments.AccountFragment.java

@Override
public void onResume() {
    super.onResume();
    mContext = getActivity();/*w  w w  . j av  a 2  s  .c om*/
    mMessageHelper = new MessageHelper(mContext);

    //Get account information
    String accountName = getActivity().getIntent().getStringExtra(ARG_ACCOUNT_NAME);
    final String accountType = getActivity().getIntent().getStringExtra(ARG_ACCOUNT_TYPE);
    mAuthTokenType = getActivity().getIntent().getStringExtra(ARG_AUTH_TYPE);
    if (mAuthTokenType == null)
        mAuthTokenType = AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS;

    if (accountName != null) {
        ((EditText) getView().findViewById(R.id.accountName)).setText(accountName);
    }

    //UI Elements
    final Button cancelButton = (Button) getView().findViewById(R.id.cancelButton);
    final Button loginButton = (Button) getView().findViewById(R.id.loginButton);
    final Button signUpButton = (Button) getView().findViewById(R.id.signUpButton);
    final EditText accountEmailField = (EditText) getView().findViewById(R.id.accountName);
    final EditText accountPasswordField = (EditText) getView().findViewById(R.id.accountPassword);
    accountPasswordField.setTypeface(Typeface.DEFAULT);
    final TextView newAccountButton = (TextView) getView().findViewById(R.id.signUp);

    //Try Login on Click
    loginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String accountEmail = accountEmailField.getText().toString().trim();
            final String accountPassword = accountPasswordField.getText().toString().trim();

            if (accountEmail.isEmpty() || accountPassword.isEmpty()) {
                mMessageHelper.showDialog(mContext, getString(R.string.login_error_title),
                        getString(R.string.login_error_message));
            } else {
                ListUser mCurrentUser = new ListUser(getActivity());
                try {
                    mCurrentUser.userSignIn(accountEmail, accountPassword, mAuthTokenType,
                            new ListUser.AuthCallback() {
                                @Override
                                public void onSuccess(String authtoken) {
                                    //TODO: authtoken stuff
                                    Bundle data = new Bundle();

                                    data.putString(AccountManager.KEY_ACCOUNT_NAME, accountEmail);
                                    data.putString(AccountManager.KEY_ACCOUNT_TYPE, accountType);
                                    data.putString(AccountManager.KEY_AUTHTOKEN, authtoken);
                                    data.putString(PARAM_USER_PASS, accountPassword);

                                    //Create Bundle to create Account
                                    mCallback.onUserSignedIn(data);
                                }
                            });
                } catch (Exception e) {
                    Log.d("LoginFragment", e.getMessage());
                    //data.putString(KEY_ERROR_MESSAGE, e.getMessage());
                }
            }
        }
    });

    //Actually I need an account --> show user Sign Up Button
    if (newAccountButton != null) {
        newAccountButton.setMovementMethod(LinkMovementMethod.getInstance());
    }
    //TODO: hide loginButton and show signUpButton
    //        newAccountButton.setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View v) {
    //
    //                //loginButton.setVisibility(View.GONE);
    //                //signUpButton.setVisibility(View.VISIBLE);
    //            }
    //        });

    //Cancel Activity
    cancelButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCallback.onCancelLogin();
        }
    });

    //TODO: do when we have register user
    //        signUpButton.setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View v) {
    //                //TODO:userSignUp
    //                final String accountEmail = accountEmailField.getText().toString().trim();
    //                final String accountPassword = accountPasswordField.getText().toString().trim();
    //
    //                if (accountEmail.isEmpty() || accountPassword.isEmpty()) {
    //                    mMessageHelper.showDialog(mContext, getString(R.string.login_error_title),
    //                            getString(R.string.login_error_message));
    //                } else {
    //                    //TODO: Login User + save to sharedPreferences
    //                    ListUser mCurrentUser = new ListUser(getActivity());
    //                    try {
    //                        mCurrentUser.userSignUp(accountEmail, accountPassword, mAuthTokenType, new ListUser.AuthCallback() {
    //                            @Override
    //                            public void onSuccess(String authtoken) {
    //
    //                                Bundle data = new Bundle();
    //
    //                                data.putString(AccountManager.KEY_ACCOUNT_NAME, accountEmail);
    //                                data.putString(AccountManager.KEY_ACCOUNT_TYPE, accountType);
    //                                data.putString(AccountManager.KEY_AUTHTOKEN, authtoken);
    //                                data.putString(PARAM_USER_PASS, accountPassword);
    //
    //                                mCallback.onUserSignedUp(data);
    //                            }
    //                        });
    //                    } catch (Exception e) {
    //                        Log.d("LoginFragment", e.getMessage());
    //                    }
    //                }
    //            }
    //        });

}

From source file:com.manning.androidhacks.hack023.authenticator.AuthenticatorActivity.java

private void finishLogin() {
    final Account account = new Account(mUsername, PARAM_ACCOUNT_TYPE);

    if (mRequestNewAccount) {
        mAccountManager.addAccountExplicitly(account, mPassword, null);

        Bundle bundle = new Bundle();
        ContentResolver.addPeriodicSync(account, TodoContentProvider.AUTHORITY, bundle, 300);

    } else {/*from ww w.jav  a  2 s.  com*/
        mAccountManager.setPassword(account, mPassword);
    }

    final Intent intent = new Intent();
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, PARAM_ACCOUNT_TYPE);

    if (mAuthTokenType != null && mAuthTokenType.equals(PARAM_AUTHTOKEN_TYPE)) {
        intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthToken);
    }

    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    finish();
}

From source file:info.semanticsoftware.semassist.android.activity.AuthenticationActivity.java

/** Sends an authentication request when the save button is pushed.
 * @param v view //from ww w. j a v  a2 s .  co m
 */
public void onSaveClick(View v) {
    TextView tvUsername = (TextView) this.findViewById(R.id.uc_txt_username);
    TextView tvPassword = (TextView) this.findViewById(R.id.uc_txt_password);

    //Qualified username, i.e, user@semanticassistants.com
    String qUsername = tvUsername.getText().toString();
    String username = null;
    if (qUsername.indexOf("@") > 0) {
        username = qUsername.substring(0, qUsername.indexOf("@"));
    } else {
        username = qUsername;
    }
    String password = tvPassword.getText().toString();

    //TODO do client-side validation like password length etc.
    String response = authenicate(username, password);
    if (!response.equals(Constants.AUTHENTICATION_FAIL)) {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        Editor editor = settings.edit();
        editor.putString("username", username);
        editor.putString("password", password);
        //FIXME replace this with a descent XML parser
        String acctype = "";
        int start = response.indexOf("<accType>");
        int end = response.indexOf("</accType>");
        if (start > -1 && end > -1) {
            acctype = response.substring(start + "<accType>".length(), end);
        }
        editor.putString("acctype", acctype);
        String sessionId = "";
        start = response.indexOf("<sessionId>");
        end = response.indexOf("</sessionId>");
        if (start > -1 && end > -1) {
            sessionId = response.substring(start + "<sessionId>".length(), end);
        }
        editor.putString("sessionId", sessionId);
        String reqNum = "";
        start = response.indexOf("<reqNum>");
        end = response.indexOf("</reqNum>");
        if (start > -1 && end > -1) {
            reqNum = response.substring(start + "<reqNum>".length(), end);
        }
        editor.putString("reqNum", reqNum);
        boolean result = editor.commit();
        if (result) {
            Toast.makeText(this, R.string.authenticationSuccess, Toast.LENGTH_LONG).show();
            String accountType = this.getIntent().getStringExtra("auth.token");
            if (accountType == null) {
                accountType = SemAssistAuthenticator.ACCOUNT_TYPE;
            }

            AccountManager accMgr = AccountManager.get(this);

            // Add the account to the Android Account Manager
            String accountName = username + "@semanticassistants.com";
            final Account account = new Account(accountName, accountType);
            accMgr.addAccountExplicitly(account, password, null);

            // Inform the caller (could be the Android Account Manager or the SA app) that the process was successful
            final Intent intent = new Intent();
            intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, accountName);
            intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType);
            intent.putExtra(AccountManager.KEY_AUTHTOKEN, accountType);
            this.setAccountAuthenticatorResult(intent.getExtras());
            this.setResult(RESULT_OK, intent);
            this.finish();
        } else {
            Toast.makeText(this, "Could not write the preferences.", Toast.LENGTH_LONG).show();
        }
    } else {
        Toast.makeText(this, R.string.authenticationFail, Toast.LENGTH_LONG).show();
    }
}

From source file:cn.code.notes.gtask.remote.GTaskClient.java

private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
    String authToken;//from  ww  w.j  a v a  2  s . com
    AccountManager accountManager = AccountManager.get(activity);
    Account[] accounts = accountManager.getAccountsByType("com.google");

    if (accounts.length == 0) {
        Log.e(TAG, "there is no available google account");
        return null;
    }

    String accountName = SystemEditActivity.getSyncAccountName(activity);
    Account account = null;
    for (Account a : accounts) {
        if (a.name.equals(accountName)) {
            account = a;
            break;
        }
    }
    if (account != null) {
        mAccount = account;
    } else {
        Log.e(TAG, "unable to get an account with the same name in the settings");
        return null;
    }

    // get the token now
    AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account, "goanna_mobile",
            null, activity, null, null);
    try {
        Bundle authTokenBundle = accountManagerFuture.getResult();
        authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
        if (invalidateToken) {
            accountManager.invalidateAuthToken("com.google", authToken);
            loginGoogleAccount(activity, false);
        }
    } catch (Exception e) {
        Log.e(TAG, "get auth token failed");
        authToken = null;
    }

    return authToken;
}

From source file:org.creativecommons.thelist.utils.ListUser.java

/**
 * Get auth token for existing account, if the account doesnt exist, create new CCID account
 * You must already have a valid ID// www  .  j  a va2  s.c  o  m
 */
public void getAuthed(final AuthCallback callback) {
    Log.d(TAG, "Getting session token");
    //sessionComplete = false;

    if (isTempUser()) {
        addNewAccount(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS,
                new AuthCallback() {
                    @Override
                    public void onSuccess(String authtoken) {
                        Log.v(TAG, "> getAuthed > addNewAccount token: " + authtoken);
                        callback.onSuccess(authtoken);
                    }
                });

    } else {
        Account account = getAccount();

        if (account == null) {
            Log.v(TAG, "getToken > getAccount > account is null");
            return;
        }

        am.getAuthToken(account, AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS, null, mActivity,
                new AccountManagerCallback<Bundle>() {
                    @Override
                    public void run(AccountManagerFuture<Bundle> future) {
                        try {
                            Bundle bundle = future.getResult();
                            String authtoken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                            Log.v(TAG, "> getAuthed > getAuthToken from existing account: " + authtoken);
                            callback.onSuccess(authtoken);
                        } catch (OperationCanceledException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (AuthenticatorException e) {
                            e.printStackTrace();
                        }
                    }
                }, null);
    }
}

From source file:com.example.simba.myapplicationnote.gtask.remote.GTaskClient.java

private String loginGoogleAccount(Activity activity, boolean invalidateToken) {
    String authToken;//from  w w  w.j ava 2 s  .  c om
    AccountManager accountManager = AccountManager.get(activity);
    Account[] accounts = accountManager.getAccountsByType("com.google");

    if (accounts.length == 0) {
        Log.e(TAG, "there is no available google account");
        return null;
    }

    String accountName = NotesPreferenceActivity.getSyncAccountName(activity);
    Account account = null;
    for (Account a : accounts) {
        if (a.name.equals(accountName)) {
            account = a;
            break;
        }
    }
    if (account != null) {
        mAccount = account;
    } else {
        Log.e(TAG, "unable to get an account with the same name in the settings");
        return null;
    }

    // get the token now
    AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account, "goanna_mobile",
            null, activity, null, null);
    try {
        Bundle authTokenBundle = accountManagerFuture.getResult();
        authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
        if (invalidateToken) {
            accountManager.invalidateAuthToken("com.google", authToken);
            loginGoogleAccount(activity, false);
        }
    } catch (Exception e) {
        Log.e(TAG, "get auth token failed");
        authToken = null;
    }

    return authToken;
}