Merge pull request #249 from owncloud/saml_based_federated_single_sign_on
authormasensio <masensio@solidgear.es>
Tue, 27 Aug 2013 12:44:12 +0000 (05:44 -0700)
committermasensio <masensio@solidgear.es>
Tue, 27 Aug 2013 12:44:12 +0000 (05:44 -0700)
Saml based federated single sign on

23 files changed:
res/layout-land/account_setup.xml
res/layout/account_setup.xml
res/layout/sso_dialog.xml [new file with mode: 0644]
res/values/branding.xml [deleted file]
res/values/oauth2_configuration.xml
res/values/setup.xml [new file with mode: 0644]
res/values/strings.xml
res/values/styles.xml
src/com/owncloud/android/authentication/AccountAuthenticator.java
src/com/owncloud/android/authentication/AccountAuthenticatorActivity.java [new file with mode: 0644]
src/com/owncloud/android/authentication/AccountUtils.java
src/com/owncloud/android/authentication/AuthenticatorActivity.java
src/com/owncloud/android/authentication/SsoWebViewClient.java [new file with mode: 0644]
src/com/owncloud/android/network/OwnCloudClientUtils.java
src/com/owncloud/android/operations/ExistenceCheckOperation.java
src/com/owncloud/android/operations/RemoteOperation.java
src/com/owncloud/android/operations/RemoteOperationResult.java
src/com/owncloud/android/operations/SynchronizeFolderOperation.java
src/com/owncloud/android/ui/activity/AccountSelectActivity.java
src/com/owncloud/android/ui/activity/FileActivity.java
src/com/owncloud/android/ui/dialog/SamlWebViewDialog.java [new file with mode: 0644]
src/com/owncloud/android/ui/dialog/SsoWebView.java [new file with mode: 0644]
src/eu/alefzero/webdav/WebdavClient.java

index 150893a..bff91f5 100644 (file)
@@ -43,6 +43,7 @@
                    android:layout_width="0dp"\r
                    android:layout_height="match_parent"\r
                    android:layout_weight="1"\r
+                   android:id="@+id/scroll"\r
                    android:fillViewport="true"\r
                    android:orientation="vertical" >\r
                                                \r
@@ -50,7 +51,6 @@
                            android:id="@+id/LinearLayout1"\r
                            android:layout_width="match_parent"\r
                            android:layout_height="wrap_content"\r
-                           android:focusable="true"\r
                            android:gravity="center"\r
                            android:orientation="vertical"\r
                            android:padding="8dp" >\r
                                        android:onClick="onCheckClick"\r
                                        android:text="@string/oauth_check_onoff"\r
                                        android:textAppearance="?android:attr/textAppearanceSmall"\r
-                                       android:visibility="gone"\r
                                        />\r
                \r
                                <EditText\r
                                        android:singleLine="true"\r
                                        android:inputType="textUri"\r
                                        android:visibility="gone" >\r
-                                       <requestFocus />\r
                                </EditText>            \r
                                \r
                                <EditText\r
index 04da4be..a7f549f 100644 (file)
     android:layout_height="match_parent"\r
     android:layout_gravity="center"\r
     android:fillViewport="true"\r
-    android:orientation="vertical" >\r
+    android:orientation="vertical" \r
+    android:id="@+id/scroll"\r
+    >\r
 \r
     <LinearLayout\r
         android:layout_width="match_parent"\r
         android:layout_height="wrap_content"\r
-        android:focusable="true"\r
         android:gravity="center"\r
         android:orientation="vertical"\r
         android:padding="8dp" >\r
             android:onClick="onCheckClick"\r
             android:text="@string/oauth_check_onoff"\r
             android:textAppearance="?android:attr/textAppearanceSmall"\r
-            android:visibility="gone" />\r
+            />\r
 \r
         <EditText\r
             android:id="@+id/oAuthEntryPoint_1"\r
             android:layout_width="match_parent"\r
             android:layout_height="wrap_content"\r
             android:ems="10"\r
-            android:inputType="textUri"\r
-            android:singleLine="true"\r
+                       android:enabled="false"\r
             android:text="@string/oauth2_url_endpoint_auth"\r
+            android:singleLine="true"\r
+            android:inputType="textUri"\r
             android:visibility="gone" >\r
         </EditText>\r
 \r
             android:layout_width="match_parent"\r
             android:layout_height="wrap_content"\r
             android:ems="10"\r
-            android:inputType="textUri"\r
-            android:singleLine="true"\r
+                       android:enabled="false"\r
             android:text="@string/oauth2_url_endpoint_access"\r
+            android:singleLine="true"\r
+            android:inputType="textUri"\r
             android:visibility="gone" />\r
 \r
         <EditText\r
             android:layout_height="wrap_content"\r
             android:ems="10"\r
             android:hint="@string/auth_username"\r
-            android:inputType="textNoSuggestions" />\r
+            android:inputType="textNoSuggestions" \r
+                       />\r
 \r
                <EditText\r
                    android:id="@+id/account_password"\r
                    android:drawablePadding="5dp"\r
                    android:ems="10"\r
                    android:hint="@string/auth_password"\r
-                   android:inputType="textPassword" />\r
+                   android:inputType="textPassword" \r
+            />\r
         \r
         <TextView\r
             android:id="@+id/auth_status_text"\r
diff --git a/res/layout/sso_dialog.xml b/res/layout/sso_dialog.xml
new file mode 100644 (file)
index 0000000..788a0e2
--- /dev/null
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+  ownCloud Android client application
+
+  Copyright (C) 2012-2013 ownCloud Inc.
+
+  This program is free software: you can redistribute it and/or modify
+  it under the terms of the GNU General Public License version 2,
+  as published by the Free Software Foundation.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+-->
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="wrap_content"
+    android:layout_height="wrap_content"
+    >
+    
+    <com.owncloud.android.ui.dialog.SsoWebView
+       android:layout_width="wrap_content"
+       android:layout_height="wrap_content"
+        android:id="@+id/sso_webview"
+        android:focusable="true"
+        android:focusableInTouchMode="true"
+        android:clickable="true"
+        />
+
+</RelativeLayout>
diff --git a/res/values/branding.xml b/res/values/branding.xml
deleted file mode 100644 (file)
index f312dad..0000000
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
-    <string name="server_url"></string>
-    <bool name="show_server_url_input">true</bool>
-</resources>
index 5fbef7c..f8e0f51 100644 (file)
@@ -1,10 +1,5 @@
 <?xml version="1.0" encoding="utf-8"?>
 <resources>
-    <!-- Flag to configure OAuth availability in the app.
-        3 valid values now: on, off, optional  
-     -->
-    <string name="oauth2_mode">off</string>
-    
     <!-- constants that must be respected by the authorization server; if changed, the app must be rebuild -->
     <string name="oauth2_redirect_scheme">owncloud</string>
     <string name="oauth2_redirect_uri">owncloud://callback</string>
diff --git a/res/values/setup.xml b/res/values/setup.xml
new file mode 100644 (file)
index 0000000..2c46d41
--- /dev/null
@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+    <string name="server_url"></string>
+    <bool name="show_server_url_input">true</bool>
+    
+    <!-- Flags to setup the authentication methods available in the app -->
+    <string name="auth_method_oauth2">off</string>
+    <string name="auth_method_saml_web_sso">on</string>
+    
+</resources>
index 8c273bd..4e375d0 100644 (file)
@@ -49,6 +49,7 @@
     <string name="prefs_log_delete_history_button">Delete History</string>
     
     <string name="auth_check_server">Check Server</string>
+    <string name="auth_account_name">Account name</string>
     <string name="auth_host_url">Server address</string>
     <string name="auth_username">Username</string>
     <string name="auth_password">Password</string>
     <string name="auth_testing_connection">Testing connection&#8230;</string>
     <string name="auth_not_configured_title">Malformed server configuration</string>
     <string name="auth_not_configured_message">It seems that your server instance is not correctly configured. Contact your administrator for more details.</string>
+    <string name="auth_account_not_new">An account for the same user and server already exists in the device</string>
     <string name="auth_unknown_error_title">Unknown error occurred!</string>
     <string name="auth_unknown_error_message">An unknown error occurred. Please contact support and include logs from your device.</string>
     <string name="auth_unknown_host_title">Couldn\'t find host</string>
     <string name="auth_wtf_reenter_URL">Unexpected state; please, enter the server URL again</string>
     <string name="auth_expired_oauth_token_toast">Your authorization expired.\nPlease, authorize again</string>
     <string name="auth_expired_basic_auth_toast">Please, enter the current password</string>
+       <string name="auth_connecting_auth_server">Connecting to authentication server…</string>
+       <string name="auth_follow_auth_server">Follow instructions above to get authenticated</string>
+       <string name="auth_unsupported_auth_method">The server does not support this authentication method</string>    
     
     <string name="crashlog_message">Application terminated unexpectedly. Would you like to submit a crash report?</string>
     <string name="crashlog_send_report">Send report</string>
index 13d0ed2..3ad0151 100644 (file)
@@ -20,7 +20,7 @@
 <resources xmlns:android="http://schemas.android.com/apk/res/android">
        <style name="Animations" />
 
-       <!-- Default ownCloud app style -->
+       <!-- General ownCloud app style -->
        <style name="Theme.ownCloud" parent="style/Theme.Sherlock.Light.DarkActionBar">
        <item name="android:actionBarStyle">@style/Theme.ownCloud.Widget.ActionBar</item>
        <item name="actionBarStyle">@style/Theme.ownCloud.Widget.ActionBar</item>
        <item name="android:shadowDy">1</item>
        <item name="android:backgroundSplit">@drawable/split_action_bg</item>
        </style>
+
+               
+       <!-- Dialogs -->
+       <style name="Theme.ownCloud.Dialog" parent="style/Theme.Sherlock.Light.Dialog">
+       </style>
+       
        
        <!-- PopDownMenu -->
        <style name="Animations.PopDownMenu" />
index 30eda59..85e9a23 100644 (file)
@@ -46,6 +46,7 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
     public static final String AUTH_TOKEN_TYPE_PASSWORD = "owncloud.password";
     public static final String AUTH_TOKEN_TYPE_ACCESS_TOKEN = "owncloud.oauth2.access_token";
     public static final String AUTH_TOKEN_TYPE_REFRESH_TOKEN = "owncloud.oauth2.refresh_token";
+    public static final String AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE = "owncloud.saml.web_sso.session_cookie";
 
     public static final String KEY_AUTH_TOKEN_TYPE = "authTokenType";
     public static final String KEY_REQUIRED_FEATURES = "requiredFeatures";
