X-Git-Url: http://git.linex4red.de/pub/Android/ownCloud.git/blobdiff_plain/d19128e770443fac3e134e46dbb88a3b29070fd3..08be3d3433b65d0858dc1503a82ed5a3ba655d36:/src/com/owncloud/android/authentication/AuthenticatorActivity.java diff --git a/src/com/owncloud/android/authentication/AuthenticatorActivity.java b/src/com/owncloud/android/authentication/AuthenticatorActivity.java index df4e21b1..7b0398e8 100644 --- a/src/com/owncloud/android/authentication/AuthenticatorActivity.java +++ b/src/com/owncloud/android/authentication/AuthenticatorActivity.java @@ -1,6 +1,11 @@ -/* ownCloud Android client application +/** + * ownCloud Android client application + * + * @author Bartek Przybylski + * @author David A. Velasco + * @author masensio * Copyright (C) 2012 Bartek Przybylski - * Copyright (C) 2012-2014 ownCloud Inc. + * Copyright (C) 2015 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, @@ -18,9 +23,6 @@ package com.owncloud.android.authentication; -import java.security.cert.X509Certificate; -import java.util.Map; - import android.accounts.Account; import android.accounts.AccountManager; import android.app.Dialog; @@ -37,6 +39,7 @@ import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.preference.PreferenceManager; +import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; @@ -48,7 +51,6 @@ import android.view.MotionEvent; import android.view.View; import android.view.View.OnFocusChangeListener; import android.view.View.OnTouchListener; -import android.view.Window; import android.view.inputmethod.EditorInfo; import android.webkit.HttpAuthHandler; import android.webkit.SslErrorHandler; @@ -60,11 +62,13 @@ import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import android.widget.Toast; -import com.actionbarsherlock.app.SherlockDialogFragment; import com.owncloud.android.MainApp; import com.owncloud.android.R; import com.owncloud.android.authentication.SsoWebViewClient.SsoWebViewClientListener; +import com.owncloud.android.lib.common.OwnCloudCredentials; +import com.owncloud.android.lib.common.OwnCloudCredentialsFactory; import com.owncloud.android.lib.common.accounts.AccountTypeUtils; +import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException; import com.owncloud.android.lib.common.accounts.AccountUtils.Constants; import com.owncloud.android.lib.common.network.CertificateCombinedException; import com.owncloud.android.lib.common.operations.OnRemoteOperationListener; @@ -72,7 +76,6 @@ import com.owncloud.android.lib.common.operations.RemoteOperation; import com.owncloud.android.lib.common.operations.RemoteOperationResult; import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode; import com.owncloud.android.lib.common.utils.Log_OC; -import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation; import com.owncloud.android.lib.resources.status.OwnCloudVersion; import com.owncloud.android.lib.resources.users.GetRemoteUserNameOperation; import com.owncloud.android.operations.DetectAuthenticationMethodOperation.AuthenticationMethod; @@ -87,16 +90,16 @@ import com.owncloud.android.ui.dialog.SslUntrustedCertDialog; import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener; import com.owncloud.android.utils.DisplayUtils; +import java.security.cert.X509Certificate; +import java.util.Map; + /** * This Activity is used to add an ownCloud account to the App - * - * @author Bartek Przybylski - * @author David A. Velasco - * @author masensio */ public class AuthenticatorActivity extends AccountAuthenticatorActivity -implements OnRemoteOperationListener, OnFocusChangeListener, OnEditorActionListener, -SsoWebViewClientListener, OnSslUntrustedCertListener { + implements OnRemoteOperationListener, OnFocusChangeListener, OnEditorActionListener, + SsoWebViewClientListener, OnSslUntrustedCertListener, + AuthenticatorAsyncTask.OnAuthenticatorTaskListener { private static final String TAG = AuthenticatorActivity.class.getSimpleName(); @@ -132,6 +135,9 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { private static final String CREDENTIALS_DIALOG_TAG = "CREDENTIALS_DIALOG"; private static final String KEY_AUTH_IS_FIRST_ATTEMPT_TAG = "KEY_AUTH_IS_FIRST_ATTEMPT"; + private static final String KEY_USERNAME = "USERNAME"; + private static final String KEY_PASSWORD = "PASSWORD"; + private static final String KEY_ASYNC_TASK_IN_PROGRESS = "AUTH_IN_PROGRESS"; /// parameters from EXTRAs in starter Intent private byte mAction; @@ -170,19 +176,27 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { private EditText mUsernameInput; private EditText mPasswordInput; private View mOkButton; + private View mCenteredRefreshButton; private TextView mAuthStatusView; private int mAuthStatusText = 0, mAuthStatusIcon = 0; private String mAuthToken = ""; + private AuthenticatorAsyncTask mAsyncTask; private boolean mIsFirstAuthAttempt; - /// Identifier of operation in progress which result shouldn't be lost private long mWaitingForOpId = Long.MAX_VALUE; - + private final String BASIC_TOKEN_TYPE = AccountTypeUtils.getAuthTokenTypePass( + MainApp.getAccountType()); + private final String OAUTH_TOKEN_TYPE = AccountTypeUtils.getAuthTokenTypeAccessToken( + MainApp.getAccountType()); + private final String SAML_TOKEN_TYPE = + AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()); + + /** * {@inheritDoc} * @@ -192,7 +206,16 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { protected void onCreate(Bundle savedInstanceState) { //Log_OC.wtf(TAG, "onCreate init"); super.onCreate(savedInstanceState); - getWindow().requestFeature(Window.FEATURE_NO_TITLE); + + // Workaround, for fixing a problem with Android Library Suppor v7 19 + //getWindow().requestFeature(Window.FEATURE_NO_TITLE); + if (getSupportActionBar() != null) { + getSupportActionBar().hide(); + + getSupportActionBar().setDisplayHomeAsUpEnabled(false); + getSupportActionBar().setDisplayShowHomeEnabled(false); + getSupportActionBar().setDisplayShowTitleEnabled(false); + } mIsFirstAuthAttempt = true; @@ -227,7 +250,25 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { setContentView(R.layout.account_setup); /// initialize general UI elements - initOverallUi(savedInstanceState); + initOverallUi(); + + mOkButton = findViewById(R.id.buttonOK); + mOkButton.setOnClickListener(new View.OnClickListener() { + + @Override + public void onClick(View v) { + onOkClick(); + } + }); + + mCenteredRefreshButton = findViewById(R.id.centeredRefreshButton); + mCenteredRefreshButton.setOnClickListener(new View.OnClickListener() { + + @Override + public void onClick(View v) { + checkOcServer(); + } + }); mOkButton = findViewById(R.id.buttonOK); @@ -265,21 +306,19 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { private String chooseAuthTokenType(boolean oauth, boolean saml) { if (saml) { - return AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()); + return SAML_TOKEN_TYPE; } else if (oauth) { - return AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()); + return OAUTH_TOKEN_TYPE; } else { - return AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType()); + return BASIC_TOKEN_TYPE; } } /** * Configures elements in the user interface under direct control of the Activity. - * - * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)} */ - private void initOverallUi(Bundle savedInstanceState) { + private void initOverallUi() { /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState) boolean isWelcomeLinkVisible = getResources().getBoolean(R.bool.show_welcome_link); @@ -327,11 +366,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { if (mAccount != null) { mServerInfo.mBaseUrl = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_BASE_URL); // TODO do next in a setter for mBaseUrl - mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith("https://"); - String ocVersion = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_VERSION); - if (ocVersion != null) { - mServerInfo.mVersion = new OwnCloudVersion(ocVersion); - } + mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith("https://"); + mServerInfo.mVersion = AccountUtils.getServerVersion(mAccount); } else { mServerInfo.mBaseUrl = getString(R.string.server_url).trim(); mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith("https://"); @@ -370,7 +406,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { findViewById(R.id.hostUrlFrame).setVisibility(View.GONE); mRefreshButton = findViewById(R.id.centeredRefreshButton); } - showRefreshButton(mServerIsChecked && !mServerIsValid && + showRefreshButton(mServerIsChecked && !mServerIsValid && mWaitingForOpId > Integer.MAX_VALUE); mServerStatusView = (TextView) findViewById(R.id.server_status_text); showServerStatus(); @@ -415,9 +451,9 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { if ( AccountTypeUtils.getAuthTokenTypeSamlSessionCookie( MainApp.getAccountType() - ).equals(mAuthTokenType) && - mHostUrlInput.hasFocus() - ) { + ).equals(mAuthTokenType) && + mHostUrlInput.hasFocus() + ) { checkOcServer(); } } @@ -549,7 +585,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { * intended to defer the processing of the redirection caught in * {@link #onNewIntent(Intent)} until {@link #onResume()} * - * See {@link #loadSavedInstanceState(Bundle)} + * See {@link super#onSaveInstanceState(Bundle)} */ @Override protected void onSaveInstanceState(Bundle outState) { @@ -581,9 +617,42 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { /// authentication outState.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG, mIsFirstAuthAttempt); + /// AsyncTask (User and password) + outState.putString(KEY_USERNAME, mUsernameInput.getText().toString()); + outState.putString(KEY_PASSWORD, mPasswordInput.getText().toString()); + + if (mAsyncTask != null) { + mAsyncTask.cancel(true); + outState.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS, true); + } else { + outState.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS, false); + } + mAsyncTask = null; + //Log_OC.wtf(TAG, "onSaveInstanceState end" ); } + @Override + public void onRestoreInstanceState(Bundle savedInstanceState) { + super.onRestoreInstanceState(savedInstanceState); + + // AsyncTask + boolean inProgress = savedInstanceState.getBoolean(KEY_ASYNC_TASK_IN_PROGRESS); + if (inProgress){ + String username = savedInstanceState.getString(KEY_USERNAME); + String password = savedInstanceState.getString(KEY_PASSWORD); + + OwnCloudCredentials credentials = null; + if (BASIC_TOKEN_TYPE.equals(mAuthTokenType)) { + credentials = OwnCloudCredentialsFactory.newBasicCredentials(username, password); + + } else if (OAUTH_TOKEN_TYPE.equals(mAuthTokenType)) { + credentials = OwnCloudCredentialsFactory.newBearerCredentials(mAuthToken); + + } + accessRootFolder(credentials); + } + } /** * The redirection triggered by the OAuth authentication server as response to the @@ -608,7 +677,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { */ @Override protected void onResume() { - //Log_OC.wtf(TAG, "onResume init" ); super.onResume(); // bound here to avoid spurious changes triggered by Android on device rotations @@ -623,15 +691,12 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { doOnResumeAndBound(); } - //Log_OC.wtf(TAG, "onResume end" ); } @Override protected void onPause() { - //Log_OC.wtf(TAG, "onPause init" ); if (mOperationsServiceBinder != null) { - //Log_OC.wtf(TAG, "unregistering to listen for operation callbacks" ); mOperationsServiceBinder.removeOperationListener(this); } @@ -639,7 +704,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { mHostUrlInput.setOnFocusChangeListener(null); super.onPause(); - //Log_OC.wtf(TAG, "onPause end" ); } @Override @@ -678,7 +742,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { mOAuthTokenEndpointText.getText().toString().trim()); getServerInfoIntent.putExtra( - OperationsService.EXTRA_OAUTH2_QUERY_PARAMETERS, + OperationsService.EXTRA_OAUTH2_QUERY_PARAMETERS, queryParameters); if (mOperationsServiceBinder != null) { @@ -695,14 +759,14 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { public void onFocusChange(View view, boolean hasFocus) { if (view.getId() == R.id.hostUrlInput) { if (!hasFocus) { - onUrlInputFocusLost((TextView) view); + onUrlInputFocusLost(); } else { showRefreshButton(false); } } else if (view.getId() == R.id.account_password) { - onPasswordFocusChanged((TextView) view, hasFocus); + onPasswordFocusChanged(hasFocus); } } @@ -715,10 +779,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { * started. * * When hasFocus: user 'comes back' to write again the server URL. - * - * @param hostInput TextView with the URL input field receiving the change of focus. */ - private void onUrlInputFocusLost(TextView hostInput) { + private void onUrlInputFocusLost() { if (!mServerInfo.mBaseUrl.equals( normalizeUrl(mHostUrlInput.getText().toString(), mServerInfo.mIsSslConn))) { // check server again only if the user changed something in the field @@ -737,10 +799,13 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { mOkButton.setEnabled(false); mServerInfo = new GetServerInfoOperation.ServerInfo(); showRefreshButton(false); - + if (uri.length() != 0) { + uri = stripIndexPhpOrAppsFiles(uri, mHostUrlInput); + // Handle internationalized domain names uri = DisplayUtils.convertIdn(uri, true); + mServerStatusText = R.string.auth_testing_connection; mServerStatusIcon = R.drawable.progress_small; showServerStatus(); @@ -748,7 +813,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { Intent getServerInfoIntent = new Intent(); getServerInfoIntent.setAction(OperationsService.ACTION_GET_SERVER_INFO); getServerInfoIntent.putExtra( - OperationsService.EXTRA_SERVER_URL, + OperationsService.EXTRA_SERVER_URL, normalizeUrlSuffix(uri) ); if (mOperationsServiceBinder != null) { @@ -772,10 +837,9 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { * * When (!hasFocus), the button is made invisible and the password is hidden. * - * @param passwordInput TextView with the password input field receiving the change of focus. * @param hasFocus 'True' if focus is received, 'false' if is lost */ - private void onPasswordFocusChanged(TextView passwordInput, boolean hasFocus) { + private void onPasswordFocusChanged(boolean hasFocus) { if (hasFocus) { showViewPasswordButton(); } else { @@ -827,10 +891,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { * is postponed until it is available. * * IMPORTANT ENTRY POINT 4 - * - * @param view OK button */ - public void onOkClick(View view) { + public void onOkClick() { // this check should be unnecessary if (mServerInfo.mVersion == null || !mServerInfo.mVersion.isVersionValid() || @@ -840,7 +902,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { mServerStatusText = R.string.auth_wtf_reenter_URL; showServerStatus(); mOkButton.setEnabled(false); - //Log_OC.wtf(TAG, "The user was allowed to click 'connect' to an unchecked server!!"); return; } @@ -873,25 +934,18 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG); /// validate credentials accessing the root folder - accessRootFolderRemoteOperation(username, password); - + OwnCloudCredentials credentials = OwnCloudCredentialsFactory.newBasicCredentials(username, + password); + accessRootFolder(credentials); } - private void accessRootFolderRemoteOperation(String username, String password) { - Intent existenceCheckIntent = new Intent(); - existenceCheckIntent.setAction(OperationsService.ACTION_EXISTENCE_CHECK); - existenceCheckIntent.putExtra(OperationsService.EXTRA_SERVER_URL, mServerInfo.mBaseUrl); - existenceCheckIntent.putExtra(OperationsService.EXTRA_REMOTE_PATH, "/"); - existenceCheckIntent.putExtra(OperationsService.EXTRA_USERNAME, username); - existenceCheckIntent.putExtra(OperationsService.EXTRA_PASSWORD, password); - existenceCheckIntent.putExtra(OperationsService.EXTRA_AUTH_TOKEN, mAuthToken); - - if (mOperationsServiceBinder != null) { - //Log_OC.wtf(TAG, "starting existenceCheckRemoteOperation..." ); - mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(existenceCheckIntent); - } + private void accessRootFolder(OwnCloudCredentials credentials) { + mAsyncTask = new AuthenticatorAsyncTask(this); + Object[] params = { mServerInfo.mBaseUrl, credentials }; + mAsyncTask.execute(params); } + /** * Starts the OAuth 'grant type' flow to get an access token, with * a GET AUTHORIZATION request to the BUILT-IN authorization server. @@ -929,17 +983,16 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { * in the server. */ private void startSamlBasedFederatedSingleSignOnAuthorization() { - // be gentle with the user + /// be gentle with the user mAuthStatusIcon = R.drawable.progress_small; mAuthStatusText = R.string.auth_connecting_auth_server; showAuthStatus(); - IndeterminateProgressDialog dialog = - IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true); - dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG); - - /// validate credentials accessing the root folder - accessRootFolderRemoteOperation("", ""); + /// Show SAML-based SSO web dialog + String targetUrl = mServerInfo.mBaseUrl + + AccountUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType); + SamlWebViewDialog dialog = SamlWebViewDialog.newInstance(targetUrl, targetUrl); + dialog.show(getSupportFragmentManager(), SAML_DIALOG_TAG); } /** @@ -959,15 +1012,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { } else if (operation instanceof OAuth2GetAccessToken) { onGetOAuthAccessTokenFinish(result); - } else if (operation instanceof ExistenceCheckRemoteOperation) { - //Log_OC.wtf(TAG, "received detection response through callback" ); - if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()). - equals(mAuthTokenType)) { - onSamlBasedFederatedSingleSignOnAuthorizationStart(result); - - } else { - onAuthorizationCheckFinish(result); - } } else if (operation instanceof GetRemoteUserNameOperation) { onGetUserNameFinish(result); } @@ -982,26 +1026,27 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { if ( mAction == ACTION_CREATE) { mUsernameInput.setText(username); - success = createAccount(); + success = createAccount(result); } else { if (!mUsernameInput.getText().toString().equals(username)) { // fail - not a new account, but an existing one; disallow result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME); - /* - OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor( - new OwnCloudAccount( - Uri.parse(mServerInfo.mBaseUrl), - OwnCloudCredentialsFactory.newSamlSsoCredentials(mAuthToken)) - ); - */ mAuthToken = ""; updateAuthStatusIconAndText(result); showAuthStatus(); Log_OC.d(TAG, result.getLogMessage()); } else { - updateToken(); - success = true; + try { + updateAccountAuthentication(); + success = true; + + } catch (AccountNotFoundException e) { + Log_OC.e(TAG, "Account " + mAccount + " was removed!", e); + Toast.makeText(this, R.string.auth_account_does_not_exist, + Toast.LENGTH_SHORT).show(); + finish(); + } } } @@ -1015,36 +1060,10 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { } - private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result) { - mWaitingForOpId = Long.MAX_VALUE; - dismissDialog(WAIT_DIALOG_TAG); - - if (result.isIdPRedirection()) { - String url = result.getRedirectedLocation(); - String targetUrl = mServerInfo.mBaseUrl - + AccountUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType); - - // Show dialog - SamlWebViewDialog dialog = SamlWebViewDialog.newInstance(url, targetUrl); - dialog.show(getSupportFragmentManager(), SAML_DIALOG_TAG); - - mAuthStatusIcon = 0; - mAuthStatusText = 0; - - } else { - mAuthStatusIcon = R.drawable.common_error; - mAuthStatusText = R.string.auth_unsupported_auth_method; - - } - showAuthStatus(); - } - - /** * Processes the result of the server check performed when the user finishes the enter of the * server URL. - * - * @param operation Server check performed. + * * @param result Result of the check. */ private void onGetServerInfoFinish(RemoteOperationResult result) { @@ -1089,16 +1108,12 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { private boolean authSupported(AuthenticationMethod authMethod) { - String basic = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType()); - String oAuth = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()); - String saml = AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()); - - return (( mAuthTokenType.equals(basic) && - authMethod.equals(AuthenticationMethod.BASIC_HTTP_AUTH) ) || - ( mAuthTokenType.equals(oAuth) && - authMethod.equals(AuthenticationMethod.BEARER_TOKEN)) || - ( mAuthTokenType.equals(saml) && - authMethod.equals(AuthenticationMethod.SAML_WEB_SSO)) + return (( BASIC_TOKEN_TYPE.equals(mAuthTokenType) && + AuthenticationMethod.BASIC_HTTP_AUTH.equals(authMethod) ) || + ( OAUTH_TOKEN_TYPE.equals(mAuthTokenType) && + AuthenticationMethod.BEARER_TOKEN.equals(authMethod)) || + ( SAML_TOKEN_TYPE.equals(mAuthTokenType) && + AuthenticationMethod.SAML_WEB_SSO.equals(authMethod)) ); } @@ -1115,7 +1130,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { url = "http://" + url; } } - + url = normalizeUrlSuffix(url); } return (url != null ? url : ""); @@ -1130,17 +1145,24 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { return url; } + private String stripIndexPhpOrAppsFiles(String url, EditText mHostUrlInput) { + if (url.endsWith("/index.php")) { + url = url.substring(0, url.lastIndexOf("/index.php")); + mHostUrlInput.setText(url); + } else if (url.contains("/index.php/apps/")) { + url = url.substring(0, url.lastIndexOf("/index.php/apps/")); + mHostUrlInput.setText(url); + } + + return url; + } // TODO remove, if possible private String trimUrlWebdav(String url){ - if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0)){ - url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0.length()); - } else if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_2_0)){ - url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_2_0.length()); - } else if (url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_1_2)){ - url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_1_2.length()); - } - return (url != null ? url : ""); + if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0_AND_LATER)){ + url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0_AND_LATER.length()); + } + return url; } @@ -1154,7 +1176,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { switch (result.getCode()) { case OK_SSL: - mServerStatusIcon = android.R.drawable.ic_secure; + mServerStatusIcon = R.drawable.ic_lock; mServerStatusText = R.string.auth_secure_connection; break; @@ -1165,7 +1187,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { mServerStatusIcon = R.drawable.ic_ok; } else { mServerStatusText = R.string.auth_nossl_plain_ok_title; - mServerStatusIcon = android.R.drawable.ic_partial_secure; + mServerStatusIcon = R.drawable.ic_lock_open; } break; @@ -1215,7 +1237,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { mServerStatusText = R.string.auth_unknown_error_title; break; case OK_REDIRECT_TO_NON_SECURE_CONNECTION: - mServerStatusIcon = android.R.drawable.ic_partial_secure; + mServerStatusIcon = R.drawable.ic_lock_open; mServerStatusText = R.string.auth_redirect_non_secure_connection_title; break; default: @@ -1235,7 +1257,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { switch (result.getCode()) { case OK_SSL: - mAuthStatusIcon = android.R.drawable.ic_secure; + mAuthStatusIcon = R.drawable.ic_lock; mAuthStatusText = R.string.auth_secure_connection; break; @@ -1246,7 +1268,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { mAuthStatusIcon = R.drawable.ic_ok; } else { mAuthStatusText = R.string.auth_nossl_plain_ok_title; - mAuthStatusIcon = android.R.drawable.ic_partial_secure; + mAuthStatusIcon = R.drawable.ic_lock_open; } break; @@ -1339,8 +1361,11 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { Map tokens = (Map)(result.getData().get(0)); mAuthToken = tokens.get(OAuth2Constants.KEY_ACCESS_TOKEN); Log_OC.d(TAG, "Got ACCESS TOKEN: " + mAuthToken); - - accessRootFolderRemoteOperation("", ""); + + /// validate token accessing to root folder / getting session + OwnCloudCredentials credentials = OwnCloudCredentialsFactory.newBearerCredentials( + mAuthToken); + accessRootFolder(credentials); } else { updateAuthStatusIconAndText(result); @@ -1354,31 +1379,41 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { * Processes the result of the access check performed to try the user credentials. * * Creates a new account through the AccountManager. - * - * @param operation Access check performed. + * * @param result Result of the operation. */ - private void onAuthorizationCheckFinish(RemoteOperationResult result) { + @Override + public void onAuthenticatorTaskCallback(RemoteOperationResult result) { mWaitingForOpId = Long.MAX_VALUE; dismissDialog(WAIT_DIALOG_TAG); + mAsyncTask = null; if (result.isSuccess()) { Log_OC.d(TAG, "Successful access - time to save the account"); boolean success = false; + if (mAction == ACTION_CREATE) { - success = createAccount(); + success = createAccount(result); } else { - updateToken(); - success = true; + try { + updateAccountAuthentication(); + success = true; + + } catch (AccountNotFoundException e) { + Log_OC.e(TAG, "Account " + mAccount + " was removed!", e); + Toast.makeText(this, R.string.auth_account_does_not_exist, + Toast.LENGTH_SHORT).show(); + finish(); + } } if (success) { finish(); } - } else if (result.isServerFail() || result.isException()) { + } else if (result.isServerFail() || result.isException()) { /// server errors or exceptions in authorization take to requiring a new check of /// the server mServerIsChecked = true; @@ -1412,16 +1447,22 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { /** - * Sets the proper response to get that the Account Authenticator that started this activity + * Updates the authentication token. + * + * Sets the proper response so that the AccountAuthenticator that started this activity * saves a new authorization token for mAccount. + * + * Kills the session kept by OwnCloudClientManager so that a new one will created with + * the new credentials when needed. */ - private void updateToken() { + private void updateAccountAuthentication() throws AccountNotFoundException { + Bundle response = new Bundle(); response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name); response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type); if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()). - equals(mAuthTokenType)) { + equals(mAuthTokenType)) { response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken); // the next line is necessary, notifications are calling directly to the // AuthenticatorActivity to update, without AccountManager intervention @@ -1451,13 +1492,18 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { * * TODO Decide how to name the OAuth accounts */ - private boolean createAccount() { + private boolean createAccount(RemoteOperationResult authResult) { /// create and save new ownCloud account boolean isOAuth = AccountTypeUtils. getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType); boolean isSaml = AccountTypeUtils. getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType); + String lastPermanentLocation = authResult.getLastPermanentLocation(); + if (lastPermanentLocation != null) { + mServerInfo.mBaseUrl = AccountUtils.trimWebdavSuffix(lastPermanentLocation); + } + Uri uri = Uri.parse(mServerInfo.mBaseUrl); String username = mUsernameInput.getText().toString().trim(); if (isOAuth) { @@ -1486,6 +1532,13 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { ); } + // include account version with the new account + mAccountMgr.setUserData( + mAccount, + Constants.KEY_OC_ACCOUNT_VERSION, + Integer.toString(AccountUtils.ACCOUNT_VERSION) + ); + /// add the new account as default in preferences, if there is none already Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this); if (defaultAccount == null) { @@ -1501,21 +1554,19 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { final Intent intent = new Intent(); intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, MainApp.getAccountType()); intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name); - /*if (!isOAuth) - intent.putExtra(AccountManager.KEY_AUTHTOKEN, MainApp.getAccountType()); */ intent.putExtra(AccountManager.KEY_USERDATA, username); if (isOAuth || isSaml) { mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken); } /// add user data to the new account; TODO probably can be done in the last parameter - // addAccountExplicitly, or in KEY_USERDATA + // addAccountExplicitly, or in KEY_USERDATA mAccountMgr.setUserData( - mAccount, Constants.KEY_OC_VERSION, mServerInfo.mVersion.getVersion() + mAccount, Constants.KEY_OC_VERSION, mServerInfo.mVersion.getVersion() ); mAccountMgr.setUserData( mAccount, Constants.KEY_OC_BASE_URL, mServerInfo.mBaseUrl ); - + if (isSaml) { mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE"); } else if (isOAuth) { @@ -1547,9 +1598,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { /** * Updates the content and visibility state of the icon and text associated * to the last check on the ownCloud server. - * - * @param serverStatusText Resource identifier of the text to show. - * @param serverStatusIcon Resource identifier of the icon to show. + * */ private void showServerStatus() { if (mServerStatusIcon == 0 && mServerStatusText == 0) { @@ -1627,9 +1676,9 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { public void onCheckClick(View view) { CheckBox oAuth2Check = (CheckBox)view; if (oAuth2Check.isChecked()) { - mAuthTokenType = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()); + mAuthTokenType = OAUTH_TOKEN_TYPE; } else { - mAuthTokenType = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType()); + mAuthTokenType = BASIC_TOKEN_TYPE; } updateAuthenticationPreFragmentVisibility(); } @@ -1695,7 +1744,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { } - private void getRemoteUserNameOperation(String sessionCookie, boolean followRedirects) { + private void getRemoteUserNameOperation(String sessionCookie) { Intent getUserNameIntent = new Intent(); getUserNameIntent.setAction(OperationsService.ACTION_GET_USER_NAME); @@ -1703,7 +1752,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { getUserNameIntent.putExtra(OperationsService.EXTRA_COOKIE, sessionCookie); if (mOperationsServiceBinder != null) { - //Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." ); mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getUserNameIntent); } } @@ -1714,10 +1762,10 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { if (sessionCookie != null && sessionCookie.length() > 0) { Log_OC.d(TAG, "Successful SSO - time to save the account"); mAuthToken = sessionCookie; - getRemoteUserNameOperation(sessionCookie, true); + getRemoteUserNameOperation(sessionCookie); Fragment fd = getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG); - if (fd != null && fd instanceof SherlockDialogFragment) { - Dialog d = ((SherlockDialogFragment)fd).getDialog(); + if (fd != null && fd instanceof DialogFragment) { + Dialog d = ((DialogFragment)fd).getDialog(); if (d != null && d.isShowing()) { d.dismiss(); } @@ -1748,7 +1796,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { X509Certificate x509Certificate, SslError error, SslErrorHandler handler ) { // Show a dialog with the certificate info - SslUntrustedCertDialog dialog = null; + SslUntrustedCertDialog dialog; if (x509Certificate == null) { dialog = SslUntrustedCertDialog.newInstanceForEmptySslError(error, handler); } else { @@ -1819,8 +1867,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { private void dismissDialog(String dialogTag){ Fragment frag = getSupportFragmentManager().findFragmentByTag(dialogTag); - if (frag != null && frag instanceof SherlockDialogFragment) { - SherlockDialogFragment dialog = (SherlockDialogFragment) frag; + if (frag != null && frag instanceof DialogFragment) { + DialogFragment dialog = (DialogFragment) frag; dialog.dismiss(); } } @@ -1836,13 +1884,10 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { if (component.equals( new ComponentName(AuthenticatorActivity.this, OperationsService.class) )) { - //Log_OC.wtf(TAG, "Operations service connected"); mOperationsServiceBinder = (OperationsServiceBinder) service; doOnResumeAndBound(); - } else { - return; } } @@ -1861,8 +1906,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { /** * Create and show dialog for request authentication to the user - * @param webView - * @param handler + * @param webView Web view to emebd into the authentication dialog. + * @param handler Object responsible for catching and recovering HTTP authentication fails. */ public void createAuthenticationDialog(WebView webView, HttpAuthHandler handler) { @@ -1892,4 +1937,5 @@ SsoWebViewClientListener, OnSslUntrustedCertListener { public void doNegativeAuthenticatioDialogClick(){ mIsFirstAuthAttempt = true; } + }