Android Open Source - hubblog Login Activity






From Project

Back to project page hubblog.

License

The source code is released under:

MIT License

If you think the Android project hubblog listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package com.donskifarrell.Hubblog.Activities;
//from w ww  .  ja va 2 s  .com
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.*;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.donskifarrell.Hubblog.Activities.Dialogs.LightProgressDialog;
import com.github.mobile.Accounts.*;
import com.donskifarrell.Hubblog.R;
import com.github.rtyley.android.sherlock.roboguice.activity.RoboSherlockAccountAuthenticatorActivity;
import org.eclipse.egit.github.core.User;
import org.eclipse.egit.github.core.client.GitHubClient;
import org.eclipse.egit.github.core.service.OAuthService;
import org.eclipse.egit.github.core.service.UserService;
import roboguice.util.RoboAsyncTask;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.github.mobile.Accounts.AccountConstants.*;
import static android.accounts.AccountManager.KEY_ACCOUNT_NAME;
import static android.accounts.AccountManager.KEY_ACCOUNT_TYPE;
import static android.accounts.AccountManager.KEY_AUTHTOKEN;
import static android.accounts.AccountManager.KEY_BOOLEAN_RESULT;
import static android.content.Intent.ACTION_VIEW;
import static android.content.Intent.CATEGORY_BROWSABLE;
import static android.text.InputType.TYPE_CLASS_TEXT;
import static android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD;
import static android.text.InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
import static android.view.KeyEvent.ACTION_DOWN;
import static android.view.KeyEvent.KEYCODE_ENTER;
import static android.view.inputmethod.EditorInfo.IME_ACTION_DONE;



/**
 * Created with IntelliJ IDEA.
 * User: donski
 * Date: 10/12/13
 * Time: 17:23
 */
public class LoginActivity extends RoboSherlockAccountAuthenticatorActivity {

    /**
     * Exception sent back to calling Activity
     */
    public static final String PARAM_EXCEPTION = "exception";

    /**
     * Auth token type parameter
     */
    public static final String PARAM_AUTHTOKEN_TYPE = "authtokenType";

    /**
     * Initial user name
     */
    public static final String PARAM_USERNAME = "username";

    private static final String PARAM_CONFIRMCREDENTIALS = "confirmCredentials";

    private static final String TAG = "LoginActivity";

    /**
     * Request to enter two-factor authentication OTP code
     */
    private static final int OTP_CODE_ENTER = 13;

    /**
     * Sync period in seconds, currently every 8 hours
     */
    private static final long SYNC_PERIOD = 8L * 60L * 60L;

    /**
     * Two-factor authentication code header
     */
    protected static final String HEADER_OTP = "X-GitHub-OTP";

    /**
     * Two-factor authentication type by application
     */
    public static final int TWO_FACTOR_AUTH_TYPE_APP = 1001;

    /**
     * Two-factor authentication type by sms
     */
    public static final int TWO_FACTOR_AUTH_TYPE_SMS = 1002;

    public static void configureSyncFor(Account account) {
        Log.d(TAG, "Configuring account sync");

        ContentResolver.setIsSyncable(account, PROVIDER_AUTHORITY, 1);
        ContentResolver.setSyncAutomatically(account, PROVIDER_AUTHORITY, true);
        ContentResolver.addPeriodicSync(account, PROVIDER_AUTHORITY,
                new Bundle(), SYNC_PERIOD);
    }

/*    public static class AccountLoader extends
            AuthenticatedUserTask<List<User>> {

        @Inject
        private AccountDataManager cache;

        protected AccountLoader(Context context) {
            super(context);
        }

        @Override
        protected List<User> run(Account account) throws Exception {
            return cache.getOrgs(true);
        }
    }*/

    private AccountManager accountManager;

    private AutoCompleteTextView loginText;

    private EditText passwordText;

    private RoboAsyncTask<User> authenticationTask;

    private String authTokenType;

    private MenuItem loginItem;

    /**
     * If set we are just checking that the user knows their credentials; this
     * doesn't cause the user's password to be changed on the device.
     */
    private Boolean confirmCredentials = false;

    private String password;

    /**
     * Was the original caller asking for an entirely new account?
     */
    protected boolean requestNewAccount = false;