@@ -75,6 +76,10 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
      * Flag signaling if the ownCloud server can be accessed with OAuth2 access tokens.
      */
     public static final String KEY_SUPPORTS_OAUTH2 = "oc_supports_oauth2";
+    /**
+     * Flag signaling if the ownCloud server can be accessed with session cookies from SAML-based web single-sign-on.
+     */
+    public static final String KEY_SUPPORTS_SAML_WEB_SSO = "oc_supports_saml_web_sso";
     
     private static final String TAG = AccountAuthenticator.class.getSimpleName();
     
@@ -254,7 +259,8 @@ public class AccountAuthenticator extends AbstractAccountAuthenticator {
         if (!authTokenType.equals(AUTH_TOKEN_TYPE) &&\r
             !authTokenType.equals(AUTH_TOKEN_TYPE_PASSWORD) &&\r
             !authTokenType.equals(AUTH_TOKEN_TYPE_ACCESS_TOKEN) &&\r
-            !authTokenType.equals(AUTH_TOKEN_TYPE_REFRESH_TOKEN) ) {\r
+            !authTokenType.equals(AUTH_TOKEN_TYPE_REFRESH_TOKEN) &&
+            !authTokenType.equals(AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE)) {\r
             throw new UnsupportedAuthTokenTypeException();\r
         }\r
     }\r
