OC-3260: Detect authentication method
[pub/Android/ownCloud.git] / src / com / owncloud / android / authentication / AuthenticatorActivity.java
index e604a95..73bbaec 100644 (file)
@@ -18,6 +18,8 @@
 \r
 package com.owncloud.android.authentication;\r
 \r
+import java.security.cert.X509Certificate;\r
+\r
 import android.accounts.Account;\r
 import android.accounts.AccountManager;\r
 import android.app.AlertDialog;\r
@@ -29,10 +31,13 @@ import android.content.SharedPreferences;
 import android.graphics.Rect;\r
 import android.graphics.drawable.Drawable;\r
 import android.net.Uri;\r
+import android.net.http.SslError;\r
 import android.os.Bundle;\r
 import android.os.Handler;\r
 import android.preference.PreferenceManager;\r
 import android.support.v4.app.Fragment;\r
+import android.support.v4.app.FragmentManager;\r
+import android.support.v4.app.FragmentTransaction;\r
 import android.text.Editable;\r
 import android.text.InputType;\r
 import android.text.TextWatcher;\r
@@ -43,6 +48,7 @@ import android.view.View.OnFocusChangeListener;
 import android.view.View.OnTouchListener;\r
 import android.view.Window;\r
 import android.view.inputmethod.EditorInfo;\r
+import android.webkit.SslErrorHandler;\r
 import android.widget.Button;\r
 import android.widget.CheckBox;\r
 import android.widget.EditText;\r
@@ -59,6 +65,7 @@ import com.owncloud.android.lib.common.OwnCloudClientFactory;
 import com.owncloud.android.lib.common.OwnCloudClient;\r
 import com.owncloud.android.operations.OAuth2GetAccessToken;\r
 
+import com.owncloud.android.lib.common.network.CertificateCombinedException;\r
 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;\r
 import com.owncloud.android.lib.resources.status.GetRemoteStatusOperation;\r
 import com.owncloud.android.lib.common.operations.RemoteOperation;\r
@@ -68,8 +75,8 @@ import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
 import com.owncloud.android.lib.resources.users.GetRemoteUserNameOperation;\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.ui.dialog.SslUntrustedCertDialog;\r
+import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;\r
 import com.owncloud.android.utils.Log_OC;\r
 import com.owncloud.android.lib.resources.status.OwnCloudVersion;\r
 \r
@@ -80,7 +87,8 @@ import com.owncloud.android.lib.resources.status.OwnCloudVersion;
  * @author David A. Velasco\r
  */\r
 public class AuthenticatorActivity extends AccountAuthenticatorActivity\r
-implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeListener, OnEditorActionListener, SsoWebViewClientListener{\r
+    implements  OnRemoteOperationListener, OnFocusChangeListener, OnEditorActionListener, \r
+    SsoWebViewClientListener, OnSslUntrustedCertListener {\r
 \r
     private static final String TAG = AuthenticatorActivity.class.getSimpleName();\r
 \r
@@ -113,9 +121,8 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     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
-    private static final int DIALOG_OAUTH2_LOGIN_PROGRESS = 3;\r
+    private static final int DIALOG_CERT_NOT_SAVED = 1;\r
+    private static final int DIALOG_OAUTH2_LOGIN_PROGRESS = 2;\r
 \r
     public static final byte ACTION_CREATE = 0;\r
     public static final byte ACTION_UPDATE_TOKEN = 1;\r
@@ -135,7 +142,6 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     private Thread mOperationThread;\r
     private GetRemoteStatusOperation mOcServerChkOperation;\r
     private ExistenceCheckRemoteOperation mAuthCheckOperation;\r
-    private RemoteOperationResult mLastSslUntrustedServerResult;\r
 \r
     private Uri mNewCapturedUriFromOAuth2Redirection;\r
 \r
@@ -168,6 +174,10 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     \r
     private boolean mResumed; // Control if activity is resumed\r
 \r
+    public static String DIALOG_UNTRUSTED_CERT = "DIALOG_UNTRUSTED_CERT";\r
+    \r
+    private boolean mTryEmptyAuthorization = false;\r
+\r
 \r
     /**\r
      * {@inheritDoc}\r
@@ -885,6 +895,8 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             /// update status icon and text\r
             if (mServerIsValid) {\r
                 hideRefreshButton();\r
+                // Try to create an account with user and pass "", to know if it is a regular server\r
+                tryEmptyAuthorization();\r
             } else {\r
                 showRefreshButton();\r
             }\r
@@ -893,22 +905,47 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
 \r
             /// very special case (TODO: move to a common place for all the remote operations)\r
             if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {\r
-                mLastSslUntrustedServerResult = result;\r
-                showDialog(DIALOG_SSL_VALIDATOR); \r
+                showUntrustedCertDialog(result);\r
             }\r
 \r
             /// retrieve discovered version and normalize server URL\r
             mDiscoveredVersion = operation.getDiscoveredVersion();\r
             mHostBaseUrl = normalizeUrl(mHostUrlInput.getText().toString());\r
 \r
-            /// allow or not the user try to access the server\r
-            mOkButton.setEnabled(mServerIsValid);\r
+//            /// allow or not the user try to access the server\r
+//            mOkButton.setEnabled(mServerIsValid);\r
             \r
         }   // else nothing ; only the last check operation is considered; \r
         // multiple can be triggered if the user amends a URL before a previous check can be triggered\r
     }\r
 \r
 \r
+    /**\r
+     *  Try to access with  user/pass ""/"", to know if it is a regular server\r
+     */\r
+    private void tryEmptyAuthorization() {\r
+        mTryEmptyAuthorization = true;\r
+        \r
+        Log_OC.d(TAG, "Trying empty authorization to detect authentication method");\r
+        \r
+        /// be gentle with the user\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
+        /// get basic credentials entered by user\r
+        String username = "";\r
+        String password = "";\r
+\r
+        /// test credentials \r
+        mAuthCheckOperation = new  ExistenceCheckRemoteOperation("", this, false);\r
+        OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this, true);\r
+        client.setBasicCredentials(username, password);\r
+        mOperationThread = mAuthCheckOperation.execute(client, this, mHandler);\r
+    }\r
+    \r
+    \r
     private String normalizeUrl(String url) {\r
         if (url != null && url.length() > 0) {\r
             url = url.trim();\r
@@ -1159,21 +1196,29 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         } 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
+        \r
         if (result.isSuccess()) {\r
-            Log_OC.d(TAG, "Successful access - time to save the account");\r
+            \r
+            if (mTryEmptyAuthorization) {\r
+                //allow or not the user try to access the server\r
+                mOkButton.setEnabled(mServerIsValid);\r
+                mTryEmptyAuthorization = false;\r
+                \r
+            } else {\r
+                Log_OC.d(TAG, "Successful access - time to save the account");\r
 \r
-            boolean success = false;\r
-            if (mAction == ACTION_CREATE) {\r
-                success = createAccount();\r
+                boolean success = false;\r
+                if (mAction == ACTION_CREATE) {\r
+                    success = createAccount();\r
 \r
-            } else {\r
-                updateToken();\r
-                success = true;\r
-            }\r
+                } else {\r
+                    updateToken();\r
+                    success = true;\r
+                }\r
 \r
-            if (success) {\r
-                finish();\r
+                if (success) {\r
+                    finish();\r
+                }\r
             }\r
 \r
         } else if (result.isServerFail() || result.isException()) {\r
@@ -1198,8 +1243,7 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
 \r
             // very special case (TODO: move to a common place for all the remote operations) (dangerous here?)\r
             if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {\r
-                mLastSslUntrustedServerResult = result;\r
-                showDialog(DIALOG_SSL_VALIDATOR); \r
+                showUntrustedCertDialog(result);\r
             }\r
 \r
         } else {    // authorization fail due to client side - probably wrong credentials\r
@@ -1331,10 +1375,6 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         case DIALOG_CERT_NOT_SAVED:\r
         case DIALOG_OAUTH2_LOGIN_PROGRESS:\r
             break;\r
-        case DIALOG_SSL_VALIDATOR: {\r
-            ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult);\r
-            break;\r
-        }\r
         default:\r
             Log_OC.e(TAG, "Incorrect dialog called with id = " + id);\r
         }\r
@@ -1385,11 +1425,6 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
             dialog = working_dialog;\r
             break;\r
         }\r
-        case DIALOG_SSL_VALIDATOR: {\r
-            /// TODO start to use new dialog interface, at least for this (it is a FragmentDialog already)\r
-            dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this);\r
-            break;\r
-        }\r
         case DIALOG_CERT_NOT_SAVED: {\r
             AlertDialog.Builder builder = new AlertDialog.Builder(this);\r
             builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));\r
