Android Open Source - sms-backup-plus Auth Preferences






From Project

Back to project page sms-backup-plus.

License

The source code is released under:

Apache License

If you think the Android project sms-backup-plus 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.zegoggles.smssync.preferences;
/*from  w w  w. jav a 2s . c o  m*/
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import com.fsck.k9.mail.AuthType;
import com.zegoggles.smssync.auth.TokenRefresher;
import com.zegoggles.smssync.auth.XOAuthConsumer;
import org.apache.commons.codec.binary.Base64;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Locale;

import static com.zegoggles.smssync.App.TAG;
import static com.zegoggles.smssync.preferences.ServerPreferences.Defaults.SERVER_PROTOCOL;

public class AuthPreferences {
    private final Context context;
    private final SharedPreferences preferences;
    private final ServerPreferences serverPreferences;

    public AuthPreferences(Context context) {
        this(context,  new ServerPreferences(context));
    }

    /* package */ AuthPreferences(Context context, ServerPreferences serverPreferences) {
        this.context = context.getApplicationContext();
        this.serverPreferences = serverPreferences;
        this.preferences =  PreferenceManager.getDefaultSharedPreferences(this.context);
    }

    /**
     * Preference key containing the Google account username.
     */
    public static final String LOGIN_USER = "login_user";
    /**
     * Preference key containing the Google account password.
     */
    public static final String LOGIN_PASSWORD = "login_password";
    public static final String SERVER_AUTHENTICATION = "server_authentication";
    private static final String OAUTH_TOKEN = "oauth_token";
    private static final String OAUTH_TOKEN_SECRET = "oauth_token_secret";
    private static final String OAUTH_USER = "oauth_user";
    private static final String OAUTH2_USER = "oauth2_user";
    private static final String OAUTH2_TOKEN = "oauth2_token";

    /**
     * IMAP URI.
     *
     * This should be in the form of:
     * <ol>
     * <li><code>imap+ssl+://XOAUTH2:ENCODED_USERNAME:ENCODED_TOKEN@imap.gmail.com:993</code></li>
     * <li><code>imap+ssl+://XOAUTH:ENCODED_USERNAME:ENCODED_TOKEN@imap.gmail.com:993</code></li>
     * <li><code>imap+ssl+://PLAIN:ENCODED_USERNAME:ENCODED_PASSWOR@imap.gmail.com:993</code></li>
     * <li><code>imap://PLAIN:ENCODED_USERNAME:ENCODED_PASSWOR@imap.gmail.com:993</code></li>
     * <li><code>imap://PLAIN:ENCODED_USERNAME:ENCODED_PASSWOR@imap.gmail.com</code></li>
     * </ol>
     */
    private static final String IMAP_URI = "imap%s://%s:%s:%s@%s";

    public XOAuthConsumer getOAuthConsumer() {
        return new XOAuthConsumer(
                getOauthUsername(),
                getOauthToken(),
                getOauthTokenSecret());
    }

    public String getOauth2Token() {
        return getCredentials().getString(OAUTH2_TOKEN, null);
    }

    public boolean hasOauthTokens() {
        return getOauthUsername() != null &&
                getOauthToken() != null &&
                getOauthTokenSecret() != null;
    }

    public boolean hasOAuth2Tokens() {
        return getOauth2Username() != null &&
                getOauth2Token() != null;
    }

    public String getUsername() {
        return preferences.getString(OAUTH_USER, getOauth2Username());
    }

    public void setOauthUsername(String s) {
        preferences.edit().putString(OAUTH_USER, s).commit();
    }

    public void setOauthTokens(String token, String secret) {
        getCredentials().edit()
                .putString(OAUTH_TOKEN, token)
                .putString(OAUTH_TOKEN_SECRET, secret)
                .commit();
    }

    public void setOauth2Token(String username, String token) {
        preferences.edit()
                .putString(OAUTH2_USER, username)
                .commit();

        getCredentials().edit()
                .putString(OAUTH2_TOKEN, token)
                .commit();
    }

   public void clearOauthData() {
        final String oauth2token = getOauth2Token();

        preferences.edit()
                .remove(OAUTH_USER)
                .remove(OAUTH2_USER)
                .commit();

        getCredentials().edit()
                .remove(OAUTH_TOKEN)
                .remove(OAUTH_TOKEN_SECRET)
                .remove(OAUTH2_TOKEN)
                .commit();

        if (!TextUtils.isEmpty(oauth2token)) {
            new TokenRefresher(context, this).invalidateToken(oauth2token);
        }
    }


    public void setImapPassword(String s) {
        getCredentials().edit().putString(LOGIN_PASSWORD, s).commit();
    }

    public void setImapUser(String s) {
        preferences.edit().putString(LOGIN_USER, s).commit();
    }

    public boolean useXOAuth() {
        return getAuthMode() == AuthMode.XOAUTH && serverPreferences.isGmail();
    }

