Add actionBar
[pub/Android/ownCloud.git] / src / com / owncloud / android / authentication / AuthenticatorActivity.java
index df4e21b..3ab7690 100644 (file)
@@ -1,6 +1,11 @@
-/* ownCloud Android client application\r
+/**\r
+ *   ownCloud Android client application\r
+ *\r
+ *   @author Bartek Przybylski\r
+ *   @author David A. Velasco\r
+ *   @author masensio\r
  *   Copyright (C) 2012  Bartek Przybylski\r
- *   Copyright (C) 2012-2014 ownCloud Inc.\r
+ *   Copyright (C) 2015 ownCloud Inc.\r
  *\r
  *   This program is free software: you can redistribute it and/or modify\r
  *   it under the terms of the GNU General Public License version 2,\r
@@ -37,6 +42,7 @@ import android.os.Bundle;
 import android.os.Handler;\r
 import android.os.IBinder;\r
 import android.preference.PreferenceManager;\r
+import android.support.v4.app.DialogFragment;\r
 import android.support.v4.app.Fragment;\r
 import android.support.v4.app.FragmentManager;\r
 import android.support.v4.app.FragmentTransaction;\r
@@ -60,11 +66,13 @@ import android.widget.TextView;
 import android.widget.TextView.OnEditorActionListener;\r
 import android.widget.Toast;\r
 \r
-import com.actionbarsherlock.app.SherlockDialogFragment;\r
 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.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
 import com.owncloud.android.lib.common.network.CertificateCombinedException;\r
 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;\r
@@ -72,7 +80,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
@@ -89,14 +96,11 @@ import com.owncloud.android.utils.DisplayUtils;
 \r
 /**\r
  * This Activity is used to add an ownCloud account to the App\r
- * \r
- * @author Bartek Przybylski\r
- * @author David A. Velasco\r
- * @author masensio\r
  */\r
 public class AuthenticatorActivity extends AccountAuthenticatorActivity\r
-implements  OnRemoteOperationListener, OnFocusChangeListener, OnEditorActionListener, \r
-SsoWebViewClientListener, OnSslUntrustedCertListener {\r
+        implements  OnRemoteOperationListener, OnFocusChangeListener, OnEditorActionListener,\r
+        SsoWebViewClientListener, OnSslUntrustedCertListener,\r
+        AuthenticatorAsyncTask.OnAuthenticatorTaskListener {\r
 \r
     private static final String TAG = AuthenticatorActivity.class.getSimpleName();\r
 \r
@@ -132,6 +136,9 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     private static final String CREDENTIALS_DIALOG_TAG = "CREDENTIALS_DIALOG";\r
     private static final String KEY_AUTH_IS_FIRST_ATTEMPT_TAG = "KEY_AUTH_IS_FIRST_ATTEMPT";\r
 \r
+    private static final String KEY_USERNAME = "USERNAME";\r
+    private static final String KEY_PASSWORD = "PASSWORD";\r
+    private static final String KEY_ASYNC_TASK_IN_PROGRESS = "AUTH_IN_PROGRESS";\r
     \r
     /// parameters from EXTRAs in starter Intent\r
     private byte mAction;\r
@@ -175,14 +182,21 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     private int mAuthStatusText = 0, mAuthStatusIcon = 0;\r
     \r
     private String mAuthToken = "";\r
+    private AuthenticatorAsyncTask mAsyncTask;\r
 \r
     private boolean mIsFirstAuthAttempt;\r
-\r
     \r
     /// 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(\r
+            MainApp.getAccountType());\r
+    private final String OAUTH_TOKEN_TYPE = AccountTypeUtils.getAuthTokenTypeAccessToken(\r
+            MainApp.getAccountType());\r
+    private final String SAML_TOKEN_TYPE =\r
+            AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType());\r
+\r
+\r
     /**\r
      * {@inheritDoc}\r
      * \r
@@ -227,7 +241,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         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
@@ -265,21 +279,19 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
 \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
@@ -370,7 +382,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             findViewById(R.id.hostUrlFrame).setVisibility(View.GONE);\r
             mRefreshButton = findViewById(R.id.centeredRefreshButton);\r
         }\r
-        showRefreshButton(mServerIsChecked && !mServerIsValid && \r
+        showRefreshButton(mServerIsChecked && !mServerIsValid &&\r
                 mWaitingForOpId > Integer.MAX_VALUE);\r
         mServerStatusView = (TextView) findViewById(R.id.server_status_text);\r
         showServerStatus();\r
@@ -415,9 +427,9 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
                     if (\r
                             AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(\r
                                     MainApp.getAccountType()\r
-                                    ).equals(mAuthTokenType) &&\r
-                            mHostUrlInput.hasFocus()\r
-                    ) {\r
+                            ).equals(mAuthTokenType) &&\r
+                                    mHostUrlInput.hasFocus()\r
+                            ) {\r
                         checkOcServer();\r
                     }\r
                 }\r
@@ -549,7 +561,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
      * intended to defer the processing of the redirection caught in \r
      * {@link #onNewIntent(Intent)} until {@link #onResume()} \r
      * \r
-     * See {@link #loadSavedInstanceState(Bundle)}\r
+     * See {@link #onSaveInstanceState(Bundle)}\r
      */\r
     @Override\r
     protected void onSaveInstanceState(Bundle outState) {\r
@@ -581,9 +593,42 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         /// authentication\r
         outState.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG, mIsFirstAuthAttempt);\r
 \r
