OC-2541: Adapt the code the new saml implementation. Get the username from OCS-API
authormasensio <masensio@solidgear.es>
Tue, 14 Jan 2014 10:06:03 +0000 (11:06 +0100)
committermasensio <masensio@solidgear.es>
Tue, 14 Jan 2014 10:06:03 +0000 (11:06 +0100)
oc_framework/src/com/owncloud/android/oc_framework/accounts/AccountUtils.java
oc_framework/src/com/owncloud/android/oc_framework/accounts/SsoWebViewClient.java
oc_framework/src/com/owncloud/android/oc_framework/operations/RemoteOperationResult.java
oc_framework/src/com/owncloud/android/oc_framework/operations/remote/GetUserNameRemoteOperation.java
src/com/owncloud/android/authentication/AuthenticatorActivity.java

index e42d1bf..20e5b07 100644 (file)
@@ -136,7 +136,7 @@ public class AccountUtils {
      * @return userName
      */
     public static String getUserNameForSamlSso(String authToken) {
-        if (authToken != null) {
+       if (authToken != null) {
             String [] cookies = authToken.split(";");
             for (int i=0; i<cookies.length; i++) {
                 if (cookies[i].startsWith(KEY_OC_USERNAME_EQUALS )) {
index c5f11d6..04f8d95 100644 (file)
@@ -19,13 +19,17 @@ package com.owncloud.android.oc_framework.accounts;
 
 import java.lang.ref.WeakReference;
 
-
 import android.graphics.Bitmap;
+import android.net.http.SslError;
 import android.os.Handler;
 import android.os.Message;
 import android.util.Log;
+import android.view.KeyEvent;
 import android.view.View;
 import android.webkit.CookieManager;
+import android.webkit.HttpAuthHandler;
+import android.webkit.SslErrorHandler;
+import android.webkit.WebResourceResponse;
 import android.webkit.WebView;
 import android.webkit.WebViewClient;
 
@@ -106,7 +110,7 @@ public class SsoWebViewClient extends WebViewClient {
             view.setVisibility(View.GONE);
             CookieManager cookieManager = CookieManager.getInstance();
             final String cookies = cookieManager.getCookie(url);
-            //Log_OC.d(TAG, "Cookies: " + cookies);
+            Log.d(TAG, "Cookies: " + cookies);
             if (mListenerHandler != null && mListenerRef != null) {
                 // this is good idea because onPageFinished is not running in the UI thread
                 mListenerHandler.post(new Runnable() {
@@ -114,16 +118,18 @@ public class SsoWebViewClient extends WebViewClient {
                     public void run() {
                         SsoWebViewClientListener listener = mListenerRef.get();
                         if (listener != null) {
+                               // Send Cookies to the listener
                             listener.onSsoFinished(cookies);
                         }
                     }
                 });
             }
+        } else {
+               Log.d(TAG, "URL==> " + url + " mTarget==> " + mTargetUrl);
         }
-
     }
     
-    /*
+    
     @Override
     public void doUpdateVisitedHistory (WebView view, String url, boolean isReload) {
         Log.d(TAG, "doUpdateVisitedHistory : " + url);
@@ -132,6 +138,7 @@ public class SsoWebViewClient extends WebViewClient {
     @Override
     public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
         Log.d(TAG, "onReceivedSslError : " + error);
+        handler.proceed();
     }
     
     @Override
@@ -171,5 +178,5 @@ public class SsoWebViewClient extends WebViewClient {
         Log.d(TAG, "shouldOverrideKeyEvent : " + event);
         return false;
     }
-    */
+
 }
index 5c857fb..ada12d2 100644 (file)
@@ -101,11 +101,13 @@ public class RemoteOperationResult implements Serializable {
     private String mRedirectedLocation;
 
     private ArrayList<RemoteFile> mFiles;
+    private String mUserName;
     
     public RemoteOperationResult(ResultCode code) {
         mCode = code;
         mSuccess = (code == ResultCode.OK || code == ResultCode.OK_SSL || code == ResultCode.OK_NO_SSL);
         mFiles = null;
+        setUserName("");
     }
 
     private RemoteOperationResult(boolean success, int httpCode) {
@@ -356,4 +358,12 @@ public class RemoteOperationResult implements Serializable {
                 mRedirectedLocation.toLowerCase().contains("wayf")));
     }
 
+       public String getUserName() {
+               return mUserName;
+       }
+
+       public void setUserName(String mUserName) {
+               this.mUserName = mUserName;
+       }
+
 }
index d45a406..d8e7626 100644 (file)
@@ -21,7 +21,6 @@ import java.io.IOException;
 
 import org.apache.commons.httpclient.HttpException;
 import org.apache.commons.httpclient.methods.GetMethod;
-import org.apache.commons.httpclient.methods.HeadMethod;
 import org.apache.http.HttpStatus;
 import org.json.JSONException;
 import org.json.JSONObject;
@@ -34,12 +33,11 @@ import com.owncloud.android.oc_framework.operations.RemoteOperationResult;
 
 
 /**
- * 
  * @author masensio
  *
  * Get the UserName for a SAML connection, from a JSON with the format:
  *             id
- *             display_name
+ *             display-name
  *             email
  */
 
@@ -48,28 +46,35 @@ public class GetUserNameRemoteOperation extends RemoteOperation {
        private static final String TAG = GetUserNameRemoteOperation.class.getSimpleName();
 
        // HEADER
-       private static final String TAG_HEADER = "OCS-APIREQUEST";
-       private static final String TAG_HEADER_VALUE = "true";
+       private static final String TAG_HEADER_OCS_API = "OCS-APIREQUEST";
+       private static final String TAG_HEADER_OCS_API_VALUE = "true";
+       
+       private static final String TAG_HEADER_CONTENT = "Content-Type";
+       private static final String TAG_HEADER_CONTENT_VALUE = "application/xml";
+       private static final String TAG_HEADER_COOKIE = "Cookie";
 
        // OCS Route
-       private static final String TAG_OCS_ROUTE = "index.php/ocs/cloud/user?format=json";
+       private static final String TAG_OCS_ROUTE ="/index.php/ocs/cloud/user?format=json"; 
 
        // JSON Node names
+       private static final String TAG_OCS = "ocs";
+       private static final String TAG_DATA = "data";
        private static final String TAG_ID = "id";
-       private static final String TAG_DISPLAY_NAME= "display_name";
+       private static final String TAG_DISPLAY_NAME= "display-name";
        private static final String TAG_EMAIL= "email";
 
+       private String mUrl;
+       private String mSessionCookie;
        private String mUserName;
 
-
        public String getUserName() {
                return mUserName;
        }
 
-       private String mUrl;
        
-       public GetUserNameRemoteOperation(String url) {
+       public GetUserNameRemoteOperation(String url, String sessioncookie) {
                mUrl = url;
+               mSessionCookie = sessioncookie;
        }
 
        @Override
@@ -78,29 +83,37 @@ public class GetUserNameRemoteOperation extends RemoteOperation {
         int status = -1;
         
         // Get Method
-        GetMethod get = new GetMethod(mUrl);
+        GetMethod get = new GetMethod(mUrl + TAG_OCS_ROUTE);
+        Log.d(TAG, "URL ------> " + mUrl + TAG_OCS_ROUTE);
         // Add the Header
-        get.addRequestHeader("application/xml", "Content-Type");
-        get.addRequestHeader(TAG_HEADER, TAG_HEADER_VALUE);
+        get.addRequestHeader(TAG_HEADER_CONTENT, TAG_HEADER_CONTENT_VALUE);
+        get.addRequestHeader(TAG_HEADER_OCS_API, TAG_HEADER_OCS_API_VALUE);
+        get.setRequestHeader(TAG_HEADER_COOKIE, mSessionCookie);
         
         //Get the user
         try {
                        status = client.executeMethod(get);
-                        if(isSuccess(status)) {
+                       if(isSuccess(status)) {
                                 Log.d(TAG, "Obtain RESPONSE");
                                 String response = get.getResponseBodyAsString();
                                 
-                                Log.d(TAG, response);
+                                Log.d(TAG, "GET RESPONSE.................... " + response);
 
                                 // Parse the response
                                 JSONObject respJSON = new JSONObject(response);
-                                String id = respJSON.getString(TAG_ID);
-                                String display_name = respJSON.getString(TAG_DISPLAY_NAME);
-                                String email = respJSON.getString(TAG_EMAIL);
-
-                                Log.d(TAG, "Response: " + id + "-" + display_name + "-" + email);
+                                JSONObject respOCS = respJSON.getJSONObject(TAG_OCS);
+                                JSONObject respData = respOCS.getJSONObject(TAG_DATA);
+                                String id = respData.getString(TAG_ID);
+                                String displayName = respData.getString(TAG_DISPLAY_NAME);
+                                String email = respData.getString(TAG_EMAIL);
+                                
+                                // Result
+                                result = new RemoteOperationResult(isSuccess(status), status, (get != null ? get.getResponseHeaders() : null));
+                                result.setUserName(displayName);
+                                
+                                Log.d(TAG, "Response: " + id + " - " + displayName + " - " + email);
                                 
-                        }
+                       }
                } catch (HttpException e) {
                        result = new RemoteOperationResult(e);
                        e.printStackTrace();
index 9d6d3f3..dd918e6 100644 (file)
@@ -18,6 +18,8 @@
 \r
 package com.owncloud.android.authentication;\r
 \r
+import java.util.concurrent.ExecutionException;\r
+\r
 import android.accounts.Account;\r
 import android.accounts.AccountManager;\r
 import android.app.AlertDialog;\r
@@ -29,6 +31,7 @@ import android.content.SharedPreferences;
 import android.graphics.Rect;\r
 import android.graphics.drawable.Drawable;\r
 import android.net.Uri;\r
+import android.os.AsyncTask;\r
 import android.os.Bundle;\r
 import android.os.Handler;\r
 import android.preference.PreferenceManager;\r
@@ -64,6 +67,7 @@ import com.owncloud.android.oc_framework.operations.RemoteOperation;
 import com.owncloud.android.oc_framework.operations.RemoteOperationResult;\r
 import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode;\r
 import com.owncloud.android.oc_framework.operations.remote.ExistenceCheckRemoteOperation;\r
+import com.owncloud.android.oc_framework.operations.remote.GetUserNameRemoteOperation;\r
 import com.owncloud.android.ui.dialog.SamlWebViewDialog;\r
 import com.owncloud.android.ui.dialog.SslValidatorDialog;\r
 import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;\r
@@ -102,9 +106,6 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     private static final String KEY_AUTH_STATUS_TEXT = "AUTH_STATUS_TEXT";\r
     private static final String KEY_AUTH_STATUS_ICON = "AUTH_STATUS_ICON";\r
     private static final String KEY_REFRESH_BUTTON_ENABLED = "KEY_REFRESH_BUTTON_ENABLED";\r
-    \r
-    // TODO Remove it\r
-    //private static final String KEY_OC_USERNAME_EQUALS = "oc_username="; \r
 \r
     private static final String AUTH_ON = "on";\r
     private static final String AUTH_OFF = "off";\r
@@ -795,8 +796,9 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             }\r
         }\r
     }\r
-    \r
-    \r
+\r
+\r
+\r
     private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperation operation, RemoteOperationResult result) {\r
         try {\r
             dismissDialog(DIALOG_LOGIN_PROGRESS);\r
@@ -1178,7 +1180,11 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);\r
             \r
         } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {\r
-            String username = com.owncloud.android.oc_framework.accounts.AccountUtils.getUserNameForSamlSso(mAuthToken);\r
+            \r
+            String username= getUserNameForSaml(mHostBaseUrl);\r
+            if (username == null)\r
+                return false;\r
+            \r
             if (!mUsernameInput.getText().toString().equals(username)) {\r
                 // fail - not a new account, but an existing one; disallow\r
                 RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME); \r
@@ -1218,8 +1224,10 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         Uri uri = Uri.parse(mHostBaseUrl);\r
         String username = mUsernameInput.getText().toString().trim();\r
         if (isSaml) {\r
-            username = com.owncloud.android.oc_framework.accounts.AccountUtils.getUserNameForSamlSso(mAuthToken);\r
-            \r
+            username = getUserNameForSaml(mHostBaseUrl);\r
+            if (username == null)\r
+                return false;\r
+\r
         } else if (isOAuth) {\r
             username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();\r
         }            \r
@@ -1280,20 +1288,6 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         }\r
     }\r
 \r
-// TODO Remove it\r
-//    private String getUserNameForSamlSso() {\r
-//        if (mAuthToken != null) {\r
-//            String [] cookies = mAuthToken.split(";");\r
-//            for (int i=0; i<cookies.length; i++) {\r
-//                if (cookies[i].startsWith(KEY_OC_USERNAME_EQUALS )) {\r
-//                    String value = Uri.decode(cookies[i].substring(KEY_OC_USERNAME_EQUALS.length()));\r
-//                    return value;\r
-//                }\r
-//            }\r
-//        }\r
-//        return "";\r
-//    }\r
-\r
 \r
     /**\r
      * {@inheritDoc}\r
@@ -1653,4 +1647,45 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         }\r
         return super.onTouchEvent(event);\r
     }\r
+    \r
+    \r
+    /**\r
+     * Asynchronous task to get the SAML User name from OCS-API\r
+     *\r
+     */\r
+    private class GetUserNameTask extends AsyncTask<String, Void, String>{\r
+\r
+        @Override\r
+        protected String doInBackground(String... params) {\r
+            \r
+            String hostUrl = (String)params[0];\r
+            \r
+            GetUserNameRemoteOperation getUserOperation = new GetUserNameRemoteOperation(hostUrl, mAuthToken);\r
+            WebdavClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(hostUrl), getApplicationContext(), true);\r
+            RemoteOperationResult result = getUserOperation.execute(client);\r
+          \r
+            return result.getUserName();\r
+        }\r
+        \r
+    }\r
+\r
+    /**\r
+     * Get the user name form OCS-API\r
+     * @param hostUrl\r
+     * @return username\r
+     */\r
+    private String getUserNameForSaml(String hostUrl){\r
+\r
+        GetUserNameTask getUserTask = new GetUserNameTask();\r
+        String username = null;\r
+        try {\r
+            username = getUserTask.execute(mHostBaseUrl).get();\r
+        } catch (InterruptedException e) {\r
+            e.printStackTrace();\r
+        } catch (ExecutionException e) {\r
+            e.printStackTrace();\r
+        }\r
+\r
+        return username;\r
+    }\r
 }\r