    public String getUserEmail() {
        switch (getAuthMode()) {
            case XOAUTH:
                return getUsername();
            default:
                return getImapUsername();
        }
    }

    public boolean isLoginInformationSet() {
        switch (getAuthMode()) {
            case PLAIN:
                return !TextUtils.isEmpty(getImapPassword()) &&
                        !TextUtils.isEmpty(getImapUsername());
            case XOAUTH:
                return hasOauthTokens() || hasOAuth2Tokens();
            default:
                return false;
        }
    }

    public String getStoreUri() {
        if (useXOAuth()) {
            if (hasOauthTokens()) {
                XOAuthConsumer consumer = getOAuthConsumer();
                return formatUri(AuthType.XOAUTH, SERVER_PROTOCOL, consumer.getUsername(), consumer.generateXOAuthString());
            } else if (hasOAuth2Tokens()) {
                return formatUri(AuthType.XOAUTH2, SERVER_PROTOCOL, getOauth2Username(), generateXOAuth2Token());
            } else {
                Log.w(TAG, "No valid xoauth1/2 tokens");
                return null;
            }
        } else {
            return formatUri(AuthType.PLAIN,
                    serverPreferences.getServerProtocol(),
                    getImapUsername(),
                    getImapPassword());
        }
    }

    private String formatUri(AuthType authType, String serverProtocol, String username, String password) {
        return String.format(IMAP_URI,
                serverProtocol,
                authType.name().toUpperCase(Locale.US),
                // NB: there's a bug in K9mail-library which requires double-encoding of uris
                // https://github.com/k9mail/k-9/commit/b0d401c3b73c6b57402dc81d3cfd6488a71a1b98
                encode(encode(username)),
                encode(encode(password)),
                serverPreferences.getServerAddress());
    }

    private String getOauthTokenSecret() {
        return getCredentials().getString(OAUTH_TOKEN_SECRET, null);
    }

    private String getOauthToken() {
        return getCredentials().getString(OAUTH_TOKEN, null);
    }

    private String getOauthUsername() {
        return preferences.getString(OAUTH_USER, null);
    }

    private String getOauth2Username() {
        return preferences.getString(OAUTH2_USER, null);
    }

    private AuthMode getAuthMode() {
        return new Preferences(context).getDefaultType(SERVER_AUTHENTICATION, AuthMode.class, AuthMode.XOAUTH);
    }

    /* package */ void setServerAuthMode(AuthType authType) {
        preferences.edit().putString(AuthPreferences.SERVER_AUTHENTICATION, authType.name()).commit();
    }

    // All sensitive information is stored in a separate prefs file so we can
    // backup the rest without exposing sensitive data
    private SharedPreferences getCredentials() {
        return context.getSharedPreferences("credentials", Context.MODE_PRIVATE);
    }

    private String getImapUsername() {
        return preferences.getString(LOGIN_USER, null);
    }

    private String getImapPassword() {
        return getCredentials().getString(LOGIN_PASSWORD, null);
    }