diff --git a/src/com/owncloud/android/authentication/AccountAuthenticatorActivity.java b/src/com/owncloud/android/authentication/AccountAuthenticatorActivity.java
new file mode 100644 (file)
index 0000000..62c8825
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2009 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.owncloud.android.authentication;
+
+import android.accounts.AccountAuthenticatorResponse;
+import android.accounts.AccountManager;
+import android.os.Bundle;
+
+import com.actionbarsherlock.app.SherlockFragmentActivity;
+
+
+/*
+ * Base class for implementing an Activity that is used to help implement an AbstractAccountAuthenticator. 
+ * If the AbstractAccountAuthenticator needs to use an activity to handle the request then it can have the activity extend 
+ * AccountAuthenticatorActivity. The AbstractAccountAuthenticator passes in the response to the intent using the following:
+ * intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
+ * 
+ * The activity then sets the result that is to be handed to the response via setAccountAuthenticatorResult(android.os.Bundle). 
+ * This result will be sent as the result of the request when the activity finishes. If this is never set or if it is set to null 
+ * then error AccountManager.ERROR_CODE_CANCELED will be called on the response.
+ */
+
+public class AccountAuthenticatorActivity extends SherlockFragmentActivity {
+
+    private AccountAuthenticatorResponse mAccountAuthenticatorResponse = null;
+    private Bundle mResultBundle = null;
+
+
+    /**
+     * Set the result that is to be sent as the result of the request that caused this Activity to be launched.
+     * If result is null or this method is never called then the request will be canceled.
+     * 
+     * @param result this is returned as the result of the AbstractAccountAuthenticator request
+     */
+    public final void setAccountAuthenticatorResult(Bundle result) {
+        mResultBundle = result;
+    }
+
+    /**
+     * Retreives the AccountAuthenticatorResponse from either the intent of the icicle, if the
+     * icicle is non-zero.
+     * @param icicle the save instance data of this Activity, may be null
+     */
+    protected void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+
+        mAccountAuthenticatorResponse =
+                getIntent().getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
+
+        if (mAccountAuthenticatorResponse != null) {
+            mAccountAuthenticatorResponse.onRequestContinued();
+        }
+    }
+    
+    /**
+     * Sends the result or a Constants.ERROR_CODE_CANCELED error if a result isn't present.
+     */
+    public void finish() {
+        if (mAccountAuthenticatorResponse != null) {
+            // send the result bundle back if set, otherwise send an error.
+            if (mResultBundle != null) {
+                mAccountAuthenticatorResponse.onResult(mResultBundle);
+            } else {
+                mAccountAuthenticatorResponse.onError(AccountManager.ERROR_CODE_CANCELED,
+                        "canceled");
+            }
+            mAccountAuthenticatorResponse = null;
+        }
+        super.finish();
+    }
+}
index 591da01..47269bc 100644 (file)
@@ -32,6 +32,7 @@ public class AccountUtils {
     public static final String WEBDAV_PATH_2_0 = "/files/webdav.php";\r
     public static final String WEBDAV_PATH_4_0 = "/remote.php/webdav";\r
     private static final String ODAV_PATH = "/remote.php/odav";\r
+    private static final String SAML_SSO_PATH = "/remote.php/webdav";\r
     public static final String CARDDAV_PATH_2_0 = "/apps/contacts/carddav.php";\r
     public static final String CARDDAV_PATH_4_0 = "/remote/carddav.php";\r
     public static final String STATUS_PATH = "/status.php";\r
@@ -74,6 +75,20 @@ public class AccountUtils {
     }\r
 \r
     \r
+    public static boolean exists(Account account, Context context) {\r
+        Account[] ocAccounts = AccountManager.get(context).getAccountsByType(\r
+                AccountAuthenticator.ACCOUNT_TYPE);\r
+\r
+        if (account != null && account.name != null) {\r
+            for (Account ac : ocAccounts) {\r
+                if (ac.name.equals(account.name)) {\r
+                    return true;\r
+                }\r
+            }\r
+        }\r
+        return false;\r
+    }\r
+    \r
 \r
     /**\r
      * Checks, whether or not there are any ownCloud accounts setup.\r
@@ -115,11 +130,41 @@ public class AccountUtils {
      * @param version version of owncloud\r
      * @return webdav path for given OC version, null if OC version unknown\r
      */\r
-    public static String getWebdavPath(OwnCloudVersion version, boolean supportsOAuth) {\r
+    public static String getWebdavPath(OwnCloudVersion version, boolean supportsOAuth, boolean supportsSamlSso) {\r
         if (version != null) {\r
             if (supportsOAuth) {\r
                 return ODAV_PATH;\r
             }\r
+            if (supportsSamlSso) {\r
+                return SAML_SSO_PATH;\r
+            }\r
+            if (version.compareTo(OwnCloudVersion.owncloud_v4) >= 0)\r
+                return WEBDAV_PATH_4_0;\r
+            if (version.compareTo(OwnCloudVersion.owncloud_v3) >= 0\r
+                    || version.compareTo(OwnCloudVersion.owncloud_v2) >= 0)\r
+                return WEBDAV_PATH_2_0;\r
+            if (version.compareTo(OwnCloudVersion.owncloud_v1) >= 0)\r
+                return WEBDAV_PATH_1_2;\r
+        }\r
+        return null;\r
+    }\r
+    \r
+    /**\r
+     * Returns the proper URL path to access the WebDAV interface of an ownCloud server,\r
+     * according to its version and the authorization method used.\r
+     * \r
+     * @param   version         Version of ownCloud server.\r
+     * @param   authTokenType   Authorization token type, matching some of the AUTH_TOKEN_TYPE_* constants in {@link AccountAuthenticator}. \r
+     * @return                  WebDAV path for given OC version and authorization method, null if OC version is unknown.\r
+     */\r
+    public static String getWebdavPath(OwnCloudVersion version, String authTokenType) {\r
+        if (version != null) {\r
+            if (AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(authTokenType)) {\r
+                return ODAV_PATH;\r
+            }\r
+            if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(authTokenType)) {\r
+                return SAML_SSO_PATH;\r
+            }\r
             if (version.compareTo(OwnCloudVersion.owncloud_v4) >= 0)\r
                 return WEBDAV_PATH_4_0;\r
             if (version.compareTo(OwnCloudVersion.owncloud_v3) >= 0\r
@@ -143,8 +188,9 @@ public class AccountUtils {
         String baseurl = ama.getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL);\r
         String strver  = ama.getUserData(account, AccountAuthenticator.KEY_OC_VERSION);\r
         boolean supportsOAuth = (ama.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null);\r
+        boolean supportsSamlSso = (ama.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO) != null);\r
         OwnCloudVersion ver = new OwnCloudVersion(strver);\r
-        String webdavpath = getWebdavPath(ver, supportsOAuth);\r
+        String webdavpath = getWebdavPath(ver, supportsOAuth, supportsSamlSso);\r
 \r
         if (baseurl == null || webdavpath == null) \r
             throw new AccountNotFoundException(account, "Account not found", null);\r
index 76041c1..4ea7f3d 100644 (file)
 \r
 package com.owncloud.android.authentication;\r
 \r
-import com.owncloud.android.Log_OC;\r
-import com.owncloud.android.ui.dialog.SslValidatorDialog;\r
-import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;\r
-import com.owncloud.android.utils.OwnCloudVersion;\r
-import com.owncloud.android.network.OwnCloudClientUtils;\r
-import com.owncloud.android.operations.OwnCloudServerCheckOperation;\r
-import com.owncloud.android.operations.ExistenceCheckOperation;\r
-import com.owncloud.android.operations.OAuth2GetAccessToken;\r
-import com.owncloud.android.operations.OnRemoteOperationListener;\r
-import com.owncloud.android.operations.RemoteOperation;\r
-import com.owncloud.android.operations.RemoteOperationResult;\r
-import com.owncloud.android.operations.RemoteOperationResult.ResultCode;\r
+import java.net.URLDecoder;\r
 \r
 import android.accounts.Account;\r
-import android.accounts.AccountAuthenticatorActivity;\r
 import android.accounts.AccountManager;\r
 import android.app.AlertDialog;\r
 import android.app.Dialog;\r
@@ -47,6 +35,7 @@ import android.net.Uri;
 import android.os.Bundle;\r
 import android.os.Handler;\r
 import android.preference.PreferenceManager;\r
+import android.support.v4.app.Fragment;\r
 import android.text.Editable;\r
 import android.text.InputType;\r
 import android.text.TextWatcher;\r
@@ -57,14 +46,29 @@ import android.view.View.OnFocusChangeListener;
 import android.view.View.OnTouchListener;\r
 import android.view.Window;\r
 import android.view.inputmethod.EditorInfo;\r
+import android.widget.Button;\r
 import android.widget.CheckBox;\r
 import android.widget.EditText;\r
-import android.widget.Button;\r
 import android.widget.TextView;\r
-import android.widget.Toast;\r
 import android.widget.TextView.OnEditorActionListener;\r
+import android.widget.Toast;\r
 \r
+import com.actionbarsherlock.app.SherlockDialogFragment;\r
+import com.owncloud.android.Log_OC;\r
 import com.owncloud.android.R;\r
+import com.owncloud.android.authentication.SsoWebViewClient.SsoWebViewClientListener;\r
+import com.owncloud.android.network.OwnCloudClientUtils;\r
+import com.owncloud.android.operations.ExistenceCheckOperation;\r
+import com.owncloud.android.operations.OAuth2GetAccessToken;\r
+import com.owncloud.android.operations.OnRemoteOperationListener;\r
+import com.owncloud.android.operations.OwnCloudServerCheckOperation;\r
+import com.owncloud.android.operations.RemoteOperation;\r
+import com.owncloud.android.operations.RemoteOperationResult;\r
+import com.owncloud.android.operations.RemoteOperationResult.ResultCode;\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
+import com.owncloud.android.utils.OwnCloudVersion;\r
 \r
 import eu.alefzero.webdav.WebdavClient;\r
 \r
@@ -75,7 +79,7 @@ import eu.alefzero.webdav.WebdavClient;
  * @author David A. Velasco\r
  */\r
 public class AuthenticatorActivity extends AccountAuthenticatorActivity\r
-implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeListener, OnEditorActionListener {\r
+implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeListener, OnEditorActionListener, SsoWebViewClientListener{\r
 \r
     private static final String TAG = AuthenticatorActivity.class.getSimpleName();\r
 \r
@@ -98,11 +102,13 @@ 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
+    private static final String KEY_OC_USERNAME_EQUALS = "oc_username=";\r
 \r
-    private static final String OAUTH_MODE_ON = "on";\r
-    private static final String OAUTH_MODE_OFF = "off";\r
-    private static final String OAUTH_MODE_OPTIONAL = "optional";\r
-\r
+    private static final String AUTH_ON = "on";\r
+    private static final String AUTH_OFF = "off";\r
+    private static final String AUTH_OPTIONAL = "optional";\r
+    \r
     private static final int DIALOG_LOGIN_PROGRESS = 0;\r
     private static final int DIALOG_SSL_VALIDATOR = 1;\r
     private static final int DIALOG_CERT_NOT_SAVED = 2;\r
@@ -111,12 +117,15 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     public static final byte ACTION_CREATE = 0;\r
     public static final byte ACTION_UPDATE_TOKEN = 1;\r
 \r
+    private static final String TAG_SAML_DIALOG = "samlWebViewDialog";\r
+    \r
     private String mHostBaseUrl;\r
     private OwnCloudVersion mDiscoveredVersion;\r
 \r
     private int mServerStatusText, mServerStatusIcon;\r
     private boolean mServerIsChecked, mServerIsValid, mIsSslConn;\r
     private int mAuthStatusText, mAuthStatusIcon;    \r
+    private TextView mAuthStatusLayout;\r
 \r
     private final Handler mHandler = new Handler();\r
     private Thread mOperationThread;\r
@@ -132,20 +141,26 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     private Account mAccount;\r
 \r
     private EditText mHostUrlInput;\r
+    private boolean mHostUrlInputEnabled;\r
     private View mRefreshButton;\r
+\r
+    private String mAuthTokenType;\r
+    \r
     private EditText mUsernameInput;\r
     private EditText mPasswordInput;\r
+    \r
     private CheckBox mOAuth2Check;\r
-    private String mOAuthAccessToken;\r
-    private View mOkButton;\r
-    private TextView mAuthStatusLayout;\r
-\r
+    \r
     private TextView mOAuthAuthEndpointText;\r
     private TextView mOAuthTokenEndpointText;\r
     \r
-    private boolean mRefreshButtonEnabled;\r
+    private SamlWebViewDialog mSamlDialog;\r
     \r
-    private boolean mHostUrlInputEnabled;\r
+    private View mOkButton;\r
+    \r
+    private String mAuthToken;\r
+    \r
+    private boolean mResumed; // Control if activity is resumed\r
 \r
 \r
     /**\r
@@ -199,6 +214,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         }\r
 \r
         if (savedInstanceState == null) {\r
+            mResumed = false;\r
             /// connection state and info\r
             mServerStatusText = mServerStatusIcon = 0;\r
             mServerIsValid = false;\r
@@ -207,9 +223,6 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             mAuthStatusText = mAuthStatusIcon = 0;\r
 \r
             /// retrieve extras from intent\r
-            String tokenType = getIntent().getExtras().getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE);\r
-            boolean oAuthRequired = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(tokenType) || OAUTH_MODE_ON.equals(getString(R.string.oauth2_mode));\r
-\r
             mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT);\r
             if (mAccount != null) {\r
                 String ocVersion = mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION);\r
@@ -218,19 +231,16 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
                 }\r
                 mHostBaseUrl = normalizeUrl(mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL));\r
                 mHostUrlInput.setText(mHostBaseUrl);\r
-                String userName = mAccount.name.substring(0, mAccount.name.lastIndexOf('@'));\r
-                mUsernameInput.setText(userName);\r
-                oAuthRequired = (mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null);\r
             }\r
-            mOAuth2Check.setChecked(oAuthRequired);\r
-            changeViewByOAuth2Check(oAuthRequired);\r
+            initAuthorizationMethod();  // checks intent and setup.xml to determine mCurrentAuthorizationMethod\r
             mJustCreated = true;\r
             \r
             if (mAction == ACTION_UPDATE_TOKEN || !mHostUrlInputEnabled) {\r
                 checkOcServer(); \r
             }\r
-\r
+            \r
         } else {\r
+            mResumed = true;\r
             /// connection state and info\r
             mServerIsValid = savedInstanceState.getBoolean(KEY_SERVER_VALID);\r
             mServerIsChecked = savedInstanceState.getBoolean(KEY_SERVER_CHECKED);\r
@@ -252,6 +262,11 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
 \r
             // account data, if updating\r
             mAccount = savedInstanceState.getParcelable(KEY_ACCOUNT);\r
+            mAuthTokenType = savedInstanceState.getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE);\r
+            if (mAuthTokenType == null) {\r
+                mAuthTokenType =  AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;\r
+                \r
+            }\r
 \r
             // check if server check was interrupted by a configuration change\r
             if (savedInstanceState.getBoolean(KEY_SERVER_CHECK_IN_PROGRESS, false)) {\r
@@ -264,9 +279,10 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
 \r
         }\r
 \r
+        adaptViewAccordingToAuthenticationMethod();\r
         showServerStatus();\r
         showAuthStatus();\r
-\r
+        \r
         if (mAction == ACTION_UPDATE_TOKEN) {\r
             /// lock things that should not change\r
             mHostUrlInput.setEnabled(false);\r
@@ -280,14 +296,17 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         if (mServerIsChecked && !mServerIsValid && refreshButtonEnabled) showRefreshButton();\r
         mOkButton.setEnabled(mServerIsValid); // state not automatically recovered in configuration changes\r
 \r
-        if (!OAUTH_MODE_OPTIONAL.equals(getString(R.string.oauth2_mode))) {\r
+        if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType) || \r
+                !AUTH_OPTIONAL.equals(getString(R.string.auth_method_oauth2))) {\r
             mOAuth2Check.setVisibility(View.GONE);\r
         }\r
 \r
         mPasswordInput.setText("");     // clean password to avoid social hacking (disadvantage: password in removed if the device is turned aside)\r
 \r
-        /// bind view elements to listeners\r
+        /// bind view elements to listeners and other friends\r
         mHostUrlInput.setOnFocusChangeListener(this);\r
+        mHostUrlInput.setImeOptions(EditorInfo.IME_ACTION_NEXT);\r
+        mHostUrlInput.setOnEditorActionListener(this);\r
         mHostUrlInput.addTextChangedListener(new TextWatcher() {\r
 \r
             @Override\r
@@ -298,12 +317,20 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             }\r
 \r
             @Override\r
-            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}\r
+            public void beforeTextChanged(CharSequence s, int start, int count, int after) {\r
+            }\r
 \r
             @Override\r
-            public void onTextChanged(CharSequence s, int start, int before, int count) {}\r
-\r
+            public void onTextChanged(CharSequence s, int start, int before, int count) {\r
+                if (!mResumed) {\r
+                    mAuthStatusIcon = 0;\r
+                    mAuthStatusText = 0;\r
+                    showAuthStatus();                    \r
+                }\r
+                mResumed = false;\r
+            }\r
         });\r
+        \r
         mPasswordInput.setOnFocusChangeListener(this);\r
         mPasswordInput.setImeOptions(EditorInfo.IME_ACTION_DONE);\r
         mPasswordInput.setOnEditorActionListener(this);
@@ -315,7 +342,60 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
                 }\r
                 return true;\r
             }\r
-        });
+        });\r
+        \r
+        findViewById(R.id.scroll).setOnTouchListener(new OnTouchListener() {\r
+            @Override\r
+            public boolean onTouch(View view, MotionEvent event) {\r
+                if (event.getAction() == MotionEvent.ACTION_DOWN) {\r
+                    if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType) &&\r
+                            mHostUrlInput.hasFocus()) {\r
+                        checkOcServer();\r
+                    }\r
+                }\r
+                return false;\r
+            }\r
+        });\r
+    }\r
+    \r
+   \r
+\r
+    private void initAuthorizationMethod() {\r
+        boolean oAuthRequired = false;\r
+        boolean samlWebSsoRequired = false;\r
+\r
+        mAuthTokenType = getIntent().getExtras().getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE);\r
+        mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT);\r
+        \r
+        // TODO could be a good moment to validate the received token type, if not null\r
+        \r
+        if (mAuthTokenType == null) {    \r
+            if (mAccount != null) {\r
+                /// same authentication method than the one used to create the account to update\r
+                oAuthRequired = (mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null);\r
+                samlWebSsoRequired = (mAccountMgr.getUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO) != null);\r
+            \r
+            } else {\r
+                /// use the one set in setup.xml\r
+                oAuthRequired = AUTH_ON.equals(getString(R.string.auth_method_oauth2));\r
+                samlWebSsoRequired = AUTH_ON.equals(getString(R.string.auth_method_saml_web_sso));            \r
+            }\r
+            if (oAuthRequired) {\r
+                mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN;\r
+            } else if (samlWebSsoRequired) {\r
+                mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE;\r
+            } else {\r
+                mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;\r
+            }\r
+        }\r
+    \r
+        if (mAccount != null) {\r
+            String userName = mAccount.name.substring(0, mAccount.name.lastIndexOf('@'));\r
+            mUsernameInput.setText(userName);\r
+        }\r
+        \r
+        mOAuth2Check.setChecked(AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType));\r
+        \r
     }\r
 \r
     /**\r
@@ -351,10 +431,11 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         if (mAccount != null) {\r
             outState.putParcelable(KEY_ACCOUNT, mAccount);\r
         }\r
+        outState.putString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE, mAuthTokenType);\r
         \r
         // refresh button enabled\r
-        //outState.putBoolean(KEY_REFRESH_BUTTON_ENABLED, mRefreshButtonEnabled);\r
         outState.putBoolean(KEY_REFRESH_BUTTON_ENABLED, (mRefreshButton.getVisibility() == View.VISIBLE));\r
+        \r
 \r
     }\r
 \r
@@ -383,8 +464,6 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     @Override\r
     protected void onResume() {\r
         super.onResume();\r
-        // the state of mOAuth2Check is automatically recovered between configuration changes, but not before onCreate() finishes; so keep the next lines here\r
-        changeViewByOAuth2Check(mOAuth2Check.isChecked());  \r
         if (mAction == ACTION_UPDATE_TOKEN && mJustCreated && getIntent().getBooleanExtra(EXTRA_ENFORCED_UPDATE, false)) {\r
             if (mOAuth2Check.isChecked())\r
                 Toast.makeText(this, R.string.auth_expired_oauth_token_toast, Toast.LENGTH_LONG).show();\r
@@ -397,6 +476,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         }\r
 \r
         mJustCreated = false;\r
+        \r
     }\r
 \r
 \r
@@ -418,7 +498,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
                 getString(R.string.oauth2_grant_type),\r
                 queryParameters);\r
         //WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(getString(R.string.oauth2_url_endpoint_access)), getApplicationContext());\r
-        WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mOAuthTokenEndpointText.getText().toString().trim()), getApplicationContext());\r
+        WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mOAuthTokenEndpointText.getText().toString().trim()), getApplicationContext(), true);\r
         operation.execute(client, this, mHandler);\r
     }\r
 \r
@@ -482,7 +562,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             mServerStatusIcon = R.drawable.progress_small;\r
             showServerStatus();\r
             mOcServerChkOperation = new  OwnCloudServerCheckOperation(uri, this);\r
-            WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(uri), this);\r
+            WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(uri), this, true);\r
             mOperationThread = mOcServerChkOperation.execute(client, this, mHandler);\r
         } else {\r
             mServerStatusText = 0;\r
@@ -582,9 +662,10 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             return;\r
         }\r
 \r
-        if (mOAuth2Check.isChecked()) {\r
+        if (AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType)) {\r
             startOauthorization();\r
-\r
+        } else if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType)) { \r
+            startSamlBasedFederatedSingleSignOnAuthorization();\r
         } else {\r
             checkBasicAuthorization();\r
         }\r
@@ -597,7 +678,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
      */\r
     private void checkBasicAuthorization() {\r
         /// get the path to the root folder through WebDAV from the version server\r
-        String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, false);\r
+        String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, mAuthTokenType);\r
 \r
         /// get basic credentials entered by user\r
         String username = mUsernameInput.getText().toString();\r
@@ -608,7 +689,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
 \r
         /// test credentials accessing the root folder\r
         mAuthCheckOperation = new  ExistenceCheckOperation("", this, false);\r
-        WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this);\r
+        WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this, true);\r
         client.setBasicCredentials(username, password);\r
         mOperationThread = mAuthCheckOperation.execute(client, this, mHandler);\r
     }\r
@@ -623,6 +704,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         mAuthStatusIcon = R.drawable.progress_small;\r
         mAuthStatusText = R.string.oauth_login_connection;\r
         showAuthStatus();\r
+        \r
 \r
         // GET AUTHORIZATION request\r
         //Uri uri = Uri.parse(getString(R.string.oauth2_url_endpoint_auth));\r
@@ -641,6 +723,27 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
 \r
 \r
     /**\r
+     * Starts the Web Single Sign On flow to get access to the root folder\r
+     * in the server.\r
+     */\r
+    private void startSamlBasedFederatedSingleSignOnAuthorization() {\r
+        // be gentle with the user\r
+        mAuthStatusIcon = R.drawable.progress_small;\r
+        mAuthStatusText = R.string.auth_connecting_auth_server;\r
+        showAuthStatus();\r
+        showDialog(DIALOG_LOGIN_PROGRESS);\r
+        \r
+        /// get the path to the root folder through WebDAV from the version server\r
+        String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, mAuthTokenType);\r
+\r
+        /// test credentials accessing the root folder\r
+        mAuthCheckOperation = new  ExistenceCheckOperation("", this, false);\r
+        WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this, false);\r
+        mOperationThread = mAuthCheckOperation.execute(client, this, mHandler);\r
+      \r
+    }\r
+\r
+    /**\r
      * Callback method invoked when a RemoteOperation executed by this Activity finishes.\r
      * \r
      * Dispatches the operation flow to the right method.\r
@@ -655,9 +758,41 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             onGetOAuthAccessTokenFinish((OAuth2GetAccessToken)operation, result);\r
 \r
         } else if (operation instanceof ExistenceCheckOperation)  {\r
-            onAuthorizationCheckFinish((ExistenceCheckOperation)operation, result);\r
-\r
+            if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType)) {\r
+                onSamlBasedFederatedSingleSignOnAuthorizationStart(operation, result);\r
+                \r
+            } else {\r
+                onAuthorizationCheckFinish((ExistenceCheckOperation)operation, result);\r
+            }\r
+        }\r
+    }\r
+    \r
+    \r
+    private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperation operation, RemoteOperationResult result) {\r
+        try {\r
+            dismissDialog(DIALOG_LOGIN_PROGRESS);\r
+        } catch (IllegalArgumentException e) {\r
+            // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens\r
         }\r
+        \r
+        //if (result.isTemporalRedirection() || result.isIdPRedirection()) {\r
+        if (result.isIdPRedirection()) {\r
+            String url = result.getRedirectedLocation();\r
+            String targetUrl = mHostBaseUrl + AccountUtils.getWebdavPath(mDiscoveredVersion, mAuthTokenType);\r
+            \r
+            // Show dialog\r
+            mSamlDialog = SamlWebViewDialog.newInstance(url, targetUrl);            \r
+            mSamlDialog.show(getSupportFragmentManager(), TAG_SAML_DIALOG);\r
+            \r
+            mAuthStatusIcon = 0;\r
+            mAuthStatusText = 0;\r
+            \r
+        } else {\r
+            mAuthStatusIcon = R.drawable.common_error;\r
+            mAuthStatusText = R.string.auth_unsupported_auth_method;\r
+            \r
+        }\r
+        showAuthStatus();\r
     }\r
 \r
 \r
@@ -723,7 +858,6 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             }\r
 \r
         }\r
-        Log_OC.d(TAG, "URL Normalize " + url);\r
         return (url != null ? url : "");\r
     }\r
 \r
@@ -883,6 +1017,9 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         case OAUTH2_ERROR_ACCESS_DENIED:\r
             mAuthStatusText = R.string.auth_oauth_error_access_denied;\r
             break;\r
+        case ACCOUNT_NOT_NEW:\r
+            mAuthStatusText = R.string.auth_account_not_new;\r
+            break;\r
         case UNHANDLED_HTTP_CODE:\r
         case UNKNOWN_ERROR:\r
             mAuthStatusText = R.string.auth_unknown_error_title;\r
@@ -908,17 +1045,17 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             // NOTHING TO DO ; can't find out what situation that leads to the exception in this code, but user logs signal that it happens\r
         }\r
 \r
-        String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, true);\r
+        String webdav_path = AccountUtils.getWebdavPath(mDiscoveredVersion, mAuthTokenType);\r
         if (result.isSuccess() && webdav_path != null) {\r
             /// be gentle with the user\r
             showDialog(DIALOG_LOGIN_PROGRESS);\r
 \r
             /// time to test the retrieved access token on the ownCloud server\r
-            mOAuthAccessToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);\r
-            Log_OC.d(TAG, "Got ACCESS TOKEN: " + mOAuthAccessToken);\r
+            mAuthToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);\r
+            Log_OC.d(TAG, "Got ACCESS TOKEN: " + mAuthToken);\r
             mAuthCheckOperation = new ExistenceCheckOperation("", this, false);\r
-            WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this);\r
-            client.setBearerCredentials(mOAuthAccessToken);\r
+            WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this, true);\r
+            client.setBearerCredentials(mAuthToken);\r
             mAuthCheckOperation.execute(client, this, mHandler);\r
 \r
         } else {\r
@@ -947,14 +1084,17 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         if (result.isSuccess()) {\r
             Log_OC.d(TAG, "Successful access - time to save the account");\r
 \r
+            boolean success = true;\r
             if (mAction == ACTION_CREATE) {\r
-                createAccount();\r
+                success = createAccount();\r
 \r
             } else {\r
                 updateToken();\r
             }\r
 \r
-            finish();\r
+            if (success) {\r
+                finish();\r
+            }\r
 \r
         } else if (result.isServerFail() || result.isException()) {\r
             /// if server fail or exception in authorization, the UI is updated as when a server check failed\r
@@ -987,6 +1127,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             showAuthStatus();\r
             Log_OC.d(TAG, "Access failed: " + result.getLogMessage());\r
         }\r
+\r
     }\r
 \r
 \r
@@ -998,11 +1139,17 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         Bundle response = new Bundle();\r
         response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);\r
         response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);\r
-        boolean isOAuth = mOAuth2Check.isChecked();\r
-        if (isOAuth) {\r
-            response.putString(AccountManager.KEY_AUTHTOKEN, mOAuthAccessToken);\r
+        \r
+        if (AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType)) { \r
+            response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);\r
             // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention\r
-            mAccountMgr.setAuthToken(mAccount, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, mOAuthAccessToken);\r
+            mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);\r
+            \r
+        } else if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType)) {\r
+            response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);\r
+            // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention\r
+            mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);\r
+            \r
         } else {\r
             response.putString(AccountManager.KEY_AUTHTOKEN, mPasswordInput.getText().toString());\r
             mAccountMgr.setPassword(mAccount, mPasswordInput.getText().toString());\r
@@ -1018,13 +1165,17 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
      * \r
      * TODO Decide how to name the OAuth accounts\r
      */\r