    private String username;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.login_layout);

        accountManager = AccountManager.get(this);

        loginText = (AutoCompleteTextView) findViewById(R.id.et_login);
        passwordText = (EditText) findViewById(R.id.et_password);

        final Intent intent = getIntent();
        username = intent.getStringExtra(PARAM_USERNAME);
        authTokenType = intent.getStringExtra(PARAM_AUTHTOKEN_TYPE);
        requestNewAccount = username == null;
        confirmCredentials = intent.getBooleanExtra(PARAM_CONFIRMCREDENTIALS,
                false);

        TextView signupText = (TextView) findViewById(R.id.tv_signup);
        signupText.setMovementMethod(LinkMovementMethod.getInstance());
        signupText.setText(Html.fromHtml(getString(R.string.signup_link)));

        if (!TextUtils.isEmpty(username)) {
            loginText.setText(username);
            loginText.setEnabled(false);
            loginText.setFocusable(false);
        }

        TextWatcher watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                updateEnablement();
            }
        };

        loginText.addTextChangedListener(watcher);
        passwordText.addTextChangedListener(watcher);

        passwordText.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event != null && ACTION_DOWN == event.getAction()
                        && keyCode == KEYCODE_ENTER && loginEnabled()) {
                    handleLogin();
                    return true;
                } else
                    return false;
            }
        });

        passwordText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == IME_ACTION_DONE && loginEnabled()) {
                    handleLogin();
                    return true;
                }
                return false;
            }
        });

        CheckBox showPassword = (CheckBox) findViewById(R.id.cb_show_password);
        showPassword.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                int type = TYPE_CLASS_TEXT;
                if (isChecked)
                    type |= TYPE_TEXT_VARIATION_VISIBLE_PASSWORD;
                else
                    type |= TYPE_TEXT_VARIATION_PASSWORD;
                int selection = passwordText.getSelectionStart();
                passwordText.setInputType(type);
                if (selection > 0)
                    passwordText.setSelection(selection);
            }
        });

        loginText.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line,
                getEmailAddresses()));
    }

    @Override
    protected void onResume() {
        super.onResume();

        // Finish task if valid account exists
        if (requestNewAccount) {
            Account existing = AccountUtils.getPasswordAccessibleAccount(this);
            if (existing != null && !TextUtils.isEmpty(existing.name)) {
                String password = AccountManager.get(this)
                        .getPassword(existing);
                if (!TextUtils.isEmpty(password))
                    finishLogin(existing.name, password);
            }
            return;
        }

        updateEnablement();
    }

    private boolean loginEnabled() {
        return !TextUtils.isEmpty(loginText.getText())
                && !TextUtils.isEmpty(passwordText.getText());
    }

    private void updateEnablement() {
        if (loginItem != null)
            loginItem.setEnabled(loginEnabled());
    }

    @Override
    public void startActivity(Intent intent) {
        if (intent != null && ACTION_VIEW.equals(intent.getAction()))
            intent.addCategory(CATEGORY_BROWSABLE);

        super.startActivity(intent);
    }

    /**
     * Authenticate login & password
     */
    public void handleLogin() {
        if (requestNewAccount)
            username = loginText.getText().toString();
        password = passwordText.getText().toString();

        final AlertDialog dialog = LightProgressDialog.create(this, R.string.login_activity_authenticating);
        dialog.setCancelable(true);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                if (authenticationTask != null)
                    authenticationTask.cancel(true);
            }
        });
        dialog.show();

        authenticationTask = new RoboAsyncTask<User>(this) {

            @Override
            public User call() throws Exception {
                GitHubClient client = new TwoFactorAuthClient();
                client.setCredentials(username, password);

                User user;
                try {
                    user = new UserService(client).getUser();
                } catch (TwoFactorAuthException e) {
                    if (e.twoFactorAuthType == TWO_FACTOR_AUTH_TYPE_SMS)
                        sendSmsOtpCode(new OAuthService(client));
                    openTwoFactorAuthActivity();

                    return null;
                }

                Account account = new Account(user.getLogin(), ACCOUNT_TYPE);
                if (requestNewAccount) {
                    accountManager
                            .addAccountExplicitly(account, password, null);
                    configureSyncFor(account);
/*                    try {
                        new AccountLoader(LoginActivity.this).call();
                    } catch (IOException e) {
                        Log.d(TAG, "Exception loading organizations", e);
                    }*/
                } else
                    accountManager.setPassword(account, password);

                return user;
            }

            @Override
            protected void onException(Exception e) throws RuntimeException {
                dialog.dismiss();

                Log.d(TAG, "Exception requesting authenticated user", e);
                handleLoginException(e);
            }

            @Override
            public void onSuccess(User user) {
                dialog.dismiss();

                if (user != null)
                    onAuthenticationResult(true);
            }
        };
        authenticationTask.execute();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == OTP_CODE_ENTER) {
            switch (resultCode) {
                case RESULT_OK:
                    onAuthenticationResult(true);
                    break;
                case RESULT_CANCELED:
                    Exception e = (Exception) data.getExtras().getSerializable(PARAM_EXCEPTION);
                    handleLoginException(e);
                    break;
            }
        }
    }

    /**
     * Called when response is received from the server for confirm credentials
     * request. See onAuthenticationResult(). Sets the
     * AccountAuthenticatorResult which is sent back to the caller.
     *
     * @param result
     */
    protected void finishConfirmCredentials(boolean result) {
        final Account account = new Account(username, ACCOUNT_TYPE);
        accountManager.setPassword(account, password);

        final Intent intent = new Intent();
        intent.putExtra(KEY_BOOLEAN_RESULT, result);
        setAccountAuthenticatorResult(intent.getExtras());
        setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * Called when response is received from the server for authentication
     * request. See onAuthenticationResult(). Sets the
     * AccountAuthenticatorResult which is sent back to the caller. Also sets
     * the authToken in AccountManager for this account.
     *
     * @param username
     * @param password
     */

    protected void finishLogin(final String username, final String password) {
        final Intent intent = new Intent();
        intent.putExtra(KEY_ACCOUNT_NAME, username);
        intent.putExtra(KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);
        if (ACCOUNT_TYPE.equals(authTokenType))
            intent.putExtra(KEY_AUTHTOKEN, password);
        setAccountAuthenticatorResult(intent.getExtras());
        setResult(RESULT_OK, intent);
        finish();
    }

    /**
     * Called when the authentication process completes (see attemptLogin()).
     *
     * @param result
     */
    public void onAuthenticationResult(boolean result) {
        if (result) {
            if (!confirmCredentials)
                finishLogin(username, password);
            else
                finishConfirmCredentials(true);
        } else {
/*            if (requestNewAccount)
                ToastUtils.show(this, R.string.invalid_login_or_password);
            else
                ToastUtils.show(this, R.string.invalid_password);*/
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
/*        switch (item.getItemId()) {
            case R.id.m_login:
                handleLogin();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }*/
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu optionMenu) {
/*        getSupportMenuInflater().inflate(menu.login, optionMenu);
        loginItem = optionMenu.findItem(R.id.m_login);*/
        return true;
    }

    private List<String> getEmailAddresses() {
        final Account[] accounts = accountManager
                .getAccountsByType("com.google");
        final List<String> addresses = new ArrayList<String>(accounts.length);
        for (Account account : accounts)
            addresses.add(account.name);
        return addresses;
    }

    private void sendSmsOtpCode(final OAuthService service) throws IOException {
        try {
            AccountAuthenticator.createAuthorization(service);
        } catch (TwoFactorAuthException ignored) {
        }
    }

    private void openTwoFactorAuthActivity() {
        Intent intent = TwoFactorAuthActivity.createIntent(this, username, password);
        startActivityForResult(intent, OTP_CODE_ENTER);
    }

    private void handleLoginException(final Exception e) {
        if (AccountUtils.isUnauthorized(e))
            onAuthenticationResult(false);
/*        else
            ToastUtils.show(LoginActivity.this, e, R.string.connection_failed);*/
    }
}




Java Source Code List

com.donskifarrell.Hubblog.BindingModule.java
com.donskifarrell.Hubblog.Activities.HubblogActivity.java
com.donskifarrell.Hubblog.Activities.LoginActivity.java
com.donskifarrell.Hubblog.Activities.StartupActivity.java
com.donskifarrell.Hubblog.Activities.Adapters.ArticleWebViewAdapter.java
com.donskifarrell.Hubblog.Activities.Adapters.ArticlesAdapter.java
com.donskifarrell.Hubblog.Activities.Adapters.MetadataAdapter.java
com.donskifarrell.Hubblog.Activities.Adapters.SidebarAdapter.java
com.donskifarrell.Hubblog.Activities.Adapters.TabsAdapter.java
com.donskifarrell.Hubblog.Activities.Dialogs.AboutDialogFragment.java
com.donskifarrell.Hubblog.Activities.Dialogs.AddSiteDialogFragment.java
com.donskifarrell.Hubblog.Activities.Dialogs.DeleteArticleDialogFragment.java
com.donskifarrell.Hubblog.Activities.Dialogs.EditArticleTitleDialogFragment.java
com.donskifarrell.Hubblog.Activities.Dialogs.LightAlertDialog.java
com.donskifarrell.Hubblog.Activities.Dialogs.LightProgressDialog.java
com.donskifarrell.Hubblog.Activities.Dialogs.NotificationDialogFragment.java
com.donskifarrell.Hubblog.Activities.Dialogs.SelectSiteDialogFragment.java
com.donskifarrell.Hubblog.Activities.Fragments.BasePageFragment.java
com.donskifarrell.Hubblog.Activities.Fragments.CommitArticleFragment.java
com.donskifarrell.Hubblog.Activities.Fragments.EditArticleFragment.java
com.donskifarrell.Hubblog.Activities.Fragments.EditMarkdownFragment.java
com.donskifarrell.Hubblog.Interfaces.ActivityDataListener.java
com.donskifarrell.Hubblog.Interfaces.ArticleWebViewJsInterface.java
com.donskifarrell.Hubblog.Interfaces.DataProvider.java
com.donskifarrell.Hubblog.Interfaces.DialogListener.java
com.donskifarrell.Hubblog.Interfaces.MetadataTagListener.java
com.donskifarrell.Hubblog.Interfaces.OnSidebarListItemSelected.java
com.donskifarrell.Hubblog.Providers.DatabaseHelper.java
com.donskifarrell.Hubblog.Providers.DatabaseProvider.java
com.donskifarrell.Hubblog.Providers.FileSystemProvider.java
com.donskifarrell.Hubblog.Providers.GitHubProvider.java
com.donskifarrell.Hubblog.Providers.HubblogDataProvider.java
com.donskifarrell.Hubblog.Providers.SharedPreferencesProvider.java
com.donskifarrell.Hubblog.Providers.Data.Account.java
com.donskifarrell.Hubblog.Providers.Data.Article.java
com.donskifarrell.Hubblog.Providers.Data.MetadataTag.java
com.donskifarrell.Hubblog.Providers.Data.Site.java
com.github.kevinsawicki.wishlist.ActivityUtils.java
com.github.kevinsawicki.wishlist.AsyncLoader.java
com.github.kevinsawicki.wishlist.CursorAdapter.java
com.github.kevinsawicki.wishlist.DatabaseHelper.java
com.github.kevinsawicki.wishlist.DecodeBitmapTask.java
com.github.kevinsawicki.wishlist.EditTextUtils.java
com.github.kevinsawicki.wishlist.Gestures.java
com.github.kevinsawicki.wishlist.ImageViewBitmapTask.java
com.github.kevinsawicki.wishlist.Keyboard.java
com.github.kevinsawicki.wishlist.LightDialog.java
com.github.kevinsawicki.wishlist.LocationUtils.java
com.github.kevinsawicki.wishlist.MultiTypeAdapter.java
com.github.kevinsawicki.wishlist.OnDoubleTapAdapter.java
com.github.kevinsawicki.wishlist.SectionFinder.java
com.github.kevinsawicki.wishlist.SectionMultiTypeAdapter.java
com.github.kevinsawicki.wishlist.SectionSingleTypeAdapter.java
com.github.kevinsawicki.wishlist.SingleTypeAdapter.java
com.github.kevinsawicki.wishlist.SingleTypeCursorAdapter.java
com.github.kevinsawicki.wishlist.Toaster.java
com.github.kevinsawicki.wishlist.TypeAdapter.java
com.github.kevinsawicki.wishlist.TypefaceUtils.java
com.github.kevinsawicki.wishlist.ViewFinder.java
com.github.kevinsawicki.wishlist.ViewUpdater.java
com.github.kevinsawicki.wishlist.ViewUtils.java
com.github.mobile.Accounts.AccountAuthenticatorService.java
com.github.mobile.Accounts.AccountAuthenticator.java
com.github.mobile.Accounts.AccountClient.java
com.github.mobile.Accounts.AccountConstants.java
com.github.mobile.Accounts.AccountScope.java
com.github.mobile.Accounts.AccountUtils.java
com.github.mobile.Accounts.AuthenticatedUserLoader.java
com.github.mobile.Accounts.AuthenticatedUserTask.java
com.github.mobile.Accounts.DefaultClient.java
com.github.mobile.Accounts.GitHubAccount.java
com.github.mobile.Accounts.ScopeBase.java
com.github.mobile.Accounts.TwoFactorAuthActivity.java
com.github.mobile.Accounts.TwoFactorAuthClient.java
com.github.mobile.Accounts.TwoFactorAuthException.java
com.github.mobile.Persistence.AccountDataManager.java
com.github.mobile.Persistence.CacheHelper.java
com.github.mobile.Persistence.DatabaseCache.java
com.github.mobile.Persistence.OrganizationLoader.java
com.github.mobile.Persistence.OrganizationRepositories.java
com.github.mobile.Persistence.Organizations.java
com.github.mobile.Persistence.PersistableResource.java
com.github.mobile.Requests.RequestCodes.java
com.github.mobile.Requests.RequestFuture.java
com.github.mobile.Requests.RequestReader.java
com.github.mobile.Requests.RequestWriter.java
com.github.mobile.Utils.IssueFilter.java
com.github.mobile.Utils.ToastUtils.java
com.github.mobile.Utils.UserComparator.java
com.viewpagerindicator.CirclePageIndicator.java
com.viewpagerindicator.IconPageIndicator.java
com.viewpagerindicator.IconPagerAdapter.java
com.viewpagerindicator.IcsLinearLayout.java
com.viewpagerindicator.LinePageIndicator.java
com.viewpagerindicator.PageIndicator.java
com.viewpagerindicator.TabPageIndicator.java
com.viewpagerindicator.TitlePageIndicator.java
com.viewpagerindicator.UnderlinePageIndicator.java