@@ -1540,23 +1575,6 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
     }\r
     \r
     /**\r
-     * Called from SslValidatorDialog when a new server certificate was correctly saved.\r
-     */\r
-    public void onSavedCertificate() {\r
-        checkOcServer();\r
-    }\r
-\r
-    /**\r
-     * Called from SslValidatorDialog when a new server certificate could not be saved \r
-     * when the user requested it.\r
-     */\r
-    @Override\r
-    public void onFailedSavingCertificate() {\r
-        showDialog(DIALOG_CERT_NOT_SAVED);\r
-    }\r
-\r
-\r
-    /**\r
      *  Called when the 'action' button in an IME is pressed ('enter' in software keyboard).\r
      * \r
      *  Used to trigger the authentication check when the user presses 'enter' after writing the password, \r
@@ -1670,5 +1688,86 @@ implements  OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList
         }\r
         return super.onTouchEvent(event);\r
     }\r
+\r
+\r
+    /**\r
+     * Show untrusted cert dialog \r
+     */\r
+    public void showUntrustedCertDialog(X509Certificate x509Certificate, SslError error, SslErrorHandler handler) {\r
+        // Show a dialog with the certificate info\r
+        SslUntrustedCertDialog dialog = null;\r
+        if (x509Certificate == null) {\r
+            dialog = SslUntrustedCertDialog.newInstanceForEmptySslError(error, handler);\r
+        } else {\r
+            dialog = SslUntrustedCertDialog.newInstanceForFullSslError(x509Certificate, error, handler);\r
+        }\r
+        FragmentManager fm = getSupportFragmentManager();\r
+        FragmentTransaction ft = fm.beginTransaction();\r
+        ft.addToBackStack(null);\r
+        dialog.show(ft, DIALOG_UNTRUSTED_CERT);\r
+    }\r
+    \r
+    /**\r
+     * Show untrusted cert dialog \r
+     */\r
+    public void showUntrustedCertDialog(RemoteOperationResult result) {\r
+        // Show a dialog with the certificate info\r
+        SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError((CertificateCombinedException)result.getException());\r
+        FragmentManager fm = getSupportFragmentManager();\r
+        FragmentTransaction ft = fm.beginTransaction();\r
+        ft.addToBackStack(null);\r
+        dialog.show(ft, DIALOG_UNTRUSTED_CERT);\r
+        \r
+    }\r
+    \r
+    /**\r
+     * Dismiss untrusted cert dialog\r
+     */\r
+    public void dismissUntrustedCertDialog(){\r
+        /*Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_UNTRUSTED_CERT);\r
+        if (frag != null) {\r
+            SslErrorViewAdapter dialog = (SslErrorViewAdapter) frag;\r
+            dialog.dismiss();\r
+        }\r
+        */\r
+    }\r
+    \r
+    /**\r
+     * Called from SslValidatorDialog when a new server certificate was correctly saved.\r
+     */\r
+    public void onSavedCertificate() {\r
+        Fragment fd = getSupportFragmentManager().findFragmentByTag(TAG_SAML_DIALOG);\r
+        if (fd == null) {\r
+            // if SAML dialog is not shown, the SslDialog was shown due to an SSL error in the server check\r
+            checkOcServer();\r
+        }\r
+    }\r
+\r
+    /**\r
+     * Called from SslValidatorDialog when a new server certificate could not be saved \r
+     * when the user requested it.\r
+     */\r
+    @Override\r
+    public void onFailedSavingCertificate() {\r
+        showDialog(DIALOG_CERT_NOT_SAVED);\r
+        cancelWebView();\r
+    }\r
+\r
+    @Override\r
+    public void onCancelCertificate() {\r
+        cancelWebView();\r
+    }\r
     \r
+\r
+    public void cancelWebView() {\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
+    }\r
+\r
 }\r