-    private void createAccount() {\r
+    private boolean createAccount() {\r
         /// create and save new ownCloud account\r
-        boolean isOAuth = mOAuth2Check.isChecked();\r
+        boolean isOAuth = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType);\r
+        boolean isSaml =  AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType);\r
 \r
         Uri uri = Uri.parse(mHostBaseUrl);\r
         String username = mUsernameInput.getText().toString().trim();\r
-        if (isOAuth) {\r
+        if (isSaml) {\r
+            username = getUserNameForSamlSso();\r
+            \r
+        } else if (isOAuth) {\r
             username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();\r
         }            \r
         String accountName = username + "@" + uri.getHost();\r
@@ -1032,45 +1183,75 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             accountName += ":" + uri.getPort();\r
         }\r
         mAccount = new Account(accountName, AccountAuthenticator.ACCOUNT_TYPE);\r
-        if (isOAuth) {\r
-            mAccountMgr.addAccountExplicitly(mAccount, "", null);  // with our implementation, the password is never input in the app\r
+        if (AccountUtils.exists(mAccount, getApplicationContext())) {\r
+            // fail - not a new account, but an existing one; disallow\r
+            RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW); \r
+            updateAuthStatusIconAndText(result);\r
+            showAuthStatus();\r
+            Log_OC.d(TAG, result.getLogMessage());\r
+            return false;\r
+            \r
+            \r
         } else {\r
-            mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);\r
-        }\r
-\r
-        /// add the new account as default in preferences, if there is none already\r
-        Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);\r
-        if (defaultAccount == null) {\r
-            SharedPreferences.Editor editor = PreferenceManager\r
-                    .getDefaultSharedPreferences(this).edit();\r
-            editor.putString("select_oc_account", accountName);\r
-            editor.commit();\r
+        \r
+            if (isOAuth || isSaml) {\r
+                mAccountMgr.addAccountExplicitly(mAccount, "", null);  // with external authorizations, the password is never input in the app\r
+            } else {\r
+                mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);\r
+            }\r
+    \r
+            /// add the new account as default in preferences, if there is none already\r
+            Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);\r
+            if (defaultAccount == null) {\r
+                SharedPreferences.Editor editor = PreferenceManager\r
+                        .getDefaultSharedPreferences(this).edit();\r
+                editor.putString("select_oc_account", accountName);\r
+                editor.commit();\r
+            }\r
+    \r
+            /// prepare result to return to the Authenticator\r
+            //  TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done\r
+            final Intent intent = new Intent();       \r
+            intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE,    AccountAuthenticator.ACCOUNT_TYPE);\r
+            intent.putExtra(AccountManager.KEY_ACCOUNT_NAME,    mAccount.name);\r
+            /*if (!isOAuth)\r
+                intent.putExtra(AccountManager.KEY_AUTHTOKEN,   AccountAuthenticator.ACCOUNT_TYPE); */\r
+            intent.putExtra(AccountManager.KEY_USERDATA,        username);\r
+            if (isOAuth || isSaml) {\r
+                mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);\r
+            }\r
+            /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA\r
+            mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION,    mDiscoveredVersion.toString());\r
+            mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL,   mHostBaseUrl);\r
+            if (isSaml) {\r
+                mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE"); \r
+            } else if (isOAuth) {\r
+                mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2, "TRUE");  \r
+            }\r
+    \r
+            setAccountAuthenticatorResult(intent.getExtras());\r
+            setResult(RESULT_OK, intent);\r
+    \r
+            /// immediately request for the synchronization of the new account\r
+            Bundle bundle = new Bundle();\r
+            bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);\r
+            ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);\r
+            return true;\r
         }\r
