Bug fixed: Upload fails
[pub/Android/ownCloud.git] / src / com / owncloud / android / authentication / AuthenticatorActivity.java
index ed68614..d88d778 100644 (file)
@@ -33,7 +33,6 @@ import android.graphics.Rect;
 import android.graphics.drawable.Drawable;\r
 import android.net.Uri;\r
 import android.net.http.SslError;\r
-import android.os.AsyncTask;\r
 import android.os.Bundle;\r
 import android.os.Handler;\r
 import android.os.IBinder;\r
@@ -65,8 +64,8 @@ import com.actionbarsherlock.app.SherlockDialogFragment;
 import com.owncloud.android.MainApp;\r
 import com.owncloud.android.R;\r
 import com.owncloud.android.authentication.SsoWebViewClient.SsoWebViewClientListener;\r
-import com.owncloud.android.lib.common.OwnCloudAccount;\r
-import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;\r
+import com.owncloud.android.lib.common.OwnCloudCredentials;\r
+import com.owncloud.android.lib.common.OwnCloudCredentialsFactory;\r
 import com.owncloud.android.lib.common.accounts.AccountTypeUtils;\r
 import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;\r
 import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;\r
@@ -76,7 +75,6 @@ import com.owncloud.android.lib.common.operations.RemoteOperation;
 import com.owncloud.android.lib.common.operations.RemoteOperationResult;\r
 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;\r
 import com.owncloud.android.lib.common.utils.Log_OC;\r
-import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;\r
 import com.owncloud.android.lib.resources.status.OwnCloudVersion;\r
 import com.owncloud.android.lib.resources.users.GetRemoteUserNameOperation;\r
 import com.owncloud.android.operations.DetectAuthenticationMethodOperation.AuthenticationMethod;\r
@@ -190,7 +188,12 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
     /// Identifier of operation in progress which result shouldn't be lost \r
     private long mWaitingForOpId = Long.MAX_VALUE;\r
 \r
-    \r
+    private final String BASIC_TOKEN_TYPE = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());\r
+    private final String OAUTH_TOKEN_TYPE = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());\r
+    private final String SAML_TOKEN_TYPE =\r
+            AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType());\r
+\r
+\r
     /**\r
      * {@inheritDoc}\r
      * \r
@@ -235,7 +238,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         setContentView(R.layout.account_setup);\r
         \r
         /// initialize general UI elements\r
-        initOverallUi(savedInstanceState);\r
+        initOverallUi();\r
         \r
         mOkButton = findViewById(R.id.buttonOK);\r
 \r
@@ -273,21 +276,19 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
 \r
     private String chooseAuthTokenType(boolean oauth, boolean saml) {\r
         if (saml) {\r
-            return AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType());\r
+            return SAML_TOKEN_TYPE;\r
         } else if (oauth) {\r
-             return AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());\r
+             return OAUTH_TOKEN_TYPE;\r
         } else {\r
-            return AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());\r
+            return BASIC_TOKEN_TYPE;\r
         }\r
     }\r
 \r
     \r
     /**\r
      * Configures elements in the user interface under direct control of the Activity.\r
-     * \r
-     * @param savedInstanceState        Saved activity state, as in {{@link #onCreate(Bundle)}\r
      */\r
-    private void initOverallUi(Bundle savedInstanceState) {\r
+    private void initOverallUi() {\r
         \r
         /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)\r
         boolean isWelcomeLinkVisible = getResources().getBoolean(R.bool.show_welcome_link);\r
@@ -611,11 +612,18 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         // AsyncTask\r
         boolean inProgress = savedInstanceState.getBoolean(KEY_ASYNC_TASK_IN_PROGRESS);\r
         if (inProgress){\r
-            mAsyncTask = new AuthenticatorAsyncTask(this);\r
             String username = savedInstanceState.getString(KEY_USERNAME);\r
             String password = savedInstanceState.getString(KEY_PASSWORD);\r
-            String[] params = {mServerInfo.mBaseUrl, username, password, mAuthToken, mAuthTokenType};\r
-            mAsyncTask.execute(params);\r
+\r
+            OwnCloudCredentials credentials = null;\r
+            if (BASIC_TOKEN_TYPE.equals(mAuthTokenType)) {\r
+                credentials = OwnCloudCredentialsFactory.newBasicCredentials(username, password);\r
+\r
+            } else if (OAUTH_TOKEN_TYPE.equals(mAuthTokenType)) {\r
+                credentials = OwnCloudCredentialsFactory.newBearerCredentials(mAuthToken);\r
+\r
+            }\r
+            accessRootFolder(credentials);\r
         }\r
     }\r
 \r
