diff --git a/.gitignore b/.gitignore index 4327478..81e1e4d 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,7 @@ gen/ out/ build/ .idea/workspace.xml - +parse/ *.iws *.iml *.ipr diff --git a/accountAuthenticator/build.gradle b/accountAuthenticator/build.gradle index 312dba1..6900f1f 100644 --- a/accountAuthenticator/build.gradle +++ b/accountAuthenticator/build.gradle @@ -1,13 +1,13 @@ apply plugin: 'com.android.library' android { - compileSdkVersion 23 - buildToolsVersion "23.0.2" + compileSdkVersion 28 + buildToolsVersion "28.0.3" useLibrary 'org.apache.http.legacy' defaultConfig { - minSdkVersion 8 - targetSdkVersion 23 + minSdkVersion 26 + targetSdkVersion 28 } buildTypes { @@ -19,5 +19,8 @@ android { } dependencies { - compile 'com.google.code.gson:gson:2.4' + implementation 'com.google.code.gson:gson:2.8.2' + testImplementation 'junit:junit:4.12' + androidTestImplementation 'com.android.support:support-annotations:28.0.0' + androidTestImplementation 'com.android.support.test:runner:0.5' } diff --git a/accountAuthenticator/src/main/java/com/udinic/accounts_authenticator_example/authentication/AdvancedEncryptionStandard.java b/accountAuthenticator/src/main/java/com/udinic/accounts_authenticator_example/authentication/AdvancedEncryptionStandard.java new file mode 100644 index 0000000..e663f0b --- /dev/null +++ b/accountAuthenticator/src/main/java/com/udinic/accounts_authenticator_example/authentication/AdvancedEncryptionStandard.java @@ -0,0 +1,54 @@ +package com.udinic.accounts_authenticator_example.authentication; + +import java.util.Base64; + +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +//Taken from stackOverflow , phew + +public class AdvancedEncryptionStandard { + String key; + String initVector; + + public AdvancedEncryptionStandard(String key, String initVector) { + this.key = key; + this.initVector = initVector; + } + + public String encrypt(String value) { + try { + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); + IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8")); + + SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); + cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); + + byte[] encrypted = cipher.doFinal(value.getBytes()); + String s = new String(Base64.getEncoder().encode(encrypted)); + return s; + } catch (Exception ex) { + ex.printStackTrace(); + } + return null; + } + + public String decrypt(String encrypted) { + try { + IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8")); + SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES"); + + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); + cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); + + byte[] original = cipher.doFinal(Base64.getDecoder().decode(encrypted)); + + return new String(original); + } catch (Exception ex) { + ex.printStackTrace(); + } + + return null; + } +} \ No newline at end of file diff --git a/accountAuthenticator/src/main/java/com/udinic/accounts_authenticator_example/authentication/AuthenticatorActivity.java b/accountAuthenticator/src/main/java/com/udinic/accounts_authenticator_example/authentication/AuthenticatorActivity.java index d98b3e5..01170df 100644 --- a/accountAuthenticator/src/main/java/com/udinic/accounts_authenticator_example/authentication/AuthenticatorActivity.java +++ b/accountAuthenticator/src/main/java/com/udinic/accounts_authenticator_example/authentication/AuthenticatorActivity.java @@ -10,15 +10,18 @@ import android.view.View; import android.widget.TextView; import android.widget.Toast; + import com.udinic.accounts_authenticator_example.R; +import java.nio.charset.StandardCharsets; + import static com.udinic.accounts_authenticator_example.authentication.AccountGeneral.sServerAuthenticate; /** * The Authenticator activity. - * + *

* Called by the Authenticator and in charge of identifing the user. - * + *

* It sends back to the Authenticator the result. */ public class AuthenticatorActivity extends AccountAuthenticatorActivity { @@ -36,6 +39,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity { private final String TAG = this.getClass().getSimpleName(); + AdvancedEncryptionStandard advancedEncryptionStandard; private AccountManager mAccountManager; private String mAuthTokenType; @@ -45,6 +49,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + advancedEncryptionStandard = new AdvancedEncryptionStandard("Bar12345Bar12345", "RandomInitVector"); setContentView(R.layout.act_login); mAccountManager = AccountManager.get(getBaseContext()); @@ -54,7 +59,7 @@ public void onCreate(Bundle savedInstanceState) { mAuthTokenType = AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS; if (accountName != null) { - ((TextView)findViewById(R.id.accountName)).setText(accountName); + ((TextView) findViewById(R.id.accountName)).setText(accountName); } findViewById(R.id.submit).setOnClickListener(new View.OnClickListener() { @@ -130,29 +135,34 @@ protected void onPostExecute(Intent intent) { } private void finishLogin(Intent intent) { - Log.d("udinic", TAG + "> finishLogin"); - - String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME); - String accountPassword = intent.getStringExtra(PARAM_USER_PASS); - final Account account = new Account(accountName, intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE)); - - if (getIntent().getBooleanExtra(ARG_IS_ADDING_NEW_ACCOUNT, false)) { - Log.d("udinic", TAG + "> finishLogin > addAccountExplicitly"); - String authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN); - String authtokenType = mAuthTokenType; - - // Creating the account on the device and setting the auth token we got - // (Not setting the auth token will cause another call to the server to authenticate the user) - mAccountManager.addAccountExplicitly(account, accountPassword, null); - mAccountManager.setAuthToken(account, authtokenType, authtoken); - } else { - Log.d("udinic", TAG + "> finishLogin > setPassword"); - mAccountManager.setPassword(account, accountPassword); - } + try { + Log.d("udinic", TAG + "> finishLogin"); + + String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME); + String accountPassword = intent.getStringExtra(PARAM_USER_PASS); + final Account account = new Account(accountName, intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE)); + + if (getIntent().getBooleanExtra(ARG_IS_ADDING_NEW_ACCOUNT, false)) { + Log.d("udinic", TAG + "> finishLogin > addAccountExplicitly" + accountPassword); + String authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN); + String authtokenType = mAuthTokenType; + + Log.d("udinic", TAG + " auth token" + authtoken + " & encrypted auth tokens"); + // Creating the account on the device and setting the auth token we got + // (Not setting the auth token will cause another call to the server to authenticate the user) + mAccountManager.addAccountExplicitly(account, accountPassword, null); + mAccountManager.setAuthToken(account, authtokenType, advancedEncryptionStandard.encrypt(authtoken)); + } else { + Log.d("udinic", TAG + "> finishLogin > setPassword>" + accountPassword); + mAccountManager.setPassword(account, accountPassword); + } - setAccountAuthenticatorResult(intent.getExtras()); - setResult(RESULT_OK, intent); - finish(); + setAccountAuthenticatorResult(intent.getExtras()); + setResult(RESULT_OK, intent); + finish(); + } catch (Exception e) { + // + } } } diff --git a/accountAuthenticator/src/main/java/com/udinic/accounts_authenticator_example/authentication/Config.java b/accountAuthenticator/src/main/java/com/udinic/accounts_authenticator_example/authentication/Config.java new file mode 100644 index 0000000..853a704 --- /dev/null +++ b/accountAuthenticator/src/main/java/com/udinic/accounts_authenticator_example/authentication/Config.java @@ -0,0 +1,10 @@ +package com.udinic.accounts_authenticator_example.authentication; + +//Start a parse Server in heroku for running this example and add these values from the heroku server +// + +class Config { + static public String APP_ID = "myAppId"; + static public String APP_KEY = "myMasterKey"; + static public String URL = "https://applicationauthenticator.herokuapp.com"; +} diff --git a/accountAuthenticator/src/main/java/com/udinic/accounts_authenticator_example/authentication/ParseComServerAuthenticate.java b/accountAuthenticator/src/main/java/com/udinic/accounts_authenticator_example/authentication/ParseComServerAuthenticate.java index 8bacf59..1726e6a 100644 --- a/accountAuthenticator/src/main/java/com/udinic/accounts_authenticator_example/authentication/ParseComServerAuthenticate.java +++ b/accountAuthenticator/src/main/java/com/udinic/accounts_authenticator_example/authentication/ParseComServerAuthenticate.java @@ -1,58 +1,69 @@ package com.udinic.accounts_authenticator_example.authentication; +import android.net.Uri; import android.util.Log; + import com.google.gson.Gson; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.params.BasicHttpParams; -import org.apache.http.params.HttpParams; -import org.apache.http.util.EntityUtils; + +import org.json.JSONObject; + +import java.io.BufferedReader; import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; import java.io.Serializable; import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.URL; import java.net.URLEncoder; + /** * Handles the comminication with Parse.com - * + *

* User: udinic * Date: 3/27/13 * Time: 3:30 AM */ -public class ParseComServerAuthenticate implements ServerAuthenticate{ +public class ParseComServerAuthenticate implements ServerAuthenticate { @Override public String userSignUp(String name, String email, String pass, String authType) throws Exception { - String url = "https://api.parse.com/1/users"; - - DefaultHttpClient httpClient = new DefaultHttpClient(); - HttpPost httpPost = new HttpPost(url); - - httpPost.addHeader("X-Parse-Application-Id","XUafJTkPikD5XN5HxciweVuSe12gDgk2tzMltOhr"); - httpPost.addHeader("X-Parse-REST-API-Key", "8L9yTQ3M86O4iiucwWb4JS7HkxoSKo7ssJqGChWx"); - httpPost.addHeader("Content-Type", "application/json"); - - String user = "{\"username\":\"" + email + "\",\"password\":\"" + pass + "\",\"phone\":\"415-392-0202\"}"; - HttpEntity entity = new StringEntity(user); - httpPost.setEntity(entity); - + //https://api.parse.com/1/users + URL url = new URL(Config.URL + "/parse/users"); + HttpURLConnection httpClient = (HttpURLConnection) url.openConnection(); + + httpClient.addRequestProperty("X-Parse-Application-Id", Config.APP_ID); + httpClient.addRequestProperty("X-Parse-REST-API-Key", Config.APP_KEY); + httpClient.addRequestProperty("Content-Type", "application/json"); + httpClient.setRequestMethod("POST"); + JSONObject params = new JSONObject(); + params.put("username", email); + params.put("password", pass); + params.put("phone", "999-999-9999"); + OutputStreamWriter wr = new OutputStreamWriter(httpClient.getOutputStream()); + wr.write(params.toString()); + wr.flush(); String authtoken = null; try { - HttpResponse response = httpClient.execute(httpPost); - String responseString = EntityUtils.toString(response.getEntity()); + String responseString = httpClient.getResponseMessage(); - if (response.getStatusLine().getStatusCode() != 201) { + if (httpClient.getResponseCode() != 201) { ParseComError error = new Gson().fromJson(responseString, ParseComError.class); - throw new Exception("Error creating user["+error.code+"] - " + error.error); + throw new Exception(responseString); } + BufferedReader in = new BufferedReader( + new InputStreamReader(httpClient.getInputStream())); + String inputLine; + StringBuffer response = new StringBuffer(); - User createdUser = new Gson().fromJson(responseString, User.class); + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + User createdUser = new Gson().fromJson(response.toString(), User.class); authtoken = createdUser.sessionToken; @@ -68,9 +79,8 @@ public String userSignIn(String user, String pass, String authType) throws Excep Log.d("udini", "userSignIn"); - DefaultHttpClient httpClient = new DefaultHttpClient(); - String url = "https://api.parse.com/1/login"; - + //https://api.parse.com/1/ + String tUrl = Config.URL + "/parse/login"; String query = null; try { @@ -78,30 +88,36 @@ public String userSignIn(String user, String pass, String authType) throws Excep } catch (UnsupportedEncodingException e) { e.printStackTrace(); } - url += "?" + query; + tUrl += "?" + query; + + URL url = new URL(tUrl); - HttpGet httpGet = new HttpGet(url); + HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection(); + httpURLConnection.setRequestMethod("GET"); - httpGet.addHeader("X-Parse-Application-Id", "XUafJTkPikD5XN5HxciweVuSe12gDgk2tzMltOhr"); - httpGet.addHeader("X-Parse-REST-API-Key", "8L9yTQ3M86O4iiucwWb4JS7HkxoSKo7ssJqGChWx"); + httpURLConnection.setRequestProperty("X-Parse-Application-Id", Config.APP_ID); + httpURLConnection.setRequestProperty("X-Parse-REST-API-Key", Config.APP_KEY); - HttpParams params = new BasicHttpParams(); - params.setParameter("username", user); - params.setParameter("password", pass); - httpGet.setParams(params); -// httpGet.getParams().setParameter("username", user).setParameter("password", pass); String authtoken = null; try { - HttpResponse response = httpClient.execute(httpGet); - String responseString = EntityUtils.toString(response.getEntity()); - if (response.getStatusLine().getStatusCode() != 200) { - ParseComError error = new Gson().fromJson(responseString, ParseComError.class); - throw new Exception("Error signing-in ["+error.code+"] - " + error.error); + String responseString = httpURLConnection.getResponseMessage(); + Log.d("here", responseString); + if (httpURLConnection.getResponseCode() != 200) { + //ParseComError error = new Gson().fromJson(httpURLConnection.getResponseMessage(), ParseComError.class); + throw new Exception(responseString); } + BufferedReader in = new BufferedReader( + new InputStreamReader(httpURLConnection.getInputStream())); + String inputLine; + StringBuffer response = new StringBuffer(); - User loggedUser = new Gson().fromJson(responseString, User.class); + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + in.close(); + User loggedUser = new Gson().fromJson(response.toString(), User.class); authtoken = loggedUser.sessionToken; } catch (IOException e) { @@ -116,6 +132,7 @@ private class ParseComError implements Serializable { int code; String error; } + private class User implements Serializable { private String firstName; diff --git a/accountAuthenticator/src/main/java/com/udinic/accounts_authenticator_example/authentication/UdinicAuthenticator.java b/accountAuthenticator/src/main/java/com/udinic/accounts_authenticator_example/authentication/UdinicAuthenticator.java index 9850a74..d75f3aa 100644 --- a/accountAuthenticator/src/main/java/com/udinic/accounts_authenticator_example/authentication/UdinicAuthenticator.java +++ b/accountAuthenticator/src/main/java/com/udinic/accounts_authenticator_example/authentication/UdinicAuthenticator.java @@ -7,6 +7,8 @@ import android.text.TextUtils; import android.util.Log; +import java.nio.charset.StandardCharsets; + import static android.accounts.AccountManager.KEY_BOOLEAN_RESULT; import static com.udinic.accounts_authenticator_example.authentication.AccountGeneral.*; @@ -20,12 +22,15 @@ public class UdinicAuthenticator extends AbstractAccountAuthenticator { private String TAG = "UdinicAuthenticator"; private final Context mContext; + AdvancedEncryptionStandard advancedEncryptionStandard; + private AccountManager mAccountManager; public UdinicAuthenticator(Context context) { super(context); - + advancedEncryptionStandard = new AdvancedEncryptionStandard("Bar12345Bar12345", "RandomInitVector"); // I hate you! Google - set mContext as protected! this.mContext = context; + mAccountManager = AccountManager.get(context); } @Override @@ -48,55 +53,66 @@ public Bundle getAuthToken(AccountAuthenticatorResponse response, Account accoun Log.d("udinic", TAG + "> getAuthToken"); - // If the caller requested an authToken type we don't support, then - // return an error - if (!authTokenType.equals(AccountGeneral.AUTHTOKEN_TYPE_READ_ONLY) && !authTokenType.equals(AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS)) { - final Bundle result = new Bundle(); - result.putString(AccountManager.KEY_ERROR_MESSAGE, "invalid authTokenType"); - return result; - } + try { + // If the caller requested an authToken type we don't support, then + // return an error + if (!authTokenType.equals(AccountGeneral.AUTHTOKEN_TYPE_READ_ONLY) && !authTokenType.equals(AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS)) { + final Bundle result = new Bundle(); + result.putString(AccountManager.KEY_ERROR_MESSAGE, "invalid authTokenType"); + return result; + } + + // Extract the username and password from the Account Manager, and ask + // the server for an appropriate AuthToken. + final AccountManager am = AccountManager.get(mContext); + Log.d("udinic", TAG + "> peekAuthToken returned - "); - // 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); - String authToken = am.peekAuthToken(account, authTokenType); - Log.d("udinic", TAG + "> peekAuthToken returned - " + authToken); + // Lets give another try to authenticate the user + if (authToken == null || TextUtils.isEmpty(authToken)) { + final String password = am.getPassword(account); + if (password != null) { + try { - // Lets give another try to authenticate the user - if (TextUtils.isEmpty(authToken)) { - final String password = am.getPassword(account); - if (password != null) { - try { - Log.d("udinic", TAG + "> re-authenticating with the existing password"); - authToken = sServerAuthenticate.userSignIn(account.name, password, authTokenType); - } catch (Exception e) { - e.printStackTrace(); + authToken = advancedEncryptionStandard.encrypt(sServerAuthenticate.userSignIn(account.name, password, authTokenType)); + mAccountManager.setAuthToken(account, authTokenType, authToken); + + //final Bundle result = new Bundle(); + Log.d("udinic", TAG + "> re-authenticating with the existing password" + authToken); + } catch (Exception e) { + e.printStackTrace(); + } } } - } - // If we get an authToken - we return it - if (!TextUtils.isEmpty(authToken)) { + // 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, advancedEncryptionStandard.decrypt(authToken)); + 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, AuthenticatorActivity.class); + intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response); + intent.putExtra(AuthenticatorActivity.ARG_ACCOUNT_TYPE, account.type); + intent.putExtra(AuthenticatorActivity.ARG_AUTH_TYPE, authTokenType); + intent.putExtra(AuthenticatorActivity.ARG_ACCOUNT_NAME, account.name); + final Bundle bundle = new Bundle(); + bundle.putParcelable(AccountManager.KEY_INTENT, intent); + return bundle; + } catch (Exception e) { + e.printStackTrace(); 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); + result.putString(AccountManager.KEY_ERROR_MESSAGE, "invalid authTokenType"); 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, AuthenticatorActivity.class); - intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response); - intent.putExtra(AuthenticatorActivity.ARG_ACCOUNT_TYPE, account.type); - intent.putExtra(AuthenticatorActivity.ARG_AUTH_TYPE, authTokenType); - intent.putExtra(AuthenticatorActivity.ARG_ACCOUNT_NAME, account.name); - final Bundle bundle = new Bundle(); - bundle.putParcelable(AccountManager.KEY_INTENT, intent); - return bundle; } diff --git a/accountAuthenticator/src/main/res/layout/act_login.xml b/accountAuthenticator/src/main/res/layout/act_login.xml index 9a9a44d..443d8a8 100644 --- a/accountAuthenticator/src/main/res/layout/act_login.xml +++ b/accountAuthenticator/src/main/res/layout/act_login.xml @@ -3,7 +3,6 @@ android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" - android:background="#000000" android:paddingLeft="17dp" android:paddingRight="17dp" > diff --git a/accountAuthenticator/src/main/res/layout/act_register.xml b/accountAuthenticator/src/main/res/layout/act_register.xml index a93bea2..96a6f40 100644 --- a/accountAuthenticator/src/main/res/layout/act_register.xml +++ b/accountAuthenticator/src/main/res/layout/act_register.xml @@ -3,7 +3,6 @@ android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" - android:background="#000000" android:paddingLeft="17dp" android:paddingRight="17dp" > diff --git a/build.gradle b/build.gradle index 349f446..5f78a45 100644 --- a/build.gradle +++ b/build.gradle @@ -1,15 +1,19 @@ // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { + google() jcenter() + maven { url "https://jitpack.io" } } dependencies { - classpath 'com.android.tools.build:gradle:1.3.1' + classpath 'com.android.tools.build:gradle:3.3.2' } } allprojects { repositories { + google() jcenter() + maven { url "https://jitpack.io" } } } diff --git a/exampleApp/build.gradle b/exampleApp/build.gradle index 7226912..97de4df 100644 --- a/exampleApp/build.gradle +++ b/exampleApp/build.gradle @@ -1,13 +1,12 @@ apply plugin: 'com.android.application' android { - compileSdkVersion 23 - buildToolsVersion "23.0.2" + compileSdkVersion 28 defaultConfig { applicationId "com.udinic.accounts_example" - minSdkVersion 8 - targetSdkVersion 23 + minSdkVersion 26 + targetSdkVersion 28 } buildTypes { @@ -19,5 +18,5 @@ android { } dependencies { - compile project(':accountAuthenticator') + api project(':accountAuthenticator') } diff --git a/exampleApp/src/main/java/com/udinic/accounts_example/Main1.java b/exampleApp/src/main/java/com/udinic/accounts_example/Main1.java index f120d08..5f027a8 100644 --- a/exampleApp/src/main/java/com/udinic/accounts_example/Main1.java +++ b/exampleApp/src/main/java/com/udinic/accounts_example/Main1.java @@ -1,6 +1,7 @@ package com.udinic.accounts_example; import static com.udinic.accounts_authenticator_example.authentication.AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS; + import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; @@ -17,16 +18,20 @@ import com.udinic.accounts_authenticator_example.authentication.AccountGeneral; + /** * Created with IntelliJ IDEA. * User: Udini * Date: 21/03/13 * Time: 13:50 + * + * Edited by Karan Goel + * Date: 13/03/19 */ public class Main1 extends Activity { - - private static final String STATE_DIALOG = "state_dialog"; - private static final String STATE_INVALIDATE = "state_invalidate"; + + private static final String STATE_DIALOG = "state_dialog"; + private static final String STATE_INVALIDATE = "state_invalidate"; private String TAG = this.getClass().getSimpleName(); private AccountManager mAccountManager; @@ -66,28 +71,29 @@ public void onClick(View v) { showAccountPicker(AUTHTOKEN_TYPE_FULL_ACCESS, true); } }); - + if (savedInstanceState != null) { - boolean showDialog = savedInstanceState.getBoolean(STATE_DIALOG); - boolean invalidate = savedInstanceState.getBoolean(STATE_INVALIDATE); - if (showDialog) { - showAccountPicker(AUTHTOKEN_TYPE_FULL_ACCESS, invalidate); - } + boolean showDialog = savedInstanceState.getBoolean(STATE_DIALOG); + boolean invalidate = savedInstanceState.getBoolean(STATE_INVALIDATE); + if (showDialog) { + showAccountPicker(AUTHTOKEN_TYPE_FULL_ACCESS, invalidate); + } } } - + @Override protected void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - if (mAlertDialog != null && mAlertDialog.isShowing()) { - outState.putBoolean(STATE_DIALOG, true); - outState.putBoolean(STATE_INVALIDATE, mInvalidate); - } + super.onSaveInstanceState(outState); + if (mAlertDialog != null && mAlertDialog.isShowing()) { + outState.putBoolean(STATE_DIALOG, true); + outState.putBoolean(STATE_INVALIDATE, mInvalidate); + } } /** * Add new account to the account manager + * * @param accountType * @param authTokenType */ @@ -110,10 +116,11 @@ public void run(AccountManagerFuture future) { /** * Show all the accounts registered on the account manager. Request an auth token upon user select. + * * @param authTokenType */ private void showAccountPicker(final String authTokenType, final boolean invalidate) { - mInvalidate = invalidate; + mInvalidate = invalidate; final Account availableAccounts[] = mAccountManager.getAccountsByType(AccountGeneral.ACCOUNT_TYPE); if (availableAccounts.length == 0) { @@ -128,7 +135,7 @@ private void showAccountPicker(final String authTokenType, final boolean invalid mAlertDialog = new AlertDialog.Builder(this).setTitle("Pick Account").setAdapter(new ArrayAdapter(getBaseContext(), android.R.layout.simple_list_item_1, name), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - if(invalidate) + if (invalidate) invalidateAuthToken(availableAccounts[which], authTokenType); else getExistingAccountAuthToken(availableAccounts[which], authTokenType); @@ -140,6 +147,7 @@ public void onClick(DialogInterface dialog, int which) { /** * Get the auth token for an existing account on the AccountManager + * * @param account * @param authTokenType */ @@ -165,11 +173,12 @@ public void run() { /** * Invalidates the auth token for the account + * * @param account * @param authTokenType */ private void invalidateAuthToken(final Account account, String authTokenType) { - final AccountManagerFuture future = mAccountManager.getAuthToken(account, authTokenType, null, this, null,null); + final AccountManagerFuture future = mAccountManager.getAuthToken(account, authTokenType, null, this, null, null); new Thread(new Runnable() { @Override @@ -193,6 +202,7 @@ public void run() { * If not exist - add it and then return its auth token. * If one exist - return its auth token. * If more than one exists - show a picker and return the select account's auth token. + * * @param accountType * @param authTokenType */ @@ -214,11 +224,11 @@ public void run(AccountManagerFuture future) { } } } - , null); + , null); } private void showMessage(final String msg) { - if (TextUtils.isEmpty(msg)) + if (TextUtils.isEmpty(msg)) return; runOnUiThread(new Runnable() { diff --git a/exampleApp2/build.gradle b/exampleApp2/build.gradle index 729b285..575ec6a 100644 --- a/exampleApp2/build.gradle +++ b/exampleApp2/build.gradle @@ -1,13 +1,12 @@ apply plugin: 'com.android.application' android { - compileSdkVersion 23 - buildToolsVersion "23.0.2" + compileSdkVersion 28 defaultConfig { applicationId "com.udinic.accounts_example2" - minSdkVersion 8 - targetSdkVersion 23 + minSdkVersion 26 + targetSdkVersion 28 } buildTypes { @@ -19,5 +18,5 @@ android { } dependencies { - compile project(':accountAuthenticator') + api project(':accountAuthenticator') } diff --git a/exampleApp2/src/main/java/com/udinic/accounts_example2/Main2.java b/exampleApp2/src/main/java/com/udinic/accounts_example2/Main2.java index 8dc3e8c..217be91 100644 --- a/exampleApp2/src/main/java/com/udinic/accounts_example2/Main2.java +++ b/exampleApp2/src/main/java/com/udinic/accounts_example2/Main2.java @@ -1,6 +1,7 @@ package com.udinic.accounts_example2; import static com.udinic.accounts_authenticator_example.authentication.AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS; + import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; @@ -24,9 +25,9 @@ * Time: 13:50 */ public class Main2 extends Activity { - - private static final String STATE_DIALOG = "state_dialog"; - private static final String STATE_INVALIDATE = "state_invalidate"; + + private static final String STATE_DIALOG = "state_dialog"; + private static final String STATE_INVALIDATE = "state_invalidate"; private String TAG = this.getClass().getSimpleName(); private AccountManager mAccountManager; @@ -66,28 +67,29 @@ public void onClick(View v) { showAccountPicker(AUTHTOKEN_TYPE_FULL_ACCESS, true); } }); - + if (savedInstanceState != null) { - boolean showDialog = savedInstanceState.getBoolean(STATE_DIALOG); - boolean invalidate = savedInstanceState.getBoolean(STATE_INVALIDATE); - if (showDialog) { - showAccountPicker(AUTHTOKEN_TYPE_FULL_ACCESS, invalidate); - } + boolean showDialog = savedInstanceState.getBoolean(STATE_DIALOG); + boolean invalidate = savedInstanceState.getBoolean(STATE_INVALIDATE); + if (showDialog) { + showAccountPicker(AUTHTOKEN_TYPE_FULL_ACCESS, invalidate); + } } } - + @Override protected void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - if (mAlertDialog != null && mAlertDialog.isShowing()) { - outState.putBoolean(STATE_DIALOG, true); - outState.putBoolean(STATE_INVALIDATE, mInvalidate); - } + super.onSaveInstanceState(outState); + if (mAlertDialog != null && mAlertDialog.isShowing()) { + outState.putBoolean(STATE_DIALOG, true); + outState.putBoolean(STATE_INVALIDATE, mInvalidate); + } } /** * Add new account to the account manager + * * @param accountType * @param authTokenType */ @@ -110,10 +112,11 @@ public void run(AccountManagerFuture future) { /** * Show all the accounts registered on the account manager. Request an auth token upon user select. + * * @param authTokenType */ private void showAccountPicker(final String authTokenType, final boolean invalidate) { - mInvalidate = invalidate; + mInvalidate = invalidate; final Account availableAccounts[] = mAccountManager.getAccountsByType(AccountGeneral.ACCOUNT_TYPE); if (availableAccounts.length == 0) { @@ -128,7 +131,7 @@ private void showAccountPicker(final String authTokenType, final boolean invalid mAlertDialog = new AlertDialog.Builder(this).setTitle("Pick Account").setAdapter(new ArrayAdapter(getBaseContext(), android.R.layout.simple_list_item_1, name), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { - if(invalidate) + if (invalidate) invalidateAuthToken(availableAccounts[which], authTokenType); else getExistingAccountAuthToken(availableAccounts[which], authTokenType); @@ -140,6 +143,7 @@ public void onClick(DialogInterface dialog, int which) { /** * Get the auth token for an existing account on the AccountManager + * * @param account * @param authTokenType */ @@ -165,11 +169,12 @@ public void run() { /** * Invalidates the auth token for the account + * * @param account * @param authTokenType */ private void invalidateAuthToken(final Account account, String authTokenType) { - final AccountManagerFuture future = mAccountManager.getAuthToken(account, authTokenType, null, this, null,null); + final AccountManagerFuture future = mAccountManager.getAuthToken(account, authTokenType, null, this, null, null); new Thread(new Runnable() { @Override @@ -193,6 +198,7 @@ public void run() { * If not exist - add it and then return its auth token. * If one exist - return its auth token. * If more than one exists - show a picker and return the select account's auth token. + * * @param accountType * @param authTokenType */ @@ -218,7 +224,7 @@ public void run(AccountManagerFuture future) { } private void showMessage(final String msg) { - if (TextUtils.isEmpty(msg)) + if (TextUtils.isEmpty(msg)) return; runOnUiThread(new Runnable() { diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index f23df6e..1e014f4 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.8-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.3-all.zip