+    }\r
 \r
-        /// prepare result to return to the Authenticator\r
-        //  TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done\r
-        final Intent intent = new Intent();       \r
-        intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE,    AccountAuthenticator.ACCOUNT_TYPE);\r
-        intent.putExtra(AccountManager.KEY_ACCOUNT_NAME,    mAccount.name);\r
-        if (!isOAuth)\r
-            intent.putExtra(AccountManager.KEY_AUTHTOKEN,   AccountAuthenticator.ACCOUNT_TYPE); // TODO check this; not sure it's right; maybe\r
-        intent.putExtra(AccountManager.KEY_USERDATA,        username);\r
-        if (isOAuth) {\r
-            mAccountMgr.setAuthToken(mAccount, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, mOAuthAccessToken);\r
+    \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
-        /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA\r
-        mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION,    mDiscoveredVersion.toString());\r
-        mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL,   mHostBaseUrl);\r
-        if (isOAuth)\r
-            mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2, "TRUE");  // TODO this flag should be unnecessary\r
-\r
-        setAccountAuthenticatorResult(intent.getExtras());\r
-        setResult(RESULT_OK, intent);\r
-\r
-        /// immediately request for the synchronization of the new account\r
-        Bundle bundle = new Bundle();\r
-        bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);\r
-        ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);\r
+        return "";\r
     }\r
 \r
 \r
@@ -1259,33 +1440,43 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
      * @param view      'View password' 'button'\r
      */\r
     public void onCheckClick(View view) {\r
-        CheckBox oAuth2Check = (CheckBox)view;      \r
-        changeViewByOAuth2Check(oAuth2Check.isChecked());\r
-\r
+        CheckBox oAuth2Check = (CheckBox)view;\r
+        if (oAuth2Check.isChecked()) {\r
+            mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN;\r
+        } else {\r
+            mAuthTokenType = AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD;\r
+        }\r
+        adaptViewAccordingToAuthenticationMethod();\r
     }\r
 \r
+    \r
     /**\r
-     * Changes the visibility of input elements depending upon the kind of authorization\r
-     * chosen by the user: basic or OAuth\r
-     * \r
-     * @param checked       'True' when OAuth is selected.\r
+     * Changes the visibility of input elements depending on\r
+     * the current authorization method.\r
      */\r
-    public void changeViewByOAuth2Check(Boolean checked) {\r
-\r
-        if (checked) {\r
+    private void adaptViewAccordingToAuthenticationMethod () {\r
+        if (AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType)) {\r
+            // OAuth 2 authorization\r
             mOAuthAuthEndpointText.setVisibility(View.VISIBLE);\r
             mOAuthTokenEndpointText.setVisibility(View.VISIBLE);\r
             mUsernameInput.setVisibility(View.GONE);\r
             mPasswordInput.setVisibility(View.GONE);\r
+            \r
+        } else if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType)) {\r
+            // SAML-based web Single Sign On\r
+            mOAuthAuthEndpointText.setVisibility(View.GONE);\r
+            mOAuthTokenEndpointText.setVisibility(View.GONE);\r
+            mUsernameInput.setVisibility(View.GONE);\r
+            mPasswordInput.setVisibility(View.GONE);\r
         } else {\r
+            // basic HTTP authorization\r
             mOAuthAuthEndpointText.setVisibility(View.GONE);\r
             mOAuthTokenEndpointText.setVisibility(View.GONE);\r
             mUsernameInput.setVisibility(View.VISIBLE);\r
             mPasswordInput.setVisibility(View.VISIBLE);\r
-        }     \r
-\r
-    }    \r
-\r
+        }\r
+    }\r
+    \r
     /**\r
      * Called from SslValidatorDialog when a new server certificate was correctly saved.\r
      */\r
@@ -1306,15 +1497,20 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     /**\r
      *  Called when the 'action' button in an IME is pressed ('enter' in software keyboard).\r
      * \r
-     *  Used to trigger the authorization check when the user presses 'enter' after writing the password.\r
+     *  Used to trigger the authentication check when the user presses 'enter' after writing the password, \r
+     *  or to throw the server test when the only field on screen is the URL input field.\r
      */\r
     @Override\r
     public boolean onEditorAction(TextView inputField, int actionId, KeyEvent event) {\r
-        if (inputField != null && inputField.equals(mPasswordInput) && \r
-                actionId == EditorInfo.IME_ACTION_DONE) {\r
+        if (actionId == EditorInfo.IME_ACTION_DONE && inputField != null && inputField.equals(mPasswordInput)) {\r
             if (mOkButton.isEnabled()) {\r
                 mOkButton.performClick();\r
             }\r
+            \r
+        } else if (actionId == EditorInfo.IME_ACTION_NEXT && inputField != null && inputField.equals(mHostUrlInput)) {\r
+            if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType)) {\r
+                checkOcServer();\r
+            }\r
         }\r
         return false;   // always return false to grant that the software keyboard is hidden anyway\r
     }\r
@@ -1352,4 +1548,64 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         public abstract boolean onDrawableTouch(final MotionEvent event);\r
     }\r
 \r
+\r
+    public void onSamlDialogSuccess(String sessionCookie){\r
+        mAuthToken = sessionCookie;\r
+        \r
+        if (sessionCookie != null && sessionCookie.length() > 0) {\r
+            mAuthToken = sessionCookie;\r
+            boolean success = true;\r
+            if (mAction == ACTION_CREATE) {\r
+                success = createAccount();\r
+        \r
+            } else {\r
+                updateToken();\r
+            }\r
+            if (success) {\r
+                finish();\r
+            }\r
+        }\r
+\r
+            \r
+    }\r
+\r
+\r
+    @Override\r
+    public void onSsoFinished(String sessionCookies) {\r
+        //Toast.makeText(this, "got cookies: " + sessionCookie, Toast.LENGTH_LONG).show();\r
+\r
+        if (sessionCookies != null && sessionCookies.length() > 0) {\r
+            Log_OC.d(TAG, "Successful SSO - time to save the account");\r
+            onSamlDialogSuccess(sessionCookies);\r
+            Fragment fd = getSupportFragmentManager().findFragmentByTag(TAG_SAML_DIALOG);\r
+            if (fd != null && fd instanceof SherlockDialogFragment) {\r
+                Dialog d = ((SherlockDialogFragment)fd).getDialog();\r
+                if (d != null && d.isShowing()) {\r
+                    d.dismiss();\r
+                }\r
+            }\r
+\r
+        } else { \r
+            // TODO - show fail\r
+            Log_OC.d(TAG, "SSO failed");\r
+        }\r
+    \r
+    }\r
+    \r
+\r
+    private void syncAccount(){\r
+        /// immediately request for the synchronization of the new account\r
+        Bundle bundle = new Bundle();\r
+        bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);\r
+        ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);\r
+    }\r
+    \r
+    @Override\r
+    public boolean onTouchEvent(MotionEvent event) {\r
+        if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType) &&\r
+                mHostUrlInput.hasFocus() && event.getAction() == MotionEvent.ACTION_DOWN) {\r
+            checkOcServer();\r
+        }\r
+        return super.onTouchEvent(event);\r
+    }\r
 }\r