@@ -642,7 +650,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
      */\r
     @Override\r
     protected void onResume() {\r
-        //Log_OC.wtf(TAG, "onResume init" );\r
         super.onResume();\r
         \r
         // bound here to avoid spurious changes triggered by Android on device rotations\r
@@ -657,15 +664,12 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
             doOnResumeAndBound();\r
         }\r
         \r
-        //Log_OC.wtf(TAG, "onResume end" );\r
     }\r
 \r
     \r
     @Override\r
     protected void onPause() {\r
-        //Log_OC.wtf(TAG, "onPause init" );\r
         if (mOperationsServiceBinder != null) {\r
-            //Log_OC.wtf(TAG, "unregistering to listen for operation callbacks" );\r
             mOperationsServiceBinder.removeOperationListener(this);\r
         }\r
         \r
@@ -673,7 +677,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         mHostUrlInput.setOnFocusChangeListener(null);\r
         \r
         super.onPause();\r
-        //Log_OC.wtf(TAG, "onPause end" );\r
     }\r
     \r
     @Override\r
@@ -729,14 +732,14 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
     public void onFocusChange(View view, boolean hasFocus) {\r
         if (view.getId() == R.id.hostUrlInput) {   \r
             if (!hasFocus) {\r
-                onUrlInputFocusLost((TextView) view);\r
+                onUrlInputFocusLost();\r
             }\r
             else {\r
                 showRefreshButton(false);\r
             }\r
 \r
         } else if (view.getId() == R.id.account_password) {\r
-            onPasswordFocusChanged((TextView) view, hasFocus);\r
+            onPasswordFocusChanged(hasFocus);\r
         }\r
     }\r
 \r
@@ -749,10 +752,8 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
      * started. \r
      * \r
      * When hasFocus:    user 'comes back' to write again the server URL.\r
-     * \r
-     * @param hostInput     TextView with the URL input field receiving the change of focus.\r
      */\r