    /**
     * TODO: this should probably be handled in K9
     *
     * <p>
     * The SASL XOAUTH2 initial client response has the following format:
     * </p>
     * <code>base64("user="{User}"^Aauth=Bearer "{Access Token}"^A^A")</code>
     * <p>
     * For example, before base64-encoding, the initial client response might look like this:
     * </p>
     * <code>user=someuser@example.com^Aauth=Bearer vF9dft4qmTc2Nvb3RlckBhdHRhdmlzdGEuY29tCg==^A^A</code>
     * <p/>
     * <em>Note:</em> ^A represents a Control+A (\001).
     *
     * @see <a href="https://developers.google.com/google-apps/gmail/xoauth2_protocol#the_sasl_xoauth2_mechanism">
     *      The SASL XOAUTH2 Mechanism</a>
     */
    private String generateXOAuth2Token() {
        final String username = getOauth2Username();
        final String token = getOauth2Token();
        final String formatted = "user=" + username + "\001auth=Bearer " + token + "\001\001";
        try {
            return new String(Base64.encodeBase64(formatted.getBytes("UTF-8")), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    private static String encode(String s) {
        try {
            return s == null ? "" : URLEncoder.encode(s, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}




Java Source Code List

com.zegoggles.smssync.App.java
com.zegoggles.smssync.Consts.java
com.zegoggles.smssync.MmsConsts.java
com.zegoggles.smssync.SmsConsts.java
com.zegoggles.smssync.activity.Dialogs.java
com.zegoggles.smssync.activity.MainActivity.java
com.zegoggles.smssync.activity.StatusPreference.java
com.zegoggles.smssync.activity.auth.AccountManagerAuthActivity.java
com.zegoggles.smssync.activity.auth.WebAuthActivity.java
com.zegoggles.smssync.activity.donation.DonationActivity.java
com.zegoggles.smssync.auth.TokenRefreshException.java
com.zegoggles.smssync.auth.TokenRefresher.java
com.zegoggles.smssync.auth.XOAuthConsumer.java
com.zegoggles.smssync.calendar.CalendarAccessorPost40.java
com.zegoggles.smssync.calendar.CalendarAccessorPre40.java
com.zegoggles.smssync.calendar.CalendarAccessor.java
com.zegoggles.smssync.compat.ComposeSmsActivity.java
com.zegoggles.smssync.compat.HeadlessSmsSendService.java
com.zegoggles.smssync.compat.MmsReceiver.java
com.zegoggles.smssync.compat.SmsReceiver.java
com.zegoggles.smssync.compat.package-info.java
com.zegoggles.smssync.contacts.ContactAccessorPost20.java
com.zegoggles.smssync.contacts.ContactAccessorPre20.java
com.zegoggles.smssync.contacts.ContactAccessor.java
com.zegoggles.smssync.contacts.ContactGroupIds.java
com.zegoggles.smssync.contacts.ContactGroup.java
com.zegoggles.smssync.contacts.Group.java
com.zegoggles.smssync.mail.AllTrustedSocketFactory.java
com.zegoggles.smssync.mail.Attachment.java
com.zegoggles.smssync.mail.BackupImapStore.java
com.zegoggles.smssync.mail.BackupStoreConfig.java
com.zegoggles.smssync.mail.CallFormatter.java
com.zegoggles.smssync.mail.ConversionResult.java
com.zegoggles.smssync.mail.DataType.java
com.zegoggles.smssync.mail.HeaderGenerator.java
com.zegoggles.smssync.mail.Headers.java
com.zegoggles.smssync.mail.MessageConverter.java
com.zegoggles.smssync.mail.MessageGenerator.java
com.zegoggles.smssync.mail.MmsSupport.java
com.zegoggles.smssync.mail.PersonLookup.java
com.zegoggles.smssync.mail.PersonRecord.java
com.zegoggles.smssync.preferences.AddressStyle.java
com.zegoggles.smssync.preferences.AuthMode.java
com.zegoggles.smssync.preferences.AuthPreferences.java
com.zegoggles.smssync.preferences.BackupManagerWrapper.java
com.zegoggles.smssync.preferences.CalendarPreferences.java
com.zegoggles.smssync.preferences.CallLogTypes.java
com.zegoggles.smssync.preferences.Defaults.java
com.zegoggles.smssync.preferences.MarkAsReadTypes.java
com.zegoggles.smssync.preferences.PreferenceBackupAgent.java
com.zegoggles.smssync.preferences.Preferences.java
com.zegoggles.smssync.preferences.ServerPreferences.java
com.zegoggles.smssync.receiver.BackupBroadcastReceiver.java
com.zegoggles.smssync.receiver.SmsBroadcastReceiver.java
com.zegoggles.smssync.service.Alarms.java
com.zegoggles.smssync.service.BackupConfig.java
com.zegoggles.smssync.service.BackupCursors.java
com.zegoggles.smssync.service.BackupItemsFetcher.java
com.zegoggles.smssync.service.BackupQueryBuilder.java
com.zegoggles.smssync.service.BackupTask.java
com.zegoggles.smssync.service.BackupType.java
com.zegoggles.smssync.service.BulkFetcher.java
com.zegoggles.smssync.service.CalendarSyncer.java
com.zegoggles.smssync.service.RestoreConfig.java
com.zegoggles.smssync.service.RestoreTask.java
com.zegoggles.smssync.service.ServiceBase.java
com.zegoggles.smssync.service.SmsBackupService.java
com.zegoggles.smssync.service.SmsRestoreService.java
com.zegoggles.smssync.service.UserCanceled.java
com.zegoggles.smssync.service.WhatsAppItemsFetcher.java
com.zegoggles.smssync.service.exception.BackupDisabledException.java
com.zegoggles.smssync.service.exception.ConnectivityException.java
com.zegoggles.smssync.service.exception.LocalizableException.java
com.zegoggles.smssync.service.exception.NoConnectionException.java
com.zegoggles.smssync.service.exception.RequiresBackgroundDataException.java
com.zegoggles.smssync.service.exception.RequiresLoginException.java
com.zegoggles.smssync.service.exception.RequiresWifiException.java
com.zegoggles.smssync.service.exception.SmsProviderNotWritableException.java
com.zegoggles.smssync.service.state.BackupState.java
com.zegoggles.smssync.service.state.RestoreState.java
com.zegoggles.smssync.service.state.SmsSyncState.java
com.zegoggles.smssync.service.state.State.java
com.zegoggles.smssync.tasks.OAuthCallbackTask.java
com.zegoggles.smssync.tasks.RequestTokenTask.java
com.zegoggles.smssync.utils.AppLog.java
com.zegoggles.smssync.utils.ListPreferenceHelper.java
com.zegoggles.smssync.utils.Sanitizer.java
com.zegoggles.smssync.utils.ThreadHelper.java