diff --git a/src/com/owncloud/android/authentication/SsoWebViewClient.java b/src/com/owncloud/android/authentication/SsoWebViewClient.java
new file mode 100644 (file)
index 0000000..4f26a80
--- /dev/null
@@ -0,0 +1,175 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2012-2013 ownCloud Inc.
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License version 2,
+ *   as published by the Free Software Foundation.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+package com.owncloud.android.authentication;
+
+import java.lang.ref.WeakReference;
+
+import com.owncloud.android.Log_OC;
+
+import android.graphics.Bitmap;
+import android.os.Handler;
+import android.os.Message;
+import android.view.View;
+import android.webkit.CookieManager;
+import android.webkit.WebView;
+import android.webkit.WebViewClient;
+
+
+/**
+ * Custom {@link WebViewClient} client aimed to catch the end of a single-sign-on process 
+ * running in the {@link WebView} that is attached to.
+ * 
+ * Assumes that the single-sign-on is kept thanks to a cookie set at the end of the
+ * authentication process.
+ *   
+ * @author David A. Velasco
+ */
+public class SsoWebViewClient extends WebViewClient {
+        
+    private static final String TAG = SsoWebViewClient.class.getSimpleName();
+    
+    public interface SsoWebViewClientListener {
+        public void onSsoFinished(String sessionCookie);
+    }
+    
+    private Handler mListenerHandler;
+    private WeakReference<SsoWebViewClientListener> mListenerRef;
+    private String mTargetUrl;
+    private String mLastReloadedUrlAtError;
+    
+    public SsoWebViewClient (Handler listenerHandler, SsoWebViewClientListener listener) {
+        mListenerHandler = listenerHandler;
+        mListenerRef = new WeakReference<SsoWebViewClient.SsoWebViewClientListener>(listener);
+        mTargetUrl = "fake://url.to.be.set";
+        mLastReloadedUrlAtError = null;
+    }
+    
+    public String getTargetUrl() {
+        return mTargetUrl;
+    }
+    
+    public void setTargetUrl(String targetUrl) {
+        mTargetUrl = targetUrl;
+    }
+
+    @Override
+    public void onPageStarted (WebView view, String url, Bitmap favicon) {
+        Log_OC.d(TAG, "onPageStarted : " + url);
+        super.onPageStarted(view, url, favicon);
+    }
+    
+    @Override
+    public void onFormResubmission (WebView view, Message dontResend, Message resend) {
+        Log_OC.d(TAG, "onFormResubMission ");
+
+        // necessary to grant reload of last page when device orientation is changed after sending a form
+        resend.sendToTarget();
+    }
+
+    @Override
+    public boolean shouldOverrideUrlLoading(WebView view, String url) {
+        return false;
+    }
+    
+    @Override
+    public void onReceivedError (WebView view, int errorCode, String description, String failingUrl) {
+        Log_OC.e(TAG, "onReceivedError : " + failingUrl + ", code " + errorCode + ", description: " + description);
+        if (!failingUrl.equals(mLastReloadedUrlAtError)) {
+            view.reload();
+            mLastReloadedUrlAtError = failingUrl;
+        } else {
+            mLastReloadedUrlAtError = null;
+            super.onReceivedError(view, errorCode, description, failingUrl);
+        }
+    }
+    
+    @Override
+    public void onPageFinished (WebView view, String url) {
+        Log_OC.d(TAG, "onPageFinished : " + url);
+        mLastReloadedUrlAtError = null;
+        if (url.startsWith(mTargetUrl)) {
+            view.setVisibility(View.GONE);
+            CookieManager cookieManager = CookieManager.getInstance();
+            final String cookies = cookieManager.getCookie(url);
+            //Log_OC.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() {
+                    @Override
+                    public void run() {
+                        SsoWebViewClientListener listener = mListenerRef.get();
+                        if (listener != null) {
+                            listener.onSsoFinished(cookies);
+                        }
+                    }
+                });
+            }
+        }
+
+    }
+    
+    /*
+    @Override
+    public void doUpdateVisitedHistory (WebView view, String url, boolean isReload) {
+        Log_OC.d(TAG, "doUpdateVisitedHistory : " + url);
+    }
+    
+    @Override
+    public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
+        Log_OC.d(TAG, "onReceivedSslError : " + error);
+    }
+    
+    @Override
+    public void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm) {
+        Log_OC.d(TAG, "onReceivedHttpAuthRequest : " + host);
+    }
+
+    @Override
+    public WebResourceResponse shouldInterceptRequest (WebView view, String url) {
+        Log_OC.d(TAG, "shouldInterceptRequest : " + url);
+        return null;
+    }
+    
+    @Override
+    public void onLoadResource (WebView view, String url) {
+        Log_OC.d(TAG, "onLoadResource : " + url);   
+    }
+    
+    @Override
+    public void onReceivedLoginRequest (WebView view, String realm, String account, String args) {
+        Log_OC.d(TAG, "onReceivedLoginRequest : " + realm + ", " + account + ", " + args);
+    }
+    
+    @Override
+    public void onScaleChanged (WebView view, float oldScale, float newScale) {
+        Log_OC.d(TAG, "onScaleChanged : " + oldScale + " -> " + newScale);
+        super.onScaleChanged(view, oldScale, newScale);
+    }
+
+    @Override
+    public void onUnhandledKeyEvent (WebView view, KeyEvent event) {
+        Log_OC.d(TAG, "onUnhandledKeyEvent : " + event);
+    }
+    
+    @Override
+    public boolean shouldOverrideKeyEvent (WebView view, KeyEvent event) {
+        Log_OC.d(TAG, "shouldOverrideKeyEvent : " + event);
+        return false;
+    }
+    */
+}
index 04fb7ac..17abf6f 100644 (file)
@@ -90,12 +90,16 @@ public class OwnCloudClientUtils {
         //Log_OC.d(TAG, "Creating WebdavClient associated to " + account.name);
        
         Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account));
-        WebdavClient client = createOwnCloudClient(uri, appContext);
+        WebdavClient client = createOwnCloudClient(uri, appContext, true);
         AccountManager am = AccountManager.get(appContext);
         if (am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null) {    // TODO avoid a call to getUserData here
             String accessToken = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, false);
             client.setBearerCredentials(accessToken);   // TODO not assume that the access token is a bearer token
         