-    private void onUrlInputFocusLost(TextView hostInput) {\r
+    private void onUrlInputFocusLost() {\r
         if (!mServerInfo.mBaseUrl.equals(\r
                 normalizeUrl(mHostUrlInput.getText().toString(), mServerInfo.mIsSslConn))) {\r
             // check server again only if the user changed something in the field\r
@@ -806,10 +807,9 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
      * \r
      * When (!hasFocus), the button is made invisible and the password is hidden.\r
      * \r
-     * @param passwordInput    TextView with the password input field receiving the change of focus.\r
      * @param hasFocus          'True' if focus is received, 'false' if is lost\r
      */\r
-    private void onPasswordFocusChanged(TextView passwordInput, boolean hasFocus) {\r
+    private void onPasswordFocusChanged(boolean hasFocus) {\r
         if (hasFocus) {\r
             showViewPasswordButton();\r
         } else {\r
@@ -874,7 +874,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
             mServerStatusText = R.string.auth_wtf_reenter_URL;\r
             showServerStatus();\r
             mOkButton.setEnabled(false);\r
-            //Log_OC.wtf(TAG,  "The user was allowed to click 'connect' to an unchecked server!!");\r
             return;\r
         }\r
 \r
@@ -907,23 +906,17 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);\r
 \r
         /// validate credentials accessing the root folder\r
-        accessRootFolderRemoteOperation(username, password);\r
-        \r
+        OwnCloudCredentials credentials = OwnCloudCredentialsFactory.newBasicCredentials(username, password);\r
+        accessRootFolder(credentials);\r
     }\r
 \r
-    private void accessRootFolderRemoteOperation(String username, String password) {\r
-        // delete the account if the token has changed\r
-        if (mAction == ACTION_UPDATE_TOKEN || mAction == ACTION_UPDATE_EXPIRED_TOKEN) {\r
-            // Remove the cookies in AccountManager\r
-            mAccountMgr.setUserData(mAccount, Constants.KEY_COOKIES, null);\r
-        }\r
-\r
+    private void accessRootFolder(OwnCloudCredentials credentials) {\r
         mAsyncTask = new AuthenticatorAsyncTask(this);\r
-        String[] params = { mServerInfo.mBaseUrl, username, password, mAuthToken, mAuthTokenType};\r
+        Object[] params = { mServerInfo.mBaseUrl, credentials };\r
         mAsyncTask.execute(params);\r
-\r
     }\r
 \r
+\r
     /**\r
      * Starts the OAuth 'grant type' flow to get an access token, with \r
      * a GET AUTHORIZATION request to the BUILT-IN authorization server. \r
@@ -961,17 +954,16 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
      * in the server.\r
      */\r
     private void startSamlBasedFederatedSingleSignOnAuthorization() {\r
-        // be gentle with the user\r
+        /// be gentle with the user\r
         mAuthStatusIcon = R.drawable.progress_small;\r
         mAuthStatusText = R.string.auth_connecting_auth_server;\r
         showAuthStatus();\r
-        IndeterminateProgressDialog dialog = \r
-                IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);\r
-        dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);\r
-\r
-        /// validate credentials accessing the root folder\r
-        accessRootFolderRemoteOperation("", "");\r
 \r
+        /// Show SAML-based SSO web dialog\r
+        String targetUrl = mServerInfo.mBaseUrl\r
+                + AccountUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType);\r
+        SamlWebViewDialog dialog = SamlWebViewDialog.newInstance(targetUrl, targetUrl);\r
+        dialog.show(getSupportFragmentManager(), SAML_DIALOG_TAG);\r
     }\r
 \r
     /**\r
@@ -991,16 +983,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         } else if (operation instanceof OAuth2GetAccessToken) {\r
             onGetOAuthAccessTokenFinish(result);\r
 \r
-        } else if (operation instanceof ExistenceCheckRemoteOperation)  {\r
-            // TODO : remove this response??\r
-            //Log_OC.wtf(TAG, "received detection response through callback" );\r
-            if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).\r
-                    equals(mAuthTokenType)) {\r
-                onSamlBasedFederatedSingleSignOnAuthorizationStart(result);\r
-\r
-            } else {\r
-                onAuthorizationCheckFinish(result);\r
-            }\r
         } else if (operation instanceof GetRemoteUserNameOperation) {\r
             onGetUserNameFinish(result);\r
         }\r
@@ -1048,30 +1030,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
 \r
     }\r
 \r
-    private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result) {\r
-        mWaitingForOpId = Long.MAX_VALUE;\r
-        dismissDialog(WAIT_DIALOG_TAG);\r
-\r
-        if (result.isIdPRedirection()) {\r
-            String targetUrl = mServerInfo.mBaseUrl \r
-                    + AccountUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType);\r
-\r
-            // Show dialog\r
-            SamlWebViewDialog dialog = SamlWebViewDialog.newInstance(targetUrl, targetUrl);            \r
-            dialog.show(getSupportFragmentManager(), SAML_DIALOG_TAG);\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
     /**\r
      * Processes the result of the server check performed when the user finishes the enter of the\r
      * server URL.\r
@@ -1120,16 +1078,12 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
 \r
 \r
     private boolean authSupported(AuthenticationMethod authMethod) {\r
-        String basic = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());\r
-        String oAuth = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());\r
-        String saml =  AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType());\r
-        \r
-        return (( mAuthTokenType.equals(basic) && \r
-                    authMethod.equals(AuthenticationMethod.BASIC_HTTP_AUTH) ) ||\r
-                ( mAuthTokenType.equals(oAuth) && \r
-                    authMethod.equals(AuthenticationMethod.BEARER_TOKEN)) ||\r
-                ( mAuthTokenType.equals(saml)  && \r
-                    authMethod.equals(AuthenticationMethod.SAML_WEB_SSO))\r
+        return (( BASIC_TOKEN_TYPE.equals(mAuthTokenType) &&\r
+                    AuthenticationMethod.BASIC_HTTP_AUTH.equals(authMethod) ) ||\r
+                ( OAUTH_TOKEN_TYPE.equals(mAuthTokenType) &&\r
+                    AuthenticationMethod.BEARER_TOKEN.equals(authMethod)) ||\r
+                ( SAML_TOKEN_TYPE.equals(mAuthTokenType)  &&\r
+                    AuthenticationMethod.SAML_WEB_SSO.equals(authMethod))\r
         );\r
     }\r
 \r
@@ -1370,8 +1324,10 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
             Map<String, String> tokens = (Map<String, String>)(result.getData().get(0));\r
             mAuthToken = tokens.get(OAuth2Constants.KEY_ACCESS_TOKEN);\r
             Log_OC.d(TAG, "Got ACCESS TOKEN: " + mAuthToken);\r
-            \r
-            accessRootFolderRemoteOperation("", "");\r
+\r
+            /// validate token accessing to root folder / getting session\r
+            OwnCloudCredentials credentials = OwnCloudCredentialsFactory.newBearerCredentials(mAuthToken);\r
+            accessRootFolder(credentials);\r
 \r
         } else {\r
             updateAuthStatusIconAndText(result);\r
@@ -1388,7 +1344,8 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
      *\r
      * @param result        Result of the operation.\r
      */\r
-    private void onAuthorizationCheckFinish(RemoteOperationResult result) {\r
+    @Override\r
+    public void onAuthenticatorTaskCallback(RemoteOperationResult result) {\r
         mWaitingForOpId = Long.MAX_VALUE;\r
         dismissDialog(WAIT_DIALOG_TAG);\r
 \r
@@ -1459,10 +1416,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
      */\r
     private void updateAccountAuthentication() throws AccountNotFoundException {\r
         \r
-//        OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(\r
-//                new OwnCloudAccount(mAccount, this)\r
-//        );\r
-\r
         Bundle response = new Bundle();\r
         response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);\r
         response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);\r
@@ -1548,8 +1501,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
             final Intent intent = new Intent();       \r
             intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE,    MainApp.getAccountType());\r
             intent.putExtra(AccountManager.KEY_ACCOUNT_NAME,    mAccount.name);\r
-            /*if (!isOAuth)\r
-                intent.putExtra(AccountManager.KEY_AUTHTOKEN,   MainApp.getAccountType()); */\r
             intent.putExtra(AccountManager.KEY_USERDATA,        username);\r
             if (isOAuth || isSaml) {\r
                 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);\r
@@ -1672,9 +1623,9 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
     public void onCheckClick(View view) {\r
         CheckBox oAuth2Check = (CheckBox)view;\r
         if (oAuth2Check.isChecked()) {\r
-            mAuthTokenType = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());\r
+            mAuthTokenType = OAUTH_TOKEN_TYPE;\r
         } else {\r
-            mAuthTokenType = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());\r
+            mAuthTokenType = BASIC_TOKEN_TYPE;\r
         }\r
         updateAuthenticationPreFragmentVisibility();\r
     }\r
@@ -1748,7 +1699,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         getUserNameIntent.putExtra(OperationsService.EXTRA_COOKIE, sessionCookie);\r
         \r
         if (mOperationsServiceBinder != null) {\r
-            //Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." );\r
             mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getUserNameIntent);\r
         }\r
     }\r
@@ -1881,7 +1831,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
             if (component.equals(\r
                     new ComponentName(AuthenticatorActivity.this, OperationsService.class)\r
                 )) {\r
-                //Log_OC.wtf(TAG, "Operations service connected");\r
                 mOperationsServiceBinder = (OperationsServiceBinder) service;\r
                 \r
                 doOnResumeAndBound();\r
@@ -1939,15 +1888,4 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
     }\r
 \r
 \r
-    @Override\r
-    public void onAuthenticatorTaskCallback(RemoteOperationResult result) {\r
-        //Log_OC.wtf(TAG, "received detection response through callback" );\r
-        if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).\r
-                equals(mAuthTokenType)) {\r
-            onSamlBasedFederatedSingleSignOnAuthorizationStart(result);\r
-\r
-        } else {\r
-            onAuthorizationCheckFinish(result);\r
-        }\r
-    }\r
 }\r