+        /// AsyncTask (User and password)\r
+        outState.putString(KEY_USERNAME, mUsernameInput.getText().toString());\r
+        outState.putString(KEY_PASSWORD, mPasswordInput.getText().toString());\r
+\r
+        if (mAsyncTask != null) {\r
+            mAsyncTask.cancel(true);\r
+            outState.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS, true);\r
+        } else {\r
+            outState.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS, false);\r
+        }\r
+        mAsyncTask = null;\r
+\r
         //Log_OC.wtf(TAG, "onSaveInstanceState end" );\r
     }\r
 \r
+    @Override\r
+    public void onRestoreInstanceState(Bundle savedInstanceState) {\r
+        super.onRestoreInstanceState(savedInstanceState);\r
+\r
+        // AsyncTask\r
+        boolean inProgress = savedInstanceState.getBoolean(KEY_ASYNC_TASK_IN_PROGRESS);\r
+        if (inProgress){\r
+            String username = savedInstanceState.getString(KEY_USERNAME);\r
+            String password = savedInstanceState.getString(KEY_PASSWORD);\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
     /**\r
      * The redirection triggered by the OAuth authentication server as response to the \r
@@ -608,7 +653,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
      */\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
@@ -623,15 +667,12 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             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
@@ -639,7 +680,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         mHostUrlInput.setOnFocusChangeListener(null);\r
         \r
         super.onPause();\r
-        //Log_OC.wtf(TAG, "onPause end" );\r
     }\r
     \r
     @Override\r
@@ -695,14 +735,14 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     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
@@ -715,10 +755,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
      * 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
@@ -737,10 +775,11 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         mOkButton.setEnabled(false);\r
         mServerInfo = new GetServerInfoOperation.ServerInfo();\r
         showRefreshButton(false);\r
-        \r
+\r
         if (uri.length() != 0) {\r
             // Handle internationalized domain names\r
             uri = DisplayUtils.convertIdn(uri, true);\r
+\r
             mServerStatusText = R.string.auth_testing_connection;\r
             mServerStatusIcon = R.drawable.progress_small;\r
             showServerStatus();\r
@@ -772,10 +811,9 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
      * \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
@@ -840,7 +878,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             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
@@ -873,25 +910,18 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         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,\r
+                password);\r
+        accessRootFolder(credentials);\r
     }\r
 \r
-    private void accessRootFolderRemoteOperation(String username, String password) {\r
-        Intent existenceCheckIntent = new Intent();\r
-        existenceCheckIntent.setAction(OperationsService.ACTION_EXISTENCE_CHECK);\r
-        existenceCheckIntent.putExtra(OperationsService.EXTRA_SERVER_URL, mServerInfo.mBaseUrl);\r
-        existenceCheckIntent.putExtra(OperationsService.EXTRA_REMOTE_PATH, "/");\r
-        existenceCheckIntent.putExtra(OperationsService.EXTRA_USERNAME, username);\r
-        existenceCheckIntent.putExtra(OperationsService.EXTRA_PASSWORD, password);\r
-        existenceCheckIntent.putExtra(OperationsService.EXTRA_AUTH_TOKEN, mAuthToken);\r
-        \r
-        if (mOperationsServiceBinder != null) {\r
-            //Log_OC.wtf(TAG, "starting existenceCheckRemoteOperation..." );\r
-            mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(existenceCheckIntent);\r
-        }\r
+    private void accessRootFolder(OwnCloudCredentials credentials) {\r
+        mAsyncTask = new AuthenticatorAsyncTask(this);\r
+        Object[] params = { mServerInfo.mBaseUrl, credentials };\r
+        mAsyncTask.execute(params);\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
@@ -929,17 +959,16 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
      * 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
@@ -959,15 +988,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         } else if (operation instanceof OAuth2GetAccessToken) {\r
             onGetOAuthAccessTokenFinish(result);\r
 \r
-        } else if (operation instanceof ExistenceCheckRemoteOperation)  {\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
@@ -988,20 +1008,21 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
                 if (!mUsernameInput.getText().toString().equals(username)) {\r
                     // fail - not a new account, but an existing one; disallow\r
                     result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME);\r
-                    /*\r
-                    OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(\r
-                            new OwnCloudAccount(\r
-                                    Uri.parse(mServerInfo.mBaseUrl),\r
-                                    OwnCloudCredentialsFactory.newSamlSsoCredentials(mAuthToken))\r
-                            );\r
-                            */\r
                     mAuthToken = "";\r
                     updateAuthStatusIconAndText(result);\r
                     showAuthStatus();\r
                     Log_OC.d(TAG, result.getLogMessage());\r
                 } else {\r
-                    updateToken();\r
-                    success = true;\r
+                    try {\r
+                        updateAccountAuthentication();\r
+                        success = true;\r
+\r
+                    } catch (AccountNotFoundException e) {\r
+                        Log_OC.e(TAG, "Account " + mAccount + " was removed!", e);\r
+                        Toast.makeText(this, R.string.auth_account_does_not_exist,\r
+                                Toast.LENGTH_SHORT).show();\r
+                        finish();\r
+                    }\r
                 }\r
             }\r
 \r
@@ -1015,36 +1036,10 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
 \r
     }\r
 \r
-    private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result) {\r
-        mWaitingForOpId = Long.MAX_VALUE;\r
-        dismissDialog(WAIT_DIALOG_TAG);\r
-
-        if (result.isIdPRedirection()) {
-            String url = result.getRedirectedLocation();\r
-            String targetUrl = mServerInfo.mBaseUrl \r
-                    + AccountUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType);\r
-\r
-            // Show dialog\r
-            SamlWebViewDialog dialog = SamlWebViewDialog.newInstance(url, 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
-     * \r
-     * @param operation     Server check performed.\r
+     *\r
      * @param result        Result of the check.\r
      */\r
     private void onGetServerInfoFinish(RemoteOperationResult result) {\r
@@ -1089,16 +1084,12 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
 \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
@@ -1133,13 +1124,9 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
 \r
     // TODO remove, if possible\r
     private String trimUrlWebdav(String url){       \r
-        if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0)){\r
-            url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0.length());             \r
-        } else if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_2_0)){\r
-            url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_2_0.length());             \r
-        } else if (url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_1_2)){\r
-            url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_1_2.length());             \r
-        } \r
+        if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0_AND_LATER)){\r
+            url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0_AND_LATER.length());\r
+        }\r
         return (url != null ? url : "");\r
     }\r
 \r
@@ -1339,8 +1326,11 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             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(\r
+                    mAuthToken);\r
+            accessRootFolder(credentials);\r
 \r
         } else {\r
             updateAuthStatusIconAndText(result);\r
@@ -1354,11 +1344,11 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
      * Processes the result of the access check performed to try the user credentials.\r
      * \r
      * Creates a new account through the AccountManager.\r
-     * \r
-     * @param operation     Access check performed.\r
+     *\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
@@ -1370,15 +1360,23 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
                 success = createAccount();\r
 \r
             } else {\r
-                updateToken();\r
-                success = true;\r
+                try {\r
+                    updateAccountAuthentication();\r
+                    success = true;\r
+\r
+                } catch (AccountNotFoundException e) {\r
+                    Log_OC.e(TAG, "Account " + mAccount + " was removed!", e);\r
+                    Toast.makeText(this, R.string.auth_account_does_not_exist,\r
+                            Toast.LENGTH_SHORT).show();\r
+                    finish();\r
+                }\r
             }\r
 \r
             if (success) {\r
                 finish();\r
             }\r
             \r
-        } else if (result.isServerFail() || result.isException()) {
+        } else if (result.isServerFail() || result.isException()) {\r
             /// server errors or exceptions in authorization take to requiring a new check of \r
             /// the server\r
             mServerIsChecked = true;\r
@@ -1412,10 +1410,16 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
 \r
 \r
     /**\r
-     * Sets the proper response to get that the Account Authenticator that started this activity \r
+     * Updates the authentication token.\r
+     *\r
+     * Sets the proper response so that the AccountAuthenticator that started this activity\r
      * saves a new authorization token for mAccount.\r
+     *\r
+     * Kills the session kept by OwnCloudClientManager so that a new one will created with\r
+     * the new credentials when needed.\r
      */\r
-    private void updateToken() {\r
+    private void updateAccountAuthentication() throws AccountNotFoundException {\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
@@ -1486,6 +1490,13 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
                 );\r
             }\r
 \r
+            // include account version with the new account\r
+            mAccountMgr.setUserData(\r
+                mAccount,\r
+                Constants.KEY_OC_ACCOUNT_VERSION,\r
+                Integer.toString(AccountUtils.ACCOUNT_VERSION)\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
@@ -1501,21 +1512,19 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             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
             }\r
             /// add user data to the new account; TODO probably can be done in the last parameter \r
-            //      addAccountExplicitly, or in KEY_USERDATA
+            //      addAccountExplicitly, or in KEY_USERDATA\r
             mAccountMgr.setUserData(\r
                     mAccount, Constants.KEY_OC_VERSION,    mServerInfo.mVersion.getVersion()\r
             );\r
             mAccountMgr.setUserData(\r
                     mAccount, Constants.KEY_OC_BASE_URL,   mServerInfo.mBaseUrl\r
             );\r
-
+\r
             if (isSaml) {\r
                 mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE"); \r
             } else if (isOAuth) {\r
@@ -1547,9 +1556,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     /**\r
      * Updates the content and visibility state of the icon and text associated\r
      * to the last check on the ownCloud server.\r
-     * \r
-     * @param serverStatusText      Resource identifier of the text to show.\r
-     * @param serverStatusIcon      Resource identifier of the icon to show.\r
+     *\r
      */\r
     private void showServerStatus() {\r
         if (mServerStatusIcon == 0 && mServerStatusText == 0) {\r
@@ -1627,9 +1634,9 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     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
@@ -1703,7 +1710,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         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
@@ -1716,8 +1722,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             mAuthToken = sessionCookie;\r
             getRemoteUserNameOperation(sessionCookie, true);\r
             Fragment fd = getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG);\r
-            if (fd != null && fd instanceof SherlockDialogFragment) {\r
-                Dialog d = ((SherlockDialogFragment)fd).getDialog();\r
+            if (fd != null && fd instanceof DialogFragment) {\r
+                Dialog d = ((DialogFragment)fd).getDialog();\r
                 if (d != null && d.isShowing()) {\r
                     d.dismiss();\r
                 }\r
@@ -1819,8 +1825,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     \r
     private void dismissDialog(String dialogTag){\r
         Fragment frag = getSupportFragmentManager().findFragmentByTag(dialogTag);\r
-        if (frag != null && frag instanceof SherlockDialogFragment) {\r
-            SherlockDialogFragment dialog = (SherlockDialogFragment) frag;\r
+        if (frag != null && frag instanceof DialogFragment) {\r
+            DialogFragment dialog = (DialogFragment) frag;\r
             dialog.dismiss();\r
         }\r
     }\r
@@ -1836,7 +1842,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             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
@@ -1892,4 +1897,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     public void doNegativeAuthenticatioDialogClick(){\r
         mIsFirstAuthAttempt = true;\r
     }\r
+\r
+\r
 }\r