+        } else if (am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO) != null) {    // TODO avoid a call to getUserData here
+            String accessToken = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE, false);
+            client.setSsoSessionCookie(accessToken);
+            
         } else {
             String username = account.name.substring(0, account.name.lastIndexOf('@'));
             //String password = am.getPassword(account);
@@ -109,16 +113,22 @@ public class OwnCloudClientUtils {
     
     public static WebdavClient createOwnCloudClient (Account account, Context appContext, Activity currentActivity) throws OperationCanceledException, AuthenticatorException, IOException, AccountNotFoundException {
         Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account));
-        WebdavClient client = createOwnCloudClient(uri, appContext);
+        WebdavClient client = createOwnCloudClient(uri, appContext, true);
         AccountManager am = AccountManager.get(appContext);
         if (am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null) {    // TODO avoid a call to getUserData here
             AccountManagerFuture<Bundle> future =  am.getAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, null, currentActivity, null, null);
             Bundle result = future.getResult();
             String accessToken = result.getString(AccountManager.KEY_AUTHTOKEN);
-            //String accessToken = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, false);
             if (accessToken == null) throw new AuthenticatorException("WTF!");
             client.setBearerCredentials(accessToken);   // TODO not assume that the access token is a bearer token
-            
+
+        } else if (am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO) != null) {    // TODO avoid a call to getUserData here
+            AccountManagerFuture<Bundle> future =  am.getAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE, null, currentActivity, null, null);
+            Bundle result = future.getResult();
+            String accessToken = result.getString(AccountManager.KEY_AUTHTOKEN);
+            if (accessToken == null) throw new AuthenticatorException("WTF!");
+            client.setSsoSessionCookie(accessToken);
+
         } else {
             String username = account.name.substring(0, account.name.lastIndexOf('@'));
             //String password = am.getPassword(account);
@@ -139,10 +149,7 @@ public class OwnCloudClientUtils {
      * @param context   Android context where the WebdavClient is being created.
      * @return          A WebdavClient object ready to be used
      */
-    public static WebdavClient createOwnCloudClient(Uri uri, Context context) {
-        //Log_OC.d(TAG, "Creating WebdavClient for " + uri);
-        
-        //allowSelfsignedCertificates(true);
+    public static WebdavClient createOwnCloudClient(Uri uri, Context context, boolean followRedirects) {
         try {
             registerAdvancedSslContext(true, context);
         }  catch (GeneralSecurityException e) {
@@ -156,6 +163,7 @@ public class OwnCloudClientUtils {
         
         client.setDefaultTimeouts(DEFAULT_DATA_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
         client.setBaseUri(uri);
+        client.setFollowRedirects(followRedirects);
         
         return client;
     }
index 1093986..e404a6f 100644 (file)
@@ -69,7 +69,7 @@ public class ExistenceCheckOperation extends RemoteOperation {
             int status = client.executeMethod(head, TIMEOUT, TIMEOUT);
             client.exhaustResponse(head.getResponseBodyAsStream());
             boolean success = (status == HttpStatus.SC_OK && !mSuccessIfAbsent) || (status == HttpStatus.SC_NOT_FOUND && mSuccessIfAbsent);
-            result = new RemoteOperationResult(success, status);
+            result = new RemoteOperationResult(success, status, head.getResponseHeaders());
             Log_OC.d(TAG, "Existence check for " + client.getBaseUri() + mPath + " targeting for " + (mSuccessIfAbsent ? " absence " : " existence ") + "finished with HTTP status " + status + (!success?"(FAIL)":""));
             
         } catch (Exception e) {
index 711a72b..9afb856 100644 (file)
@@ -278,4 +278,5 @@ public abstract class RemoteOperation implements Runnable {
         return mClient;
     }
 
+
 }
index 60cdcb2..1679bf7 100644 (file)
@@ -28,6 +28,7 @@ import java.net.UnknownHostException;
 import javax.net.ssl.SSLException;
 
 import org.apache.commons.httpclient.ConnectTimeoutException;
+import org.apache.commons.httpclient.Header;
 import org.apache.commons.httpclient.HttpException;
 import org.apache.commons.httpclient.HttpStatus;
 import org.apache.jackrabbit.webdav.DavException;
@@ -50,7 +51,7 @@ import com.owncloud.android.network.CertificateCombinedException;
 public class RemoteOperationResult implements Serializable {
 
     /** Generated - should be refreshed every time the class changes!! */
-    private static final long serialVersionUID = 6106167714625712390L;
+    private static final long serialVersionUID = 3267227833178885664L;
 
     
     private static final String TAG = "RemoteOperationResult";
@@ -84,13 +85,15 @@ public class RemoteOperationResult implements Serializable {
         OAUTH2_ERROR_ACCESS_DENIED,
         QUOTA_EXCEEDED, 
         ACCOUNT_NOT_FOUND, 
-        ACCOUNT_EXCEPTION
+        ACCOUNT_EXCEPTION, 
+        ACCOUNT_NOT_NEW
     }
 
     private boolean mSuccess = false;
     private int mHttpCode = -1;
     private Exception mException = null;
     private ResultCode mCode = ResultCode.UNKNOWN_ERROR;
+    private String mRedirectedLocation;
 
     public RemoteOperationResult(ResultCode code) {
         mCode = code;
@@ -123,10 +126,24 @@ public class RemoteOperationResult implements Serializable {
                 break;
             default:
                 mCode = ResultCode.UNHANDLED_HTTP_CODE;
-                Log_OC.d(TAG, "RemoteOperationResult has prcessed UNHANDLED_HTTP_CODE: " + httpCode);
+                Log_OC.d(TAG, "RemoteOperationResult has processed UNHANDLED_HTTP_CODE: " + httpCode);
             }
         }
     }
+    
+    public RemoteOperationResult(boolean success, int httpCode, Header[] headers) {
+        this(success, httpCode);
+        if (headers != null) {
+            Header current;
+            for (int i=0; i<headers.length; i++) {
+                current = headers[i];
+                if ("Location".equals(current.getName())) {
+                    mRedirectedLocation = current.getValue();
+                    break;
+                }
+            }
+        }
+    }    
 
     public RemoteOperationResult(Exception e) {
         mException = e;
@@ -281,6 +298,9 @@ public class RemoteOperationResult implements Serializable {
 
         } else if (mCode == ResultCode.LOCAL_STORAGE_NOT_MOVED) {
             return "Error while moving file to final directory";
+
+        } else if (mCode == ResultCode.ACCOUNT_NOT_NEW) {
+            return "Account already existing when creating a new one";
         }
 
         return "Operation finished with HTTP status code " + mHttpCode + " (" + (isSuccess() ? "success" : "fail") + ")";
@@ -295,4 +315,18 @@ public class RemoteOperationResult implements Serializable {
         return (mException != null);
     }
 
+    public boolean isTemporalRedirection() {
+        return (mHttpCode == 302 || mHttpCode == 307);
+    }
+
+    public String getRedirectedLocation() {
+        return mRedirectedLocation;
+    }
+    
+    public boolean isIdPRedirection() {
+        return (mRedirectedLocation != null &&
+                (mRedirectedLocation.toUpperCase().contains("SAML") || 
+                mRedirectedLocation.toLowerCase().contains("wayf")));
+    }
+
 }
index 3c1a64f..7b157c3 100644 (file)
@@ -28,6 +28,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Vector;
 
+import org.apache.commons.httpclient.Header;
 import org.apache.http.HttpStatus;
 import org.apache.jackrabbit.webdav.MultiStatus;
 import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
@@ -208,9 +209,9 @@ public class SynchronizeFolderOperation extends RemoteOperation {
                         } else {
                             mFailsInFavouritesFound++;
                             if (contentsResult.getException() != null) {
-                                Log_OC.d(TAG, "Error while synchronizing favourites : " +  contentsResult.getLogMessage(), contentsResult.getException());
+                                Log_OC.e(TAG, "Error while synchronizing favourites : " +  contentsResult.getLogMessage(), contentsResult.getException());
                             } else {
-                                Log_OC.d(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage());
+                                Log_OC.e(TAG, "Error while synchronizing favourites : " + contentsResult.getLogMessage());
                             }
                         }
                     }   // won't let these fails break the synchronization process
@@ -243,20 +244,35 @@ public class SynchronizeFolderOperation extends RemoteOperation {
                             
                 } else {
                     result = new RemoteOperationResult(true, status);
+                    Header hCookie = query.getResponseHeader("Cookie");
+                    if (hCookie != null) {
+                        Log_OC.e(TAG, "PROPFIND cookie: " + hCookie.getValue());
+                    } else {
+                        Log_OC.e(TAG, "PROPFIND NO COOKIE");
+                    }
                 }
             } else {
                 result = new RemoteOperationResult(false, status);
             }
-            Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
+            
             
             
         } catch (Exception e) {
             result = new RemoteOperationResult(e);
-            Log_OC.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException());
+            
 
         } finally {
             if (query != null)
                 query.releaseConnection();  // let the connection available for other methods
+            if (result.isSuccess()) {
+                Log_OC.i(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
+            } else {
+                if (result.isException()) {
+                    Log_OC.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage(), result.getException());
+                } else {
+                    Log_OC.e(TAG, "Synchronizing " + mAccount.name + ", folder " + mRemotePath + ": " + result.getLogMessage());
+                }
+            }
         }
         
         return result;
index 1a1cd51..2c3448d 100644 (file)
@@ -50,6 +50,7 @@ import com.actionbarsherlock.view.MenuItem;
 import com.owncloud.android.authentication.AccountAuthenticator;
 import com.owncloud.android.authentication.AuthenticatorActivity;
 import com.owncloud.android.authentication.AccountUtils;
+import com.owncloud.android.ui.activity.FileActivity.AccountCreationCallback;
 import com.owncloud.android.Log_OC;
 
 import com.owncloud.android.R;
@@ -133,11 +134,20 @@ public class AccountSelectActivity extends SherlockListActivity implements
     @Override
     public boolean onMenuItemSelected(int featureId, MenuItem item) {
         if (item.getItemId() == R.id.createAccount) {
-            Intent intent = new Intent(
+            /*Intent intent = new Intent(
                     android.provider.Settings.ACTION_ADD_ACCOUNT);
             intent.putExtra("authorities",
                     new String[] { AccountAuthenticator.AUTHORITY });
-            startActivity(intent);
+            startActivity(intent);*/
+            AccountManager am = AccountManager.get(getApplicationContext());
+            am.addAccount(AccountAuthenticator.ACCOUNT_TYPE, 
+                            null,
+                            null, 
+                            null, 
+                            this, 
+                            null,                        
+                            null);
+            
             return true;
         }
         return false;
index a23b3be..2e47ce0 100644 (file)
@@ -174,7 +174,7 @@ public abstract class FileActivity extends SherlockFragmentActivity {
     private void createFirstAccount() {
         AccountManager am = AccountManager.get(getApplicationContext());
         am.addAccount(AccountAuthenticator.ACCOUNT_TYPE, 
-                        AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD,
+                        null,
                         null, 
                         null, 
                         this, 
diff --git a/src/com/owncloud/android/ui/dialog/SamlWebViewDialog.java b/src/com/owncloud/android/ui/dialog/SamlWebViewDialog.java
new file mode 100644 (file)
index 0000000..fe20d81
--- /dev/null
@@ -0,0 +1,284 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2012-2013 ownCloud Inc.
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License version 2,
+ *   as published by the Free Software Foundation.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+package com.owncloud.android.ui.dialog;
+
+import android.annotation.SuppressLint;
+import android.app.Activity;
+import android.app.Dialog;
+import android.content.DialogInterface;
+import android.os.Bundle;
+import android.os.Handler;
+import android.support.v4.app.FragmentTransaction;
+import android.support.v4.app.FragmentManager;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.webkit.CookieManager;
+import android.webkit.CookieSyncManager;
+import android.webkit.WebBackForwardList;
+import android.webkit.WebSettings;
+import android.webkit.WebView;
+
+import com.actionbarsherlock.app.SherlockDialogFragment;
+import com.owncloud.android.Log_OC;
+import com.owncloud.android.R;
+import com.owncloud.android.authentication.SsoWebViewClient;
+import com.owncloud.android.authentication.SsoWebViewClient.SsoWebViewClientListener;
+
+import eu.alefzero.webdav.WebdavClient;
+
+/**
+ * Dialog to show the WebView for SAML Authentication
+ * 
+ * @author Maria Asensio
+ * @author David A. Velasco
+ */
+public class SamlWebViewDialog extends SherlockDialogFragment {
+
+    public final String SAML_DIALOG_TAG = "SamlWebViewDialog";
+    
+    private final static String TAG =  SamlWebViewDialog.class.getSimpleName();
+
+    private static final String ARG_INITIAL_URL = "INITIAL_URL";
+    private static final String ARG_TARGET_URL = "TARGET_URL";
+    private static final String KEY_WEBVIEW_STATE = "WEBVIEW_STATE";
+    
+    private WebView mSsoWebView;
+    private SsoWebViewClient mWebViewClient;
+    
+    private String mInitialUrl;
+    private String mTargetUrl;
+    
+    private Handler mHandler;
+
+    private SsoWebViewClientListener mSsoWebViewClientListener;
+
+    //private View mSsoRootView;
+
+
+    /**
+     * Public factory method to get dialog instances.
+     * 
+     * @param handler
+     * @param Url           Url to open at WebView
+     * @param targetURL     mHostBaseUrl + AccountUtils.getWebdavPath(mDiscoveredVersion, mCurrentAuthTokenType)
+     * @return              New dialog instance, ready to show.
+     */
+    public static SamlWebViewDialog newInstance(String url, String targetUrl) {
+        Log_OC.d(TAG, "New instance");
+        SamlWebViewDialog fragment = new SamlWebViewDialog();
+        Bundle args = new Bundle();
+        args.putString(ARG_INITIAL_URL, url);
+        args.putString(ARG_TARGET_URL, targetUrl);
+        fragment.setArguments(args);
+        return fragment;
+    }
+    
+    
+    public SamlWebViewDialog() {
+        super();
+        Log_OC.d(TAG, "constructor");
+    }
+    
+    
+    @Override
+    public void onAttach(Activity activity) {
+        Log_OC.d(TAG, "onAttach");
+        super.onAttach(activity);
+        try {
+            mSsoWebViewClientListener = (SsoWebViewClientListener) activity;
+            mHandler = new Handler();
+            mWebViewClient = new SsoWebViewClient(mHandler, mSsoWebViewClientListener);
+            
+       } catch (ClassCastException e) {
+            throw new ClassCastException(activity.toString() + " must implement " + SsoWebViewClientListener.class.getSimpleName());
+        }
+    }
+
+    
+    @SuppressLint("SetJavaScriptEnabled")
+    @Override
+    public void onCreate(Bundle savedInstanceState) {
+        Log_OC.d(TAG, "onCreate");
+        super.onCreate(savedInstanceState);
+        
+        CookieSyncManager.createInstance(getActivity());
+        
+        if (savedInstanceState == null) {
+            mInitialUrl = getArguments().getString(ARG_INITIAL_URL);
+            mTargetUrl = getArguments().getString(ARG_TARGET_URL);
+        } else {
+            mInitialUrl = savedInstanceState.getString(ARG_INITIAL_URL);
+            mTargetUrl = savedInstanceState.getString(ARG_TARGET_URL);
+        }
+        
+        setStyle(SherlockDialogFragment.STYLE_NO_TITLE, R.style.Theme_ownCloud_Dialog);
+    }
+    
+    @Override
+    public Dialog onCreateDialog(Bundle savedInstanceState) {
+        Log_OC.d(TAG, "onCreateDialog");
+
+        /*
+        // build the dialog
+        AlertDialog.Builder builder = new AlertDialog.Builder(getSherlockActivity());
+        if (mSsoRootView.getParent() != null) {
+            ((ViewGroup)(mSsoRootView.getParent())).removeView(mSsoRootView);
+        }
+        builder.setView(mSsoRootView);
+        //builder.setView(mSsoWebView);
+        Dialog dialog = builder.create();
+        */
+        
+        return super.onCreateDialog(savedInstanceState);
+    }
+
+    @SuppressLint("SetJavaScriptEnabled")
+    @Override
+    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+        Log_OC.d(TAG, "onCreateView");
+        
+        // Inflate layout of the dialog  
+        View rootView = inflater.inflate(R.layout.sso_dialog, container, false);  // null parent view because it will go in the dialog layout
+        mSsoWebView  = (WebView) rootView.findViewById(R.id.sso_webview);
+            
+        mWebViewClient.setTargetUrl(mTargetUrl);
+        mSsoWebView.setWebViewClient(mWebViewClient);
+        
+        if (savedInstanceState == null) {
+            Log_OC.d(TAG,  "   initWebView start");
+            CookieManager cookieManager = CookieManager.getInstance();
+            cookieManager.setAcceptCookie(true);
+            cookieManager.removeAllCookie();
+            mSsoWebView.loadUrl(mInitialUrl);
+            
+        } else {
+            Log_OC.d(TAG, "   restoreWebView start");
+            WebBackForwardList history = mSsoWebView.restoreState(savedInstanceState.getBundle(KEY_WEBVIEW_STATE));
+            if (history == null) {
+                Log_OC.e(TAG, "Error restoring WebView state ; back to starting URL");
+                mSsoWebView.loadUrl(mInitialUrl);
+            }
+        }
+
+        WebSettings webSettings = mSsoWebView.getSettings();
+        webSettings.setJavaScriptEnabled(true);
+        webSettings.setBuiltInZoomControls(true);
+        webSettings.setLoadWithOverviewMode(false);
+        webSettings.setSavePassword(false);
+        webSettings.setUserAgentString(WebdavClient.USER_AGENT);
+        webSettings.setSaveFormData(false);
+        
+        return rootView;
+    }
+
+    @Override
+    public void onSaveInstanceState(Bundle outState) {
+        Log_OC.d(SAML_DIALOG_TAG, "onSaveInstanceState being CALLED");
+        super.onSaveInstanceState(outState);
+        
+        // save URLs
+        outState.putString(ARG_INITIAL_URL, mInitialUrl);
+        outState.putString(ARG_TARGET_URL, mTargetUrl);
+        
+        // Save the state of the WebView
+        Bundle webviewState = new Bundle();
+        mSsoWebView.saveState(webviewState);
+        outState.putBundle(KEY_WEBVIEW_STATE, webviewState);
+    }
+
+    @Override
+    public void onDestroyView() {
+        Log_OC.d(TAG, "onDestroyView");
+        
+        mSsoWebView.setWebViewClient(null);
+        
+        // Work around bug: http://code.google.com/p/android/issues/detail?id=17423
+        Dialog dialog = getDialog();
+        if ((dialog != null)) {
+            dialog.setOnDismissListener(null);
+            //dialog.dismiss();
+            //dialog.setDismissMessage(null);
+        }
+        
+        super.onDestroyView();
+    }
+    
+    @Override
+    public void onDestroy() {
+        Log_OC.d(TAG, "onDestroy");
+        super.onDestroy();
+    }
+
+    @Override
+    public void onDetach() {
+        Log_OC.d(TAG, "onDetach");
+        mSsoWebViewClientListener = null;
+        mWebViewClient = null;
+        super.onDetach();
+    }
+    
+    @Override
+    public void onCancel (DialogInterface dialog) {
+        Log_OC.d(SAML_DIALOG_TAG, "onCancel");
+        super.onCancel(dialog);
+    }
+    
+    @Override
+    public void onDismiss (DialogInterface dialog) {
+        Log_OC.d(SAML_DIALOG_TAG, "onDismiss");
+        super.onDismiss(dialog);
+    }
+    
+    @Override
+    public void onStart() {
+        Log_OC.d(SAML_DIALOG_TAG, "onStart");
+        super.onStart();
+    }
+
+    @Override
+    public void onStop() {
+        Log_OC.d(SAML_DIALOG_TAG, "onStop");
+        super.onStop();
+    }
+
+    @Override
+    public void onResume() {
+        Log_OC.d(SAML_DIALOG_TAG, "onResume");
+        super.onResume();
+    }
+
+    @Override
+    public void onPause() {
+        Log_OC.d(SAML_DIALOG_TAG, "onPause");
+        super.onPause();
+    }
+    
+    @Override
+    public int show (FragmentTransaction transaction, String tag) {
+        Log_OC.d(SAML_DIALOG_TAG, "show (transaction)");
+        return super.show(transaction, tag);
+    }
+
+    @Override
+    public void show (FragmentManager manager, String tag) {
+        Log_OC.d(SAML_DIALOG_TAG, "show (manager)");
+        super.show(manager, tag);
+    }
+
+}
\ No newline at end of file
diff --git a/src/com/owncloud/android/ui/dialog/SsoWebView.java b/src/com/owncloud/android/ui/dialog/SsoWebView.java
new file mode 100644 (file)
index 0000000..3a71139
--- /dev/null
@@ -0,0 +1,40 @@
+/* ownCloud Android client application
+ *   Copyright (C) 2012-2013 ownCloud Inc.
+ *
+ *   This program is free software: you can redistribute it and/or modify
+ *   it under the terms of the GNU General Public License version 2,
+ *   as published by the Free Software Foundation.
+ *
+ *   This program is distributed in the hope that it will be useful,
+ *   but WITHOUT ANY WARRANTY; without even the implied warranty of
+ *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ *   GNU General Public License for more details.
+ *
+ *   You should have received a copy of the GNU General Public License
+ *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+package com.owncloud.android.ui.dialog;
+
+import android.content.Context;
+import android.util.AttributeSet;
+import android.webkit.WebView;
+
+public class SsoWebView extends WebView {
+    
+    public SsoWebView(Context context) {
+        super(context);
+    }
+    
+    public SsoWebView(Context context, AttributeSet attr) {
+        super(context, attr);
+    }
+    
+    @Override
+    public boolean onCheckIsTextEditor () {
+        return false;
+    }
+    
+}
+
index fdabebe..570ebb8 100644 (file)
 
 package eu.alefzero.webdav;
 
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.ArrayList;
 import java.util.List;
 
 import org.apache.commons.httpclient.Credentials;
-import org.apache.commons.httpclient.HostConfiguration;
 import org.apache.commons.httpclient.HttpClient;
 import org.apache.commons.httpclient.HttpConnectionManager;
 import org.apache.commons.httpclient.HttpException;
 import org.apache.commons.httpclient.HttpMethod;
 import org.apache.commons.httpclient.HttpMethodBase;
-import org.apache.commons.httpclient.HttpState;
 import org.apache.commons.httpclient.HttpVersion;
 import org.apache.commons.httpclient.UsernamePasswordCredentials;
 import org.apache.commons.httpclient.auth.AuthPolicy;
 import org.apache.commons.httpclient.auth.AuthScope;
-import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.httpclient.cookie.CookiePolicy;
 import org.apache.commons.httpclient.methods.HeadMethod;
-import org.apache.commons.httpclient.methods.PutMethod;
 import org.apache.commons.httpclient.params.HttpMethodParams;
 import org.apache.http.HttpStatus;
 import org.apache.http.params.CoreProtocolPNames;
-import org.apache.jackrabbit.webdav.client.methods.DavMethod;
-import org.apache.jackrabbit.webdav.client.methods.DeleteMethod;
 
 import com.owncloud.android.Log_OC;
 
@@ -57,10 +49,11 @@ import android.net.Uri;
 public class WebdavClient extends HttpClient {
     private Uri mUri;
     private Credentials mCredentials;
+    private boolean mFollowRedirects;
+    private String mSsoSessionCookie;
     final private static String TAG = "WebdavClient";
-    private static final String USER_AGENT = "Android-ownCloud";
+    public static final String USER_AGENT = "Android-ownCloud";
     
-    private OnDatatransferProgressListener mDataTransferListener;
     static private byte[] sExhaustBuffer = new byte[1024];
     
     /**
@@ -71,6 +64,8 @@ public class WebdavClient extends HttpClient {
         Log_OC.d(TAG, "Creating WebdavClient");
         getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
         getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
+        mFollowRedirects = true;
+        mSsoSessionCookie = null;
     }
 
     public void setBearerCredentials(String accessToken) {
@@ -82,6 +77,7 @@ public class WebdavClient extends HttpClient {
         
         mCredentials = new BearerCredentials(accessToken);
         getState().setCredentials(AuthScope.ANY, mCredentials);
+        mSsoSessionCookie = null;
     }
 
     public void setBasicCredentials(String username, String password) {
@@ -92,8 +88,17 @@ public class WebdavClient extends HttpClient {
         getParams().setAuthenticationPreemptive(true);
         mCredentials = new UsernamePasswordCredentials(username, password);
         getState().setCredentials(AuthScope.ANY, mCredentials);
+        mSsoSessionCookie = null;
     }
     
+    public void setSsoSessionCookie(String accessToken) {
+        getParams().setAuthenticationPreemptive(false);
+        getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
+        mSsoSessionCookie = accessToken;
+        mCredentials = null;
+    }
+    
+    
     /**
      * Check if a file exists in the OC server
      * 
@@ -145,6 +150,21 @@ public class WebdavClient extends HttpClient {
             getHttpConnectionManager().getParams().setConnectionTimeout(oldConnectionTimeout);
         }
     }
+    
+    
+    @Override
+    public int executeMethod(HttpMethod method) throws IOException, HttpException {
+        try {
+            method.setFollowRedirects(mFollowRedirects);
+        } catch (Exception e) {
+            
+        }
+        if (mSsoSessionCookie != null && mSsoSessionCookie.length() > 0) {
+            method.setRequestHeader("Cookie", mSsoSessionCookie);
+        }
+        return super.executeMethod(method);
+    }
+
 
     /**
      * Exhausts a not interesting HTTP response. Encouraged by HttpClient documentation.
@@ -185,6 +205,10 @@ public class WebdavClient extends HttpClient {
 
     public final Credentials getCredentials() {\r
         return mCredentials;\r
-    }\r
-\r
+    }
+
+    public void setFollowRedirects(boolean followRedirects) {
+        mFollowRedirects = followRedirects;
+    }
+
 }