]> average.org Git - WhereAmI.git/commitdiff
Implement OAuth2 authorization
authorEugene Crosser <Eugene.Crosser@ru.ibm.com>
Wed, 1 Feb 2012 14:01:06 +0000 (18:01 +0400)
committerEugene Crosser <Eugene.Crosser@ru.ibm.com>
Wed, 1 Feb 2012 14:01:06 +0000 (18:01 +0400)
AndroidManifest.xml
res/menu/main_menu.xml
res/values/strings.xml
src/org/average/whereami/Authorize.java [new file with mode: 0644]
src/org/average/whereami/Location.java
src/org/average/whereami/PhoneLog.java
src/org/average/whereami/WhereAmI.java

index ebf93832f07d5bcbfaaa921bdbc298d287d74400..5ec033454772c63c739fe5211e0bab45c970120e 100644 (file)
@@ -17,6 +17,9 @@
                 <category android:name="android.intent.category.LAUNCHER" />
             </intent-filter>
         </activity>
+        <activity android:name="Authorize"
+                  android:label="@string/app_name">
+        </activity>
         <activity android:name="WhereAmIprefs"
                   android:label="@string/app_name">
         </activity>
index 6fd0da172f35f5c60a5e103828eb3d476b5c3f7b..3c056cbbe6e793ba5c305cf12a2fe75b9cda24d4 100644 (file)
@@ -3,6 +3,9 @@
     <item android:id="@+id/quit"
           android:icon="@android:drawable/ic_menu_close_clear_cancel"
           android:title="@string/quit" />
+    <item android:id="@+id/authorize"
+          android:icon="@android:drawable/ic_lock_lock"
+          android:title="@string/authorize" />
     <item android:id="@+id/settings"
           android:icon="@android:drawable/ic_menu_preferences"
           android:title="@string/settings" />
index 5d803211630992701da6628be58b0838f6554c38..4835bca020a008faa7b59774b766c247c4455505 100644 (file)
@@ -8,6 +8,7 @@
     <string name="lasttry">Последнее обновление</string>
     <string name="failtry">Неудачная попытка</string>
     <string name="quit">Выход</string>
+    <string name="authorize">Авторизация</string>
     <string name="settings">Конфигурация</string>
     <string name="fullscreentitle">Полный экран</string>
     <string name="fullscreensummary">Полный экран или с индикаторами</string>
diff --git a/src/org/average/whereami/Authorize.java b/src/org/average/whereami/Authorize.java
new file mode 100644 (file)
index 0000000..1bf5fad
--- /dev/null
@@ -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);
+    }
+}
index 9f588b3fa10b62cafcbcdd2f8bceeda769aa1d4a..da9d6fbc4b4311d9ff7ea928fc2880652d2d53e6 100644 (file)
@@ -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);
index 0d99cbbec77a988008eda8741544bd09cd056e7a..cf157a4b3cabb9ebfae70748d2a233cb6b262c26 100644 (file)
@@ -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);
index 953fcc92bb42c1ee07a0263d930eb2d290452662..16d11256c67ed5ca549eb9afdf3b772b0f27caea 100644 (file)
@@ -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<Void, Void, String> {
             @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: