From 50c044c1b04021f044bc954274c198653c6b3902 Mon Sep 17 00:00:00 2001 From: Eugene Crosser Date: Wed, 1 Feb 2012 18:01:06 +0400 Subject: [PATCH] Implement OAuth2 authorization --- AndroidManifest.xml | 3 + res/menu/main_menu.xml | 3 + res/values/strings.xml | 1 + src/org/average/whereami/Authorize.java | 127 ++++++++++++++++++++++++ src/org/average/whereami/Location.java | 3 + src/org/average/whereami/PhoneLog.java | 3 + src/org/average/whereami/WhereAmI.java | 36 ++++--- 7 files changed, 161 insertions(+), 15 deletions(-) create mode 100644 src/org/average/whereami/Authorize.java diff --git a/AndroidManifest.xml b/AndroidManifest.xml index ebf9383..5ec0334 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -17,6 +17,9 @@ + + diff --git a/res/menu/main_menu.xml b/res/menu/main_menu.xml index 6fd0da1..3c056cb 100644 --- a/res/menu/main_menu.xml +++ b/res/menu/main_menu.xml @@ -3,6 +3,9 @@ + diff --git a/res/values/strings.xml b/res/values/strings.xml index 5d80321..4835bca 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -8,6 +8,7 @@ Последнее обновление Неудачная попытка Выход + Авторизация Конфигурация Полный экран Полный экран или с индикаторами diff --git a/src/org/average/whereami/Authorize.java b/src/org/average/whereami/Authorize.java new file mode 100644 index 0000000..1bf5fad --- /dev/null +++ b/src/org/average/whereami/Authorize.java @@ -0,0 +1,127 @@ +// http://blog.doityourselfandroid.com/2011/08/06/oauth-2-0-flow-android/ +// http://code.google.com/p/google-api-java-client/wiki/OAuth2Draft10 + +package org.average.whereami; + +import java.io.IOException; + +import org.average.whereami.ClientCredentials; + +import android.app.Activity; +import android.os.Bundle; +import android.graphics.Bitmap; +import android.content.Intent; +import android.content.SharedPreferences; +import android.content.SharedPreferences.Editor; +import android.preference.PreferenceManager; +import android.util.Log; +import android.view.View; +import android.webkit.WebView; +import android.webkit.WebViewClient; + +import com.google.api.client.auth.oauth2.draft10.AccessTokenResponse; +import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessTokenRequest.GoogleAuthorizationCodeGrant; +import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAuthorizationRequestUrl; +import com.google.api.client.http.javanet.NetHttpTransport; +import com.google.api.client.json.jackson.JacksonFactory; + +public class Authorize extends Activity { + + final String TAG = getClass().getName(); + + private SharedPreferences prefs; + private static final String ACCESS_TOKEN = "access_token"; + private static final String EXPIRES_IN = "expires_in"; + private static final String REFRESH_TOKEN = "refresh_token"; + private static final String SCOPE = "scope"; + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + Log.w(TAG, "Starting task to retrieve request token."); + prefs = PreferenceManager.getDefaultSharedPreferences(this); + } + + @Override + protected void onResume() { + super.onResume(); + WebView webview = new WebView(this); + webview.getSettings().setJavaScriptEnabled(true); + webview.setVisibility(View.VISIBLE); + setContentView(webview); + String authorizationUrl = new GoogleAuthorizationRequestUrl( + ClientCredentials.CLIENT_ID, + ClientCredentials.REDIRECT_URI, + ClientCredentials.SCOPE).build(); + webview.setWebViewClient(new WebViewClient() { + @Override + public void onPageStarted(WebView view, String url, Bitmap bitmap) { + Log.w(TAG, "onPageStarted : " + url); + } + @Override + public void onPageFinished(WebView view, String url) { + if (url.startsWith(ClientCredentials.REDIRECT_URI)) { + try { + if (url.indexOf("code=")!=-1) { + String code = extractCodeFromUrl(url); + AccessTokenResponse accessTokenResponse = + new GoogleAuthorizationCodeGrant( + new NetHttpTransport(), + new JacksonFactory(), + ClientCredentials.CLIENT_ID, + ClientCredentials.CLIENT_SECRET, + code, + ClientCredentials.REDIRECT_URI).execute(); + storeTokens(accessTokenResponse); + finish(); + //view.setVisibility(View.INVISIBLE); + //startActivity(new Intent(Authorize.this, + // WhereAmI.class)); + } else if (url.indexOf("error=")!=-1) { + clearTokens(); + finish(); + //view.setVisibility(View.INVISIBLE); + //startActivity(new Intent(Authorize.this, + // WhereAmI.class)); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + Log.w(TAG, "onPageFinished : " + url); + } + + private String extractCodeFromUrl(String url) { + return url.substring( + ClientCredentials.REDIRECT_URI.length()+7, + url.length()); + } + + private void storeTokens(AccessTokenResponse accessTokenResponse) { + Log.w(TAG, "Storing tokens: " + accessTokenResponse); + Editor editor = prefs.edit(); + editor.putString(ACCESS_TOKEN, + accessTokenResponse.accessToken); + editor.putLong( EXPIRES_IN, + accessTokenResponse.expiresIn); + editor.putString(REFRESH_TOKEN, + accessTokenResponse.refreshToken); + editor.putString(SCOPE, + accessTokenResponse.scope); + editor.commit(); + } + + private void clearTokens() { + Log.w(TAG, "Clear tokens"); + Editor editor = prefs.edit(); + editor.remove(ACCESS_TOKEN); + editor.remove(EXPIRES_IN); + editor.remove(REFRESH_TOKEN); + editor.remove(SCOPE); + editor.commit(); + } + }); + + webview.loadUrl(authorizationUrl); + } +} diff --git a/src/org/average/whereami/Location.java b/src/org/average/whereami/Location.java index 9f588b3..da9d6fb 100644 --- a/src/org/average/whereami/Location.java +++ b/src/org/average/whereami/Location.java @@ -12,6 +12,9 @@ import android.util.Log; import android.os.SystemClock; public final class Location extends Oracle { + + final String TAG = getClass().getName(); + @Override public final String getResult() { SystemClock.sleep(6000); diff --git a/src/org/average/whereami/PhoneLog.java b/src/org/average/whereami/PhoneLog.java index 0d99cbb..cf157a4 100644 --- a/src/org/average/whereami/PhoneLog.java +++ b/src/org/average/whereami/PhoneLog.java @@ -19,6 +19,9 @@ import android.util.Log; import android.os.SystemClock; public final class PhoneLog extends Oracle { + + final String TAG = getClass().getName(); + @Override public final String getResult() { SystemClock.sleep(5000); diff --git a/src/org/average/whereami/WhereAmI.java b/src/org/average/whereami/WhereAmI.java index 953fcc9..16d1125 100644 --- a/src/org/average/whereami/WhereAmI.java +++ b/src/org/average/whereami/WhereAmI.java @@ -31,6 +31,8 @@ import android.widget.TextView; public class WhereAmI extends Activity { + final String TAG = getClass().getName(); + private WifiManager wifiman; private Boolean managewifi = false; private Long updatedelay = 60000L; @@ -45,18 +47,18 @@ public class WhereAmI extends Activity private class BgUpdate extends AsyncTask { @Override protected String doInBackground(Void... params) { - Log.w("WhereAmI", "BgUpdate " + updater + " starting"); + Log.w(TAG, "BgUpdate " + updater + " starting"); return updater.getResult(); } @Override protected void onPostExecute(String str) { - Log.w("WhereAmI", "BgUpdate callback executing"); + Log.w(TAG, "BgUpdate callback executing"); tv.setText(str); runningtasks--; if (runningtasks <= 0) { boolean wifion = wifiman.setWifiEnabled(false); - Log.w("WhereAmI", "disabling wifi result " + wifion); + Log.w(TAG, "disabling wifi result " + wifion); Time tm = new Time(); tm.setToNow(); tvs.setText(R.string.lasttry); @@ -66,7 +68,7 @@ public class WhereAmI extends Activity @Override protected void onCancelled() { - Log.w("WhereAmI", "BgUpdate callback cancelled"); + Log.w(TAG, "BgUpdate callback cancelled"); runningtasks--; } } @@ -129,14 +131,14 @@ public class WhereAmI extends Activity private Runnable updateInfo = new Runnable () { public void run() { - Log.w("WhereAmI", "updateInfo starting"); + Log.w(TAG, "updateInfo starting"); if (managewifi) { IntentFilter intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"); registerReceiver(connChanged,intentFilter); connChangedRegistered = true; boolean wifion = wifiman.setWifiEnabled(true); - Log.w("WhereAmI", "enabling wifi result " + wifion); + Log.w(TAG, "enabling wifi result " + wifion); } else { for (int i = 0; i < ut.length; i++) { runningtasks++; @@ -150,7 +152,7 @@ public class WhereAmI extends Activity private Runnable resetInfo = new Runnable () { public void run() { - Log.w("WhereAmI", "resetInfo starting"); + Log.w(TAG, "resetInfo starting"); if (connChangedRegistered) { unregisterReceiver(connChanged); connChangedRegistered = false; @@ -166,7 +168,7 @@ public class WhereAmI extends Activity } if (managewifi) { boolean wifion = wifiman.setWifiEnabled(false); - Log.w("WhereAmI", "disabling wifi result " + wifion); + Log.w(TAG, "disabling wifi result " + wifion); } } }; @@ -180,7 +182,7 @@ public class WhereAmI extends Activity NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); - Log.w("WhereAmI", "Connectivity changed to " + isConnected); + Log.w(TAG, "Connectivity changed to " + isConnected); if (isConnected) { for (int i = 0; i < ut.length; i++) { runningtasks++; @@ -210,11 +212,11 @@ public class WhereAmI extends Activity new UpdateTarget((TextView)findViewById(R.id.phonecall), new Location()) }; - Log.w("WhereAmI", "created UI, about to start update task"); + Log.w(TAG, "created UI, about to start update task"); mHandler.post(updateClock); mHandler.post(updateCal); mHandler.post(updateInfo); - Log.w("WhereAmI", "created UI, update task created"); + Log.w(TAG, "created UI, update task created"); } /** Called when reactivated */ @@ -238,14 +240,14 @@ public class WhereAmI extends Activity @Override public void onPause() { super.onPause(); - Log.w("WhereAmI", "going background"); + Log.w(TAG, "going background"); } /** Called when the activity is destroyed. */ @Override public void onDestroy() { super.onDestroy(); - Log.w("WhereAmI", "going down"); + Log.w(TAG, "going down"); mHandler.removeCallbacks(updateClock); mHandler.removeCallbacks(updateCal); mHandler.removeCallbacks(updateInfo); @@ -254,7 +256,7 @@ public class WhereAmI extends Activity connChangedRegistered = false; } boolean wifion = wifiman.setWifiEnabled(false); - Log.w("WhereAmI", "disabling wifi result " + wifion); + Log.w(TAG, "disabling wifi result " + wifion); } /** Called when the menu is activated. */ @@ -272,8 +274,12 @@ public class WhereAmI extends Activity case R.id.quit: finish(); return true; + case R.id.authorize: + Log.w(TAG, "authorize requested"); + startActivity(new Intent(this, Authorize.class)); + return true; case R.id.settings: - Log.w("WhereAmI", "settings requested"); + Log.w(TAG, "settings requested"); startActivity(new Intent(this, WhereAmIprefs.class)); return true; default: -- 2.43.0