Adapt behaviour Authentication AyncTask + rotations
[pub/Android/ownCloud.git] / src / com / owncloud / android / authentication / AuthenticatorActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2015 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package com.owncloud.android.authentication;
20
21 import java.security.cert.X509Certificate;
22 import java.util.Map;
23
24 import android.accounts.Account;
25 import android.accounts.AccountManager;
26 import android.app.Dialog;
27 import android.content.ComponentName;
28 import android.content.Context;
29 import android.content.Intent;
30 import android.content.ServiceConnection;
31 import android.content.SharedPreferences;
32 import android.graphics.Rect;
33 import android.graphics.drawable.Drawable;
34 import android.net.Uri;
35 import android.net.http.SslError;
36 import android.os.AsyncTask;
37 import android.os.Bundle;
38 import android.os.Handler;
39 import android.os.IBinder;
40 import android.preference.PreferenceManager;
41 import android.support.v4.app.Fragment;
42 import android.support.v4.app.FragmentManager;
43 import android.support.v4.app.FragmentTransaction;
44 import android.text.Editable;
45 import android.text.InputType;
46 import android.text.TextWatcher;
47 import android.view.KeyEvent;
48 import android.view.MotionEvent;
49 import android.view.View;
50 import android.view.View.OnFocusChangeListener;
51 import android.view.View.OnTouchListener;
52 import android.view.Window;
53 import android.view.inputmethod.EditorInfo;
54 import android.webkit.HttpAuthHandler;
55 import android.webkit.SslErrorHandler;
56 import android.webkit.WebView;
57 import android.widget.Button;
58 import android.widget.CheckBox;
59 import android.widget.EditText;
60 import android.widget.TextView;
61 import android.widget.TextView.OnEditorActionListener;
62 import android.widget.Toast;
63
64 import com.actionbarsherlock.app.SherlockDialogFragment;
65 import com.owncloud.android.MainApp;
66 import com.owncloud.android.R;
67 import com.owncloud.android.authentication.SsoWebViewClient.SsoWebViewClientListener;
68 import com.owncloud.android.lib.common.accounts.AccountTypeUtils;
69 import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
70 import com.owncloud.android.lib.common.network.CertificateCombinedException;
71 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
72 import com.owncloud.android.lib.common.operations.RemoteOperation;
73 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
74 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
75 import com.owncloud.android.lib.common.utils.Log_OC;
76 import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
77 import com.owncloud.android.lib.resources.status.OwnCloudVersion;
78 import com.owncloud.android.lib.resources.users.GetRemoteUserNameOperation;
79 import com.owncloud.android.operations.DetectAuthenticationMethodOperation.AuthenticationMethod;
80 import com.owncloud.android.operations.GetServerInfoOperation;
81 import com.owncloud.android.operations.OAuth2GetAccessToken;
82 import com.owncloud.android.services.OperationsService;
83 import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
84 import com.owncloud.android.ui.dialog.CredentialsDialogFragment;
85 import com.owncloud.android.ui.dialog.IndeterminateProgressDialog;
86 import com.owncloud.android.ui.dialog.SamlWebViewDialog;
87 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
88 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
89 import com.owncloud.android.utils.DisplayUtils;
90
91 /**
92 * This Activity is used to add an ownCloud account to the App
93 *
94 * @author Bartek Przybylski
95 * @author David A. Velasco
96 * @author masensio
97 */
98 public class AuthenticatorActivity extends AccountAuthenticatorActivity
99 implements OnRemoteOperationListener, OnFocusChangeListener, OnEditorActionListener,
100 SsoWebViewClientListener, OnSslUntrustedCertListener,
101 AuthenticatorAsyncTask.OnAuthenticatorTaskListener {
102
103 private static final String TAG = AuthenticatorActivity.class.getSimpleName();
104
105 public static final String EXTRA_ACTION = "ACTION";
106 public static final String EXTRA_ACCOUNT = "ACCOUNT";
107
108 private static final String KEY_AUTH_TOKEN_TYPE = "AUTH_TOKEN_TYPE";
109
110 private static final String KEY_HOST_URL_TEXT = "HOST_URL_TEXT";
111 private static final String KEY_OC_VERSION = "OC_VERSION";
112 private static final String KEY_SERVER_VALID = "SERVER_VALID";
113 private static final String KEY_SERVER_CHECKED = "SERVER_CHECKED";
114 private static final String KEY_SERVER_STATUS_TEXT = "SERVER_STATUS_TEXT";
115 private static final String KEY_SERVER_STATUS_ICON = "SERVER_STATUS_ICON";
116 private static final String KEY_IS_SSL_CONN = "IS_SSL_CONN";
117 private static final String KEY_PASSWORD_EXPOSED = "PASSWORD_VISIBLE";
118 private static final String KEY_AUTH_STATUS_TEXT = "AUTH_STATUS_TEXT";
119 private static final String KEY_AUTH_STATUS_ICON = "AUTH_STATUS_ICON";
120 private static final String KEY_SERVER_AUTH_METHOD = "SERVER_AUTH_METHOD";
121 private static final String KEY_WAITING_FOR_OP_ID = "WAITING_FOR_OP_ID";
122 private static final String KEY_AUTH_TOKEN = "AUTH_TOKEN";
123
124 private static final String AUTH_ON = "on";
125 private static final String AUTH_OPTIONAL = "optional";
126
127 public static final byte ACTION_CREATE = 0;
128 public static final byte ACTION_UPDATE_TOKEN = 1; // requested by the user
129 public static final byte ACTION_UPDATE_EXPIRED_TOKEN = 2; // detected by the app
130
131 private static final String UNTRUSTED_CERT_DIALOG_TAG = "UNTRUSTED_CERT_DIALOG";
132 private static final String SAML_DIALOG_TAG = "SAML_DIALOG";
133 private static final String WAIT_DIALOG_TAG = "WAIT_DIALOG";
134 private static final String CREDENTIALS_DIALOG_TAG = "CREDENTIALS_DIALOG";
135 private static final String KEY_AUTH_IS_FIRST_ATTEMPT_TAG = "KEY_AUTH_IS_FIRST_ATTEMPT";
136
137 private static final String KEY_USERNAME = "USERNAME";
138 private static final String KEY_PASSWORD = "PASSWORD";
139 private static final String KEY_ASYNC_TASK_IN_PROGRESS = "AUTH_IN_PROGRESS";
140
141 /// parameters from EXTRAs in starter Intent
142 private byte mAction;
143 private Account mAccount;
144 private String mAuthTokenType;
145
146
147 /// activity-level references / state
148 private final Handler mHandler = new Handler();
149 private ServiceConnection mOperationsServiceConnection = null;
150 private OperationsServiceBinder mOperationsServiceBinder = null;
151 private AccountManager mAccountMgr;
152 private Uri mNewCapturedUriFromOAuth2Redirection;
153
154
155 /// Server PRE-Fragment elements
156 private EditText mHostUrlInput;
157 private View mRefreshButton;
158 private TextView mServerStatusView;
159
160 private TextWatcher mHostUrlInputWatcher;
161 private int mServerStatusText = 0, mServerStatusIcon = 0;
162
163 private boolean mServerIsChecked = false;
164 private boolean mServerIsValid = false;
165 private boolean mPendingAutoCheck = false;
166
167 private GetServerInfoOperation.ServerInfo mServerInfo =
168 new GetServerInfoOperation.ServerInfo();
169
170
171 /// Authentication PRE-Fragment elements
172 private CheckBox mOAuth2Check;
173 private TextView mOAuthAuthEndpointText;
174 private TextView mOAuthTokenEndpointText;
175 private EditText mUsernameInput;
176 private EditText mPasswordInput;
177 private View mOkButton;
178 private TextView mAuthStatusView;
179
180 private int mAuthStatusText = 0, mAuthStatusIcon = 0;
181
182 private String mAuthToken = "";
183 private AuthenticatorAsyncTask mAsyncTask;
184
185 private boolean mIsFirstAuthAttempt;
186
187 /// Identifier of operation in progress which result shouldn't be lost
188 private long mWaitingForOpId = Long.MAX_VALUE;
189
190
191 /**
192 * {@inheritDoc}
193 *
194 * IMPORTANT ENTRY POINT 1: activity is shown to the user
195 */
196 @Override
197 protected void onCreate(Bundle savedInstanceState) {
198 //Log_OC.wtf(TAG, "onCreate init");
199 super.onCreate(savedInstanceState);
200 getWindow().requestFeature(Window.FEATURE_NO_TITLE);
201
202 mIsFirstAuthAttempt = true;
203
204 // bind to Operations Service
205 mOperationsServiceConnection = new OperationsServiceConnection();
206 if (!bindService(new Intent(this, OperationsService.class),
207 mOperationsServiceConnection,
208 Context.BIND_AUTO_CREATE)) {
209 Toast.makeText(this,
210 R.string.error_cant_bind_to_operations_service,
211 Toast.LENGTH_LONG)
212 .show();
213 finish();
214 }
215
216 /// init activity state
217 mAccountMgr = AccountManager.get(this);
218 mNewCapturedUriFromOAuth2Redirection = null;
219
220 /// get input values
221 mAction = getIntent().getByteExtra(EXTRA_ACTION, ACTION_CREATE);
222 mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT);
223 if (savedInstanceState == null) {
224 initAuthTokenType();
225 } else {
226 mAuthTokenType = savedInstanceState.getString(KEY_AUTH_TOKEN_TYPE);
227 mWaitingForOpId = savedInstanceState.getLong(KEY_WAITING_FOR_OP_ID);
228 mIsFirstAuthAttempt = savedInstanceState.getBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG);
229 }
230
231
232
233 /// load user interface
234 setContentView(R.layout.account_setup);
235
236 /// initialize general UI elements
237 initOverallUi(savedInstanceState);
238
239 mOkButton = findViewById(R.id.buttonOK);
240
241 /// initialize block to be moved to single Fragment to check server and get info about it
242 initServerPreFragment(savedInstanceState);
243
244 /// initialize block to be moved to single Fragment to retrieve and validate credentials
245 initAuthorizationPreFragment(savedInstanceState);
246
247 //Log_OC.wtf(TAG, "onCreate end");
248 }
249
250 private void initAuthTokenType() {
251 mAuthTokenType =
252 getIntent().getExtras().getString(AccountAuthenticator.KEY_AUTH_TOKEN_TYPE);
253 if (mAuthTokenType == null) {
254 if (mAccount != null) {
255 boolean oAuthRequired =
256 (mAccountMgr.getUserData(mAccount, Constants.KEY_SUPPORTS_OAUTH2) != null);
257 boolean samlWebSsoRequired = (
258 mAccountMgr.getUserData(
259 mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO
260 ) != null
261 );
262 mAuthTokenType = chooseAuthTokenType(oAuthRequired, samlWebSsoRequired);
263
264 } else {
265 boolean oAuthSupported = AUTH_ON.equals(getString(R.string.auth_method_oauth2));
266 boolean samlWebSsoSupported =
267 AUTH_ON.equals(getString(R.string.auth_method_saml_web_sso));
268 mAuthTokenType = chooseAuthTokenType(oAuthSupported, samlWebSsoSupported);
269 }
270 }
271 }
272
273 private String chooseAuthTokenType(boolean oauth, boolean saml) {
274 if (saml) {
275 return AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType());
276 } else if (oauth) {
277 return AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());
278 } else {
279 return AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());
280 }
281 }
282
283
284 /**
285 * Configures elements in the user interface under direct control of the Activity.
286 *
287 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
288 */
289 private void initOverallUi(Bundle savedInstanceState) {
290
291 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
292 boolean isWelcomeLinkVisible = getResources().getBoolean(R.bool.show_welcome_link);
293
294 String instructionsMessageText = null;
295 if (mAction == ACTION_UPDATE_EXPIRED_TOKEN) {
296 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType())
297 .equals(mAuthTokenType)) {
298 instructionsMessageText = getString(R.string.auth_expired_oauth_token_toast);
299
300 } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType())
301 .equals(mAuthTokenType)) {
302 instructionsMessageText = getString(R.string.auth_expired_saml_sso_token_toast);
303
304 } else {
305 instructionsMessageText = getString(R.string.auth_expired_basic_auth_toast);
306 }
307 }
308
309 /// step 2 - set properties of UI elements (text, visibility, enabled...)
310 Button welcomeLink = (Button) findViewById(R.id.welcome_link);
311 welcomeLink.setVisibility(isWelcomeLinkVisible ? View.VISIBLE : View.GONE);
312 welcomeLink.setText(
313 String.format(getString(R.string.auth_register), getString(R.string.app_name)));
314
315 TextView instructionsView = (TextView) findViewById(R.id.instructions_message);
316 if (instructionsMessageText != null) {
317 instructionsView.setVisibility(View.VISIBLE);
318 instructionsView.setText(instructionsMessageText);
319 } else {
320 instructionsView.setVisibility(View.GONE);
321 }
322 }
323
324
325 /**
326 *
327 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
328 */
329 private void initServerPreFragment(Bundle savedInstanceState) {
330
331 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
332 boolean isUrlInputAllowed = getResources().getBoolean(R.bool.show_server_url_input);
333 if (savedInstanceState == null) {
334 if (mAccount != null) {
335 mServerInfo.mBaseUrl = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_BASE_URL);
336 // TODO do next in a setter for mBaseUrl
337 mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith("https://");
338 String ocVersion = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_VERSION);
339 if (ocVersion != null) {
340 mServerInfo.mVersion = new OwnCloudVersion(ocVersion);
341 }
342 } else {
343 mServerInfo.mBaseUrl = getString(R.string.server_url).trim();
344 mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith("https://");
345 }
346 } else {
347 mServerStatusText = savedInstanceState.getInt(KEY_SERVER_STATUS_TEXT);
348 mServerStatusIcon = savedInstanceState.getInt(KEY_SERVER_STATUS_ICON);
349
350 mServerIsValid = savedInstanceState.getBoolean(KEY_SERVER_VALID);
351 mServerIsChecked = savedInstanceState.getBoolean(KEY_SERVER_CHECKED);
352
353 // TODO parcelable
354 mServerInfo.mIsSslConn = savedInstanceState.getBoolean(KEY_IS_SSL_CONN);
355 mServerInfo.mBaseUrl = savedInstanceState.getString(KEY_HOST_URL_TEXT);
356 String ocVersion = savedInstanceState.getString(KEY_OC_VERSION);
357 if (ocVersion != null) {
358 mServerInfo.mVersion = new OwnCloudVersion(ocVersion);
359 }
360 mServerInfo.mAuthMethod = AuthenticationMethod.valueOf(
361 savedInstanceState.getString(KEY_SERVER_AUTH_METHOD));
362
363 }
364
365 /// step 2 - set properties of UI elements (text, visibility, enabled...)
366 mHostUrlInput = (EditText) findViewById(R.id.hostUrlInput);
367 // Convert IDN to Unicode
368 mHostUrlInput.setText(DisplayUtils.convertIdn(mServerInfo.mBaseUrl, false));
369 if (mAction != ACTION_CREATE) {
370 /// lock things that should not change
371 mHostUrlInput.setEnabled(false);
372 mHostUrlInput.setFocusable(false);
373 }
374 if (isUrlInputAllowed) {
375 mRefreshButton = findViewById(R.id.embeddedRefreshButton);
376 } else {
377 findViewById(R.id.hostUrlFrame).setVisibility(View.GONE);
378 mRefreshButton = findViewById(R.id.centeredRefreshButton);
379 }
380 showRefreshButton(mServerIsChecked && !mServerIsValid &&
381 mWaitingForOpId > Integer.MAX_VALUE);
382 mServerStatusView = (TextView) findViewById(R.id.server_status_text);
383 showServerStatus();
384
385 /// step 3 - bind some listeners and options
386 mHostUrlInput.setImeOptions(EditorInfo.IME_ACTION_NEXT);
387 mHostUrlInput.setOnEditorActionListener(this);
388
389 /// step 4 - create listeners that will be bound at onResume
390 mHostUrlInputWatcher = new TextWatcher() {
391
392 @Override
393 public void afterTextChanged(Editable s) {
394 if (mOkButton.isEnabled() &&
395 !mServerInfo.mBaseUrl.equals(
396 normalizeUrl(s.toString(), mServerInfo.mIsSslConn))) {
397 mOkButton.setEnabled(false);
398 }
399 }
400
401 @Override
402 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
403 }
404
405 @Override
406 public void onTextChanged(CharSequence s, int start, int before, int count) {
407 if (mAuthStatusIcon != 0) {
408 Log_OC.d(TAG, "onTextChanged: hiding authentication status");
409 mAuthStatusIcon = 0;
410 mAuthStatusText = 0;
411 showAuthStatus();
412 }
413 }
414 };
415
416
417 // TODO find out if this is really necessary, or if it can done in a different way
418 findViewById(R.id.scroll).setOnTouchListener(new OnTouchListener() {
419 @Override
420 public boolean onTouch(View view, MotionEvent event) {
421 if (event.getAction() == MotionEvent.ACTION_DOWN) {
422 if (
423 AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(
424 MainApp.getAccountType()
425 ).equals(mAuthTokenType) &&
426 mHostUrlInput.hasFocus()
427 ) {
428 checkOcServer();
429 }
430 }
431 return false;
432 }
433 });
434
435
436 /// step 4 - mark automatic check to be started when OperationsService is ready
437 mPendingAutoCheck = (savedInstanceState == null &&
438 (mAction != ACTION_CREATE || !isUrlInputAllowed));
439 }
440
441
442 /**
443 *
444 * @param savedInstanceState Saved activity state, as in {{@link #onCreate(Bundle)}
445 */
446 private void initAuthorizationPreFragment(Bundle savedInstanceState) {
447
448 /// step 0 - get UI elements in layout
449 mOAuth2Check = (CheckBox) findViewById(R.id.oauth_onOff_check);
450 mOAuthAuthEndpointText = (TextView)findViewById(R.id.oAuthEntryPoint_1);
451 mOAuthTokenEndpointText = (TextView)findViewById(R.id.oAuthEntryPoint_2);
452 mUsernameInput = (EditText) findViewById(R.id.account_username);
453 mPasswordInput = (EditText) findViewById(R.id.account_password);
454 mAuthStatusView = (TextView) findViewById(R.id.auth_status_text);
455
456 /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
457 String presetUserName = null;
458 boolean isPasswordExposed = false;
459 if (savedInstanceState == null) {
460 if (mAccount != null) {
461 presetUserName = mAccount.name.substring(0, mAccount.name.lastIndexOf('@'));
462 }
463
464 } else {
465 isPasswordExposed = savedInstanceState.getBoolean(KEY_PASSWORD_EXPOSED, false);
466 mAuthStatusText = savedInstanceState.getInt(KEY_AUTH_STATUS_TEXT);
467 mAuthStatusIcon = savedInstanceState.getInt(KEY_AUTH_STATUS_ICON);
468 mAuthToken = savedInstanceState.getString(KEY_AUTH_TOKEN);
469 }
470
471 /// step 2 - set properties of UI elements (text, visibility, enabled...)
472 mOAuth2Check.setChecked(
473 AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType())
474 .equals(mAuthTokenType));
475 if (presetUserName != null) {
476 mUsernameInput.setText(presetUserName);
477 }
478 if (mAction != ACTION_CREATE) {
479 mUsernameInput.setEnabled(false);
480 mUsernameInput.setFocusable(false);
481 }
482 mPasswordInput.setText(""); // clean password to avoid social hacking
483 if (isPasswordExposed) {
484 showPassword();
485 }
486 updateAuthenticationPreFragmentVisibility();
487 showAuthStatus();
488 mOkButton.setEnabled(mServerIsValid);
489
490
491 /// step 3 - bind listeners
492 // bindings for password input field
493 mPasswordInput.setOnFocusChangeListener(this);
494 mPasswordInput.setImeOptions(EditorInfo.IME_ACTION_DONE);
495 mPasswordInput.setOnEditorActionListener(this);
496 mPasswordInput.setOnTouchListener(new RightDrawableOnTouchListener() {
497 @Override
498 public boolean onDrawableTouch(final MotionEvent event) {
499 if (event.getAction() == MotionEvent.ACTION_UP) {
500 AuthenticatorActivity.this.onViewPasswordClick();
501 }
502 return true;
503 }
504 });
505
506 }
507
508
509 /**
510 * Changes the visibility of input elements depending on
511 * the current authorization method.
512 */
513 private void updateAuthenticationPreFragmentVisibility () {
514 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
515 equals(mAuthTokenType)) {
516 // SAML-based web Single Sign On
517 mOAuth2Check.setVisibility(View.GONE);
518 mOAuthAuthEndpointText.setVisibility(View.GONE);
519 mOAuthTokenEndpointText.setVisibility(View.GONE);
520 mUsernameInput.setVisibility(View.GONE);
521 mPasswordInput.setVisibility(View.GONE);
522
523 } else {
524 if (mAction == ACTION_CREATE &&
525 AUTH_OPTIONAL.equals(getString(R.string.auth_method_oauth2))) {
526 mOAuth2Check.setVisibility(View.VISIBLE);
527 } else {
528 mOAuth2Check.setVisibility(View.GONE);
529 }
530
531 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).
532 equals(mAuthTokenType)) {
533 // OAuth 2 authorization
534
535 mOAuthAuthEndpointText.setVisibility(View.VISIBLE);
536 mOAuthTokenEndpointText.setVisibility(View.VISIBLE);
537 mUsernameInput.setVisibility(View.GONE);
538 mPasswordInput.setVisibility(View.GONE);
539
540 } else {
541 // basic HTTP authorization
542 mOAuthAuthEndpointText.setVisibility(View.GONE);
543 mOAuthTokenEndpointText.setVisibility(View.GONE);
544 mUsernameInput.setVisibility(View.VISIBLE);
545 mPasswordInput.setVisibility(View.VISIBLE);
546 }
547 }
548 }
549
550
551
552 /**
553 * Saves relevant state before {@link #onPause()}
554 *
555 * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag,
556 * intended to defer the processing of the redirection caught in
557 * {@link #onNewIntent(Intent)} until {@link #onResume()}
558 *
559 * See {@link #onSaveInstanceState(Bundle)}
560 */
561 @Override
562 protected void onSaveInstanceState(Bundle outState) {
563 //Log_OC.wtf(TAG, "onSaveInstanceState init" );
564 super.onSaveInstanceState(outState);
565
566 /// global state
567 outState.putString(KEY_AUTH_TOKEN_TYPE, mAuthTokenType);
568 outState.putLong(KEY_WAITING_FOR_OP_ID, mWaitingForOpId);
569
570 /// Server PRE-fragment state
571 outState.putInt(KEY_SERVER_STATUS_TEXT, mServerStatusText);
572 outState.putInt(KEY_SERVER_STATUS_ICON, mServerStatusIcon);
573 outState.putBoolean(KEY_SERVER_CHECKED, mServerIsChecked);
574 outState.putBoolean(KEY_SERVER_VALID, mServerIsValid);
575 outState.putBoolean(KEY_IS_SSL_CONN, mServerInfo.mIsSslConn);
576 outState.putString(KEY_HOST_URL_TEXT, mServerInfo.mBaseUrl);
577 if (mServerInfo.mVersion != null) {
578 outState.putString(KEY_OC_VERSION, mServerInfo.mVersion.getVersion());
579 }
580 outState.putString(KEY_SERVER_AUTH_METHOD, mServerInfo.mAuthMethod.name());
581
582 /// Authentication PRE-fragment state
583 outState.putBoolean(KEY_PASSWORD_EXPOSED, isPasswordVisible());
584 outState.putInt(KEY_AUTH_STATUS_ICON, mAuthStatusIcon);
585 outState.putInt(KEY_AUTH_STATUS_TEXT, mAuthStatusText);
586 outState.putString(KEY_AUTH_TOKEN, mAuthToken);
587
588 /// authentication
589 outState.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG, mIsFirstAuthAttempt);
590
591 /// AsyncTask (User and password)
592 outState.putString(KEY_USERNAME, mUsernameInput.getText().toString());
593 outState.putString(KEY_PASSWORD, mPasswordInput.getText().toString());
594
595 if (mAsyncTask != null) {
596 mAsyncTask.cancel(true);
597 outState.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS, true);
598 } else {
599 outState.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS, false);
600 }
601 mAsyncTask = null;
602
603 //Log_OC.wtf(TAG, "onSaveInstanceState end" );
604 }
605
606 @Override
607 public void onRestoreInstanceState(Bundle savedInstanceState) {
608 super.onRestoreInstanceState(savedInstanceState);
609
610 // AsyncTask
611 boolean inProgress = savedInstanceState.getBoolean(KEY_ASYNC_TASK_IN_PROGRESS);
612 if (inProgress){
613 mAsyncTask = new AuthenticatorAsyncTask(this);
614 String username = savedInstanceState.getString(KEY_USERNAME);
615 String password = savedInstanceState.getString(KEY_PASSWORD);
616 String[] params = {mServerInfo.mBaseUrl, username, password, mAuthToken, mAuthTokenType};
617 mAsyncTask.execute(params);
618 }
619 }
620
621 /**
622 * The redirection triggered by the OAuth authentication server as response to the
623 * GET AUTHORIZATION request is caught here.
624 *
625 * To make this possible, this activity needs to be qualified with android:launchMode =
626 * "singleTask" in the AndroidManifest.xml file.
627 */
628 @Override
629 protected void onNewIntent (Intent intent) {
630 Log_OC.d(TAG, "onNewIntent()");
631 Uri data = intent.getData();
632 if (data != null && data.toString().startsWith(getString(R.string.oauth2_redirect_uri))) {
633 mNewCapturedUriFromOAuth2Redirection = data;
634 }
635 }
636
637
638 /**
639 * The redirection triggered by the OAuth authentication server as response to the
640 * GET AUTHORIZATION, and deferred in {@link #onNewIntent(Intent)}, is processed here.
641 */
642 @Override
643 protected void onResume() {
644 //Log_OC.wtf(TAG, "onResume init" );
645 super.onResume();
646
647 // bound here to avoid spurious changes triggered by Android on device rotations
648 mHostUrlInput.setOnFocusChangeListener(this);
649 mHostUrlInput.addTextChangedListener(mHostUrlInputWatcher);
650
651 if (mNewCapturedUriFromOAuth2Redirection != null) {
652 getOAuth2AccessTokenFromCapturedRedirection();
653 }
654
655 if (mOperationsServiceBinder != null) {
656 doOnResumeAndBound();
657 }
658
659 //Log_OC.wtf(TAG, "onResume end" );
660 }
661
662
663 @Override
664 protected void onPause() {
665 //Log_OC.wtf(TAG, "onPause init" );
666 if (mOperationsServiceBinder != null) {
667 //Log_OC.wtf(TAG, "unregistering to listen for operation callbacks" );
668 mOperationsServiceBinder.removeOperationListener(this);
669 }
670
671 mHostUrlInput.removeTextChangedListener(mHostUrlInputWatcher);
672 mHostUrlInput.setOnFocusChangeListener(null);
673
674 super.onPause();
675 //Log_OC.wtf(TAG, "onPause end" );
676 }
677
678 @Override
679 protected void onDestroy() {
680
681 mHostUrlInputWatcher = null;
682
683 if (mOperationsServiceConnection != null) {
684 unbindService(mOperationsServiceConnection);
685 mOperationsServiceBinder = null;
686 }
687 super.onDestroy();
688 }
689
690
691 /**
692 * Parses the redirection with the response to the GET AUTHORIZATION request to the
693 * oAuth server and requests for the access token (GET ACCESS TOKEN)
694 */
695 private void getOAuth2AccessTokenFromCapturedRedirection() {
696 /// Parse data from OAuth redirection
697 String queryParameters = mNewCapturedUriFromOAuth2Redirection.getQuery();
698 mNewCapturedUriFromOAuth2Redirection = null;
699
700 /// Showing the dialog with instructions for the user.
701 IndeterminateProgressDialog dialog =
702 IndeterminateProgressDialog.newInstance(R.string.auth_getting_authorization, true);
703 dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
704
705 /// GET ACCESS TOKEN to the oAuth server
706 Intent getServerInfoIntent = new Intent();
707 getServerInfoIntent.setAction(OperationsService.ACTION_OAUTH2_GET_ACCESS_TOKEN);
708
709 getServerInfoIntent.putExtra(
710 OperationsService.EXTRA_SERVER_URL,
711 mOAuthTokenEndpointText.getText().toString().trim());
712
713 getServerInfoIntent.putExtra(
714 OperationsService.EXTRA_OAUTH2_QUERY_PARAMETERS,
715 queryParameters);
716
717 if (mOperationsServiceBinder != null) {
718 //Log_OC.wtf(TAG, "getting access token..." );
719 mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getServerInfoIntent);
720 }
721 }
722
723
724
725 /**
726 * Handles the change of focus on the text inputs for the server URL and the password
727 */
728 public void onFocusChange(View view, boolean hasFocus) {
729 if (view.getId() == R.id.hostUrlInput) {
730 if (!hasFocus) {
731 onUrlInputFocusLost((TextView) view);
732 }
733 else {
734 showRefreshButton(false);
735 }
736
737 } else if (view.getId() == R.id.account_password) {
738 onPasswordFocusChanged((TextView) view, hasFocus);
739 }
740 }
741
742
743 /**
744 * Handles changes in focus on the text input for the server URL.
745 *
746 * IMPORTANT ENTRY POINT 2: When (!hasFocus), user wrote the server URL and changed to
747 * other field. The operation to check the existence of the server in the entered URL is
748 * started.
749 *
750 * When hasFocus: user 'comes back' to write again the server URL.
751 *
752 * @param hostInput TextView with the URL input field receiving the change of focus.
753 */
754 private void onUrlInputFocusLost(TextView hostInput) {
755 if (!mServerInfo.mBaseUrl.equals(
756 normalizeUrl(mHostUrlInput.getText().toString(), mServerInfo.mIsSslConn))) {
757 // check server again only if the user changed something in the field
758 checkOcServer();
759 } else {
760 mOkButton.setEnabled(mServerIsValid);
761 showRefreshButton(!mServerIsValid);
762 }
763 }
764
765
766 private void checkOcServer() {
767 String uri = mHostUrlInput.getText().toString().trim();
768 mServerIsValid = false;
769 mServerIsChecked = false;
770 mOkButton.setEnabled(false);
771 mServerInfo = new GetServerInfoOperation.ServerInfo();
772 showRefreshButton(false);
773
774 if (uri.length() != 0) {
775 // Handle internationalized domain names
776 uri = DisplayUtils.convertIdn(uri, true);
777 mServerStatusText = R.string.auth_testing_connection;
778 mServerStatusIcon = R.drawable.progress_small;
779 showServerStatus();
780
781 Intent getServerInfoIntent = new Intent();
782 getServerInfoIntent.setAction(OperationsService.ACTION_GET_SERVER_INFO);
783 getServerInfoIntent.putExtra(
784 OperationsService.EXTRA_SERVER_URL,
785 normalizeUrlSuffix(uri)
786 );
787 if (mOperationsServiceBinder != null) {
788 mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getServerInfoIntent);
789 } else {
790 Log_OC.wtf(TAG, "Server check tried with OperationService unbound!" );
791 }
792
793 } else {
794 mServerStatusText = 0;
795 mServerStatusIcon = 0;
796 showServerStatus();
797 }
798 }
799
800
801 /**
802 * Handles changes in focus on the text input for the password (basic authorization).
803 *
804 * When (hasFocus), the button to toggle password visibility is shown.
805 *
806 * When (!hasFocus), the button is made invisible and the password is hidden.
807 *
808 * @param passwordInput TextView with the password input field receiving the change of focus.
809 * @param hasFocus 'True' if focus is received, 'false' if is lost
810 */
811 private void onPasswordFocusChanged(TextView passwordInput, boolean hasFocus) {
812 if (hasFocus) {
813 showViewPasswordButton();
814 } else {
815 hidePassword();
816 hidePasswordButton();
817 }
818 }
819
820
821 private void showViewPasswordButton() {
822 int drawable = R.drawable.ic_view;
823 if (isPasswordVisible()) {
824 drawable = R.drawable.ic_hide;
825 }
826 mPasswordInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable, 0);
827 }
828
829 private boolean isPasswordVisible() {
830 return ((mPasswordInput.getInputType() & InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) ==
831 InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
832 }
833
834 private void hidePasswordButton() {
835 mPasswordInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
836 }
837
838 private void showPassword() {
839 mPasswordInput.setInputType(
840 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
841 );
842 showViewPasswordButton();
843 }
844
845 private void hidePassword() {
846 mPasswordInput.setInputType(
847 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
848 );
849 showViewPasswordButton();
850 }
851
852 /**
853 * Checks the credentials of the user in the root of the ownCloud server
854 * before creating a new local account.
855 *
856 * For basic authorization, a check of existence of the root folder is
857 * performed.
858 *
859 * For OAuth, starts the flow to get an access token; the credentials test
860 * is postponed until it is available.
861 *
862 * IMPORTANT ENTRY POINT 4
863 *
864 * @param view OK button
865 */
866 public void onOkClick(View view) {
867 // this check should be unnecessary
868 if (mServerInfo.mVersion == null ||
869 !mServerInfo.mVersion.isVersionValid() ||
870 mServerInfo.mBaseUrl == null ||
871 mServerInfo.mBaseUrl.length() == 0) {
872 mServerStatusIcon = R.drawable.common_error;
873 mServerStatusText = R.string.auth_wtf_reenter_URL;
874 showServerStatus();
875 mOkButton.setEnabled(false);
876 //Log_OC.wtf(TAG, "The user was allowed to click 'connect' to an unchecked server!!");
877 return;
878 }
879
880 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).
881 equals(mAuthTokenType)) {
882
883 startOauthorization();
884 } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
885 equals(mAuthTokenType)) {
886
887 startSamlBasedFederatedSingleSignOnAuthorization();
888 } else {
889 checkBasicAuthorization();
890 }
891 }
892
893
894 /**
895 * Tests the credentials entered by the user performing a check of existence on
896 * the root folder of the ownCloud server.
897 */
898 private void checkBasicAuthorization() {
899 /// get basic credentials entered by user
900 String username = mUsernameInput.getText().toString();
901 String password = mPasswordInput.getText().toString();
902
903 /// be gentle with the user
904 IndeterminateProgressDialog dialog =
905 IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);
906 dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
907
908 /// validate credentials accessing the root folder
909 accessRootFolderRemoteOperation(username, password);
910
911 }
912
913 private void accessRootFolderRemoteOperation(String username, String password) {
914 // delete the account if the token has changed
915 if (mAction == ACTION_UPDATE_TOKEN || mAction == ACTION_UPDATE_EXPIRED_TOKEN) {
916 // Remove the cookies in AccountManager
917 mAccountMgr.setUserData(mAccount, Constants.KEY_COOKIES, null);
918 }
919
920 mAsyncTask = new AuthenticatorAsyncTask(this);
921 String[] params = { mServerInfo.mBaseUrl, username, password, mAuthToken, mAuthTokenType};
922 mAsyncTask.execute(params);
923
924 }
925
926 /**
927 * Starts the OAuth 'grant type' flow to get an access token, with
928 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
929 */
930 private void startOauthorization() {
931 // be gentle with the user
932 mAuthStatusIcon = R.drawable.progress_small;
933 mAuthStatusText = R.string.oauth_login_connection;
934 showAuthStatus();
935
936 // GET AUTHORIZATION request
937 Uri uri = Uri.parse(mOAuthAuthEndpointText.getText().toString().trim());
938 Uri.Builder uriBuilder = uri.buildUpon();
939 uriBuilder.appendQueryParameter(
940 OAuth2Constants.KEY_RESPONSE_TYPE, getString(R.string.oauth2_response_type)
941 );
942 uriBuilder.appendQueryParameter(
943 OAuth2Constants.KEY_REDIRECT_URI, getString(R.string.oauth2_redirect_uri)
944 );
945 uriBuilder.appendQueryParameter(
946 OAuth2Constants.KEY_CLIENT_ID, getString(R.string.oauth2_client_id)
947 );
948 uriBuilder.appendQueryParameter(
949 OAuth2Constants.KEY_SCOPE, getString(R.string.oauth2_scope)
950 );
951 uri = uriBuilder.build();
952 Log_OC.d(TAG, "Starting browser to view " + uri.toString());
953 Intent i = new Intent(Intent.ACTION_VIEW, uri);
954 startActivity(i);
955 }
956
957
958 /**
959 * Starts the Web Single Sign On flow to get access to the root folder
960 * in the server.
961 */
962 private void startSamlBasedFederatedSingleSignOnAuthorization() {
963 // be gentle with the user
964 mAuthStatusIcon = R.drawable.progress_small;
965 mAuthStatusText = R.string.auth_connecting_auth_server;
966 showAuthStatus();
967 IndeterminateProgressDialog dialog =
968 IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);
969 dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
970
971 /// validate credentials accessing the root folder
972 accessRootFolderRemoteOperation("", "");
973
974 }
975
976 /**
977 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
978 *
979 * Dispatches the operation flow to the right method.
980 */
981 @Override
982 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
983
984 if (operation instanceof GetServerInfoOperation) {
985 if (operation.hashCode() == mWaitingForOpId) {
986 onGetServerInfoFinish(result);
987 } // else nothing ; only the last check operation is considered;
988 // multiple can be started if the user amends a URL quickly
989
990 } else if (operation instanceof OAuth2GetAccessToken) {
991 onGetOAuthAccessTokenFinish(result);
992
993 } else if (operation instanceof ExistenceCheckRemoteOperation) {
994 // TODO : remove this response??
995 //Log_OC.wtf(TAG, "received detection response through callback" );
996 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
997 equals(mAuthTokenType)) {
998 onSamlBasedFederatedSingleSignOnAuthorizationStart(result);
999
1000 } else {
1001 onAuthorizationCheckFinish(result);
1002 }
1003 } else if (operation instanceof GetRemoteUserNameOperation) {
1004 onGetUserNameFinish(result);
1005 }
1006
1007 }
1008
1009 private void onGetUserNameFinish(RemoteOperationResult result) {
1010 mWaitingForOpId = Long.MAX_VALUE;
1011 if (result.isSuccess()) {
1012 boolean success = false;
1013 String username = (String) result.getData().get(0);
1014
1015 if ( mAction == ACTION_CREATE) {
1016 mUsernameInput.setText(username);
1017 success = createAccount();
1018 } else {
1019
1020 if (!mUsernameInput.getText().toString().equals(username)) {
1021 // fail - not a new account, but an existing one; disallow
1022 result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME);
1023 /*
1024 OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(
1025 new OwnCloudAccount(
1026 Uri.parse(mServerInfo.mBaseUrl),
1027 OwnCloudCredentialsFactory.newSamlSsoCredentials(mAuthToken))
1028 );
1029 */
1030 mAuthToken = "";
1031 updateAuthStatusIconAndText(result);
1032 showAuthStatus();
1033 Log_OC.d(TAG, result.getLogMessage());
1034 } else {
1035 updateToken();
1036 success = true;
1037 }
1038 }
1039
1040 if (success)
1041 finish();
1042 } else {
1043 updateStatusIconFailUserName();
1044 showAuthStatus();
1045 Log_OC.e(TAG, "Access to user name failed: " + result.getLogMessage());
1046 }
1047
1048 }
1049
1050 private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result) {
1051 mWaitingForOpId = Long.MAX_VALUE;
1052 dismissDialog(WAIT_DIALOG_TAG);
1053
1054 if (result.isIdPRedirection()) {
1055 String targetUrl = mServerInfo.mBaseUrl
1056 + AccountUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType);
1057
1058 // Show dialog
1059 SamlWebViewDialog dialog = SamlWebViewDialog.newInstance(targetUrl, targetUrl);
1060 dialog.show(getSupportFragmentManager(), SAML_DIALOG_TAG);
1061
1062 mAuthStatusIcon = 0;
1063 mAuthStatusText = 0;
1064
1065 } else {
1066 mAuthStatusIcon = R.drawable.common_error;
1067 mAuthStatusText = R.string.auth_unsupported_auth_method;
1068
1069 }
1070 showAuthStatus();
1071 }
1072
1073
1074 /**
1075 * Processes the result of the server check performed when the user finishes the enter of the
1076 * server URL.
1077 *
1078 * @param result Result of the check.
1079 */
1080 private void onGetServerInfoFinish(RemoteOperationResult result) {
1081 /// update activity state
1082 mServerIsChecked = true;
1083 mWaitingForOpId = Long.MAX_VALUE;
1084
1085 // update server status, but don't show it yet
1086 updateServerStatusIconAndText(result);
1087
1088 if (result.isSuccess()) {
1089 /// SUCCESS means:
1090 // 1. connection succeeded, and we know if it's SSL or not
1091 // 2. server is installed
1092 // 3. we got the server version
1093 // 4. we got the authentication method required by the server
1094 mServerInfo = (GetServerInfoOperation.ServerInfo) (result.getData().get(0));
1095
1096 if (!authSupported(mServerInfo.mAuthMethod)) {
1097
1098 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1099 mServerIsValid = false;
1100
1101 } else {
1102 mServerIsValid = true;
1103 }
1104
1105 } else {
1106 mServerIsValid = false;
1107 }
1108
1109 // refresh UI
1110 showRefreshButton(!mServerIsValid);
1111 showServerStatus();
1112 mOkButton.setEnabled(mServerIsValid);
1113
1114 /// very special case (TODO: move to a common place for all the remote operations)
1115 if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
1116 showUntrustedCertDialog(result);
1117 }
1118 }
1119
1120
1121 private boolean authSupported(AuthenticationMethod authMethod) {
1122 String basic = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());
1123 String oAuth = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());
1124 String saml = AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType());
1125
1126 return (( mAuthTokenType.equals(basic) &&
1127 authMethod.equals(AuthenticationMethod.BASIC_HTTP_AUTH) ) ||
1128 ( mAuthTokenType.equals(oAuth) &&
1129 authMethod.equals(AuthenticationMethod.BEARER_TOKEN)) ||
1130 ( mAuthTokenType.equals(saml) &&
1131 authMethod.equals(AuthenticationMethod.SAML_WEB_SSO))
1132 );
1133 }
1134
1135
1136 // TODO remove, if possible
1137 private String normalizeUrl(String url, boolean sslWhenUnprefixed) {
1138 if (url != null && url.length() > 0) {
1139 url = url.trim();
1140 if (!url.toLowerCase().startsWith("http://") &&
1141 !url.toLowerCase().startsWith("https://")) {
1142 if (sslWhenUnprefixed) {
1143 url = "https://" + url;
1144 } else {
1145 url = "http://" + url;
1146 }
1147 }
1148
1149 url = normalizeUrlSuffix(url);
1150 }
1151 return (url != null ? url : "");
1152 }
1153
1154
1155 private String normalizeUrlSuffix(String url) {
1156 if (url.endsWith("/")) {
1157 url = url.substring(0, url.length() - 1);
1158 }
1159 url = trimUrlWebdav(url);
1160 return url;
1161 }
1162
1163
1164 // TODO remove, if possible
1165 private String trimUrlWebdav(String url){
1166 if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0)){
1167 url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0.length());
1168 } else if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_2_0)){
1169 url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_2_0.length());
1170 } else if (url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_1_2)){
1171 url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_1_2.length());
1172 }
1173 return (url != null ? url : "");
1174 }
1175
1176
1177 /**
1178 * Chooses the right icon and text to show to the user for the received operation result.
1179 *
1180 * @param result Result of a remote operation performed in this activity
1181 */
1182 private void updateServerStatusIconAndText(RemoteOperationResult result) {
1183 mServerStatusIcon = R.drawable.common_error; // the most common case in the switch below
1184
1185 switch (result.getCode()) {
1186 case OK_SSL:
1187 mServerStatusIcon = android.R.drawable.ic_secure;
1188 mServerStatusText = R.string.auth_secure_connection;
1189 break;
1190
1191 case OK_NO_SSL:
1192 case OK:
1193 if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1194 mServerStatusText = R.string.auth_connection_established;
1195 mServerStatusIcon = R.drawable.ic_ok;
1196 } else {
1197 mServerStatusText = R.string.auth_nossl_plain_ok_title;
1198 mServerStatusIcon = android.R.drawable.ic_partial_secure;
1199 }
1200 break;
1201
1202 case NO_NETWORK_CONNECTION:
1203 mServerStatusIcon = R.drawable.no_network;
1204 mServerStatusText = R.string.auth_no_net_conn_title;
1205 break;
1206
1207 case SSL_RECOVERABLE_PEER_UNVERIFIED:
1208 mServerStatusText = R.string.auth_ssl_unverified_server_title;
1209 break;
1210 case BAD_OC_VERSION:
1211 mServerStatusText = R.string.auth_bad_oc_version_title;
1212 break;
1213 case WRONG_CONNECTION:
1214 mServerStatusText = R.string.auth_wrong_connection_title;
1215 break;
1216 case TIMEOUT:
1217 mServerStatusText = R.string.auth_timeout_title;
1218 break;
1219 case INCORRECT_ADDRESS:
1220 mServerStatusText = R.string.auth_incorrect_address_title;
1221 break;
1222 case SSL_ERROR:
1223 mServerStatusText = R.string.auth_ssl_general_error_title;
1224 break;
1225 case UNAUTHORIZED:
1226 mServerStatusText = R.string.auth_unauthorized;
1227 break;
1228 case HOST_NOT_AVAILABLE:
1229 mServerStatusText = R.string.auth_unknown_host_title;
1230 break;
1231 case INSTANCE_NOT_CONFIGURED:
1232 mServerStatusText = R.string.auth_not_configured_title;
1233 break;
1234 case FILE_NOT_FOUND:
1235 mServerStatusText = R.string.auth_incorrect_path_title;
1236 break;
1237 case OAUTH2_ERROR:
1238 mServerStatusText = R.string.auth_oauth_error;
1239 break;
1240 case OAUTH2_ERROR_ACCESS_DENIED:
1241 mServerStatusText = R.string.auth_oauth_error_access_denied;
1242 break;
1243 case UNHANDLED_HTTP_CODE:
1244 case UNKNOWN_ERROR:
1245 mServerStatusText = R.string.auth_unknown_error_title;
1246 break;
1247 case OK_REDIRECT_TO_NON_SECURE_CONNECTION:
1248 mServerStatusIcon = android.R.drawable.ic_partial_secure;
1249 mServerStatusText = R.string.auth_redirect_non_secure_connection_title;
1250 break;
1251 default:
1252 mServerStatusText = 0;
1253 mServerStatusIcon = 0;
1254 }
1255 }
1256
1257
1258 /**
1259 * Chooses the right icon and text to show to the user for the received operation result.
1260 *
1261 * @param result Result of a remote operation performed in this activity
1262 */
1263 private void updateAuthStatusIconAndText(RemoteOperationResult result) {
1264 mAuthStatusIcon = R.drawable.common_error; // the most common case in the switch below
1265
1266 switch (result.getCode()) {
1267 case OK_SSL:
1268 mAuthStatusIcon = android.R.drawable.ic_secure;
1269 mAuthStatusText = R.string.auth_secure_connection;
1270 break;
1271
1272 case OK_NO_SSL:
1273 case OK:
1274 if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1275 mAuthStatusText = R.string.auth_connection_established;
1276 mAuthStatusIcon = R.drawable.ic_ok;
1277 } else {
1278 mAuthStatusText = R.string.auth_nossl_plain_ok_title;
1279 mAuthStatusIcon = android.R.drawable.ic_partial_secure;
1280 }
1281 break;
1282
1283 case NO_NETWORK_CONNECTION:
1284 mAuthStatusIcon = R.drawable.no_network;
1285 mAuthStatusText = R.string.auth_no_net_conn_title;
1286 break;
1287
1288 case SSL_RECOVERABLE_PEER_UNVERIFIED:
1289 mAuthStatusText = R.string.auth_ssl_unverified_server_title;
1290 break;
1291 case BAD_OC_VERSION:
1292 mAuthStatusText = R.string.auth_bad_oc_version_title;
1293 break;
1294 case WRONG_CONNECTION:
1295 mAuthStatusText = R.string.auth_wrong_connection_title;
1296 break;
1297 case TIMEOUT:
1298 mAuthStatusText = R.string.auth_timeout_title;
1299 break;
1300 case INCORRECT_ADDRESS:
1301 mAuthStatusText = R.string.auth_incorrect_address_title;
1302 break;
1303 case SSL_ERROR:
1304 mAuthStatusText = R.string.auth_ssl_general_error_title;
1305 break;
1306 case UNAUTHORIZED:
1307 mAuthStatusText = R.string.auth_unauthorized;
1308 break;
1309 case HOST_NOT_AVAILABLE:
1310 mAuthStatusText = R.string.auth_unknown_host_title;
1311 break;
1312 case INSTANCE_NOT_CONFIGURED:
1313 mAuthStatusText = R.string.auth_not_configured_title;
1314 break;
1315 case FILE_NOT_FOUND:
1316 mAuthStatusText = R.string.auth_incorrect_path_title;
1317 break;
1318 case OAUTH2_ERROR:
1319 mAuthStatusText = R.string.auth_oauth_error;
1320 break;
1321 case OAUTH2_ERROR_ACCESS_DENIED:
1322 mAuthStatusText = R.string.auth_oauth_error_access_denied;
1323 break;
1324 case ACCOUNT_NOT_NEW:
1325 mAuthStatusText = R.string.auth_account_not_new;
1326 break;
1327 case ACCOUNT_NOT_THE_SAME:
1328 mAuthStatusText = R.string.auth_account_not_the_same;
1329 break;
1330 case UNHANDLED_HTTP_CODE:
1331 case UNKNOWN_ERROR:
1332 mAuthStatusText = R.string.auth_unknown_error_title;
1333 break;
1334 default:
1335 mAuthStatusText = 0;
1336 mAuthStatusIcon = 0;
1337 }
1338 }
1339
1340
1341 private void updateStatusIconFailUserName(){
1342 mAuthStatusIcon = R.drawable.common_error;
1343 mAuthStatusText = R.string.auth_fail_get_user_name;
1344 }
1345
1346 private void updateServerStatusIconNoRegularAuth(){
1347 mServerStatusIcon = R.drawable.common_error;
1348 mServerStatusText = R.string.auth_can_not_auth_against_server;
1349 }
1350
1351 /**
1352 * Processes the result of the request for and access token send
1353 * to an OAuth authorization server.
1354 *
1355 * @param result Result of the operation.
1356 */
1357 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result) {
1358 mWaitingForOpId = Long.MAX_VALUE;
1359 dismissDialog(WAIT_DIALOG_TAG);
1360
1361 if (result.isSuccess()) {
1362 /// be gentle with the user
1363 IndeterminateProgressDialog dialog =
1364 IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);
1365 dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
1366
1367 /// time to test the retrieved access token on the ownCloud server
1368 @SuppressWarnings("unchecked")
1369 Map<String, String> tokens = (Map<String, String>)(result.getData().get(0));
1370 mAuthToken = tokens.get(OAuth2Constants.KEY_ACCESS_TOKEN);
1371 Log_OC.d(TAG, "Got ACCESS TOKEN: " + mAuthToken);
1372
1373 accessRootFolderRemoteOperation("", "");
1374
1375 } else {
1376 updateAuthStatusIconAndText(result);
1377 showAuthStatus();
1378 Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
1379 }
1380 }
1381
1382
1383 /**
1384 * Processes the result of the access check performed to try the user credentials.
1385 *
1386 * Creates a new account through the AccountManager.
1387 *
1388 * @param result Result of the operation.
1389 */
1390 private void onAuthorizationCheckFinish(RemoteOperationResult result) {
1391 mWaitingForOpId = Long.MAX_VALUE;
1392 dismissDialog(WAIT_DIALOG_TAG);
1393
1394 if (result.isSuccess()) {
1395 Log_OC.d(TAG, "Successful access - time to save the account");
1396
1397 boolean success = false;
1398 if (mAction == ACTION_CREATE) {
1399 success = createAccount();
1400
1401 } else {
1402 updateToken();
1403 success = true;
1404 }
1405
1406 if (success) {
1407 finish();
1408 }
1409
1410 } else if (result.isServerFail() || result.isException()) {
1411 /// server errors or exceptions in authorization take to requiring a new check of
1412 /// the server
1413 mServerIsChecked = true;
1414 mServerIsValid = false;
1415 mServerInfo = new GetServerInfoOperation.ServerInfo();
1416
1417 // update status icon and text
1418 updateServerStatusIconAndText(result);
1419 showServerStatus();
1420 mAuthStatusIcon = 0;
1421 mAuthStatusText = 0;
1422 showAuthStatus();
1423
1424 // update input controls state
1425 showRefreshButton(true);
1426 mOkButton.setEnabled(false);
1427
1428 // very special case (TODO: move to a common place for all the remote operations)
1429 if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
1430 showUntrustedCertDialog(result);
1431 }
1432
1433 } else { // authorization fail due to client side - probably wrong credentials
1434 updateAuthStatusIconAndText(result);
1435 showAuthStatus();
1436 Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
1437 }
1438 }
1439
1440
1441
1442
1443 /**
1444 * Sets the proper response to get that the Account Authenticator that started this activity
1445 * saves a new authorization token for mAccount.
1446 */
1447 private void updateToken() {
1448 Bundle response = new Bundle();
1449 response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
1450 response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);
1451
1452 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).
1453 equals(mAuthTokenType)) {
1454 response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
1455 // the next line is necessary, notifications are calling directly to the
1456 // AuthenticatorActivity to update, without AccountManager intervention
1457 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1458
1459 } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
1460 equals(mAuthTokenType)) {
1461
1462 response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
1463 // the next line is necessary; by now, notifications are calling directly to the
1464 // AuthenticatorActivity to update, without AccountManager intervention
1465 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1466
1467 } else {
1468 response.putString(AccountManager.KEY_AUTHTOKEN, mPasswordInput.getText().toString());
1469 mAccountMgr.setPassword(mAccount, mPasswordInput.getText().toString());
1470 }
1471 setAccountAuthenticatorResult(response);
1472
1473 }
1474
1475
1476 /**
1477 * Creates a new account through the Account Authenticator that started this activity.
1478 *
1479 * This makes the account permanent.
1480 *
1481 * TODO Decide how to name the OAuth accounts
1482 */
1483 private boolean createAccount() {
1484 /// create and save new ownCloud account
1485 boolean isOAuth = AccountTypeUtils.
1486 getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType);
1487 boolean isSaml = AccountTypeUtils.
1488 getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType);
1489
1490 Uri uri = Uri.parse(mServerInfo.mBaseUrl);
1491 String username = mUsernameInput.getText().toString().trim();
1492 if (isOAuth) {
1493 username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();
1494 }
1495 String accountName = com.owncloud.android.lib.common.accounts.AccountUtils.
1496 buildAccountName(uri, username);
1497 Account newAccount = new Account(accountName, MainApp.getAccountType());
1498 if (AccountUtils.exists(newAccount, getApplicationContext())) {
1499 // fail - not a new account, but an existing one; disallow
1500 RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW);
1501 updateAuthStatusIconAndText(result);
1502 showAuthStatus();
1503 Log_OC.d(TAG, result.getLogMessage());
1504 return false;
1505
1506 } else {
1507 mAccount = newAccount;
1508
1509 if (isOAuth || isSaml) {
1510 // with external authorizations, the password is never input in the app
1511 mAccountMgr.addAccountExplicitly(mAccount, "", null);
1512 } else {
1513 mAccountMgr.addAccountExplicitly(
1514 mAccount, mPasswordInput.getText().toString(), null
1515 );
1516 }
1517
1518 /// add the new account as default in preferences, if there is none already
1519 Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
1520 if (defaultAccount == null) {
1521 SharedPreferences.Editor editor = PreferenceManager
1522 .getDefaultSharedPreferences(this).edit();
1523 editor.putString("select_oc_account", accountName);
1524 editor.commit();
1525 }
1526
1527 /// prepare result to return to the Authenticator
1528 // TODO check again what the Authenticator makes with it; probably has the same
1529 // effect as addAccountExplicitly, but it's not well done
1530 final Intent intent = new Intent();
1531 intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, MainApp.getAccountType());
1532 intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
1533 /*if (!isOAuth)
1534 intent.putExtra(AccountManager.KEY_AUTHTOKEN, MainApp.getAccountType()); */
1535 intent.putExtra(AccountManager.KEY_USERDATA, username);
1536 if (isOAuth || isSaml) {
1537 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1538 }
1539 /// add user data to the new account; TODO probably can be done in the last parameter
1540 // addAccountExplicitly, or in KEY_USERDATA
1541 mAccountMgr.setUserData(
1542 mAccount, Constants.KEY_OC_VERSION, mServerInfo.mVersion.getVersion()
1543 );
1544 mAccountMgr.setUserData(
1545 mAccount, Constants.KEY_OC_BASE_URL, mServerInfo.mBaseUrl
1546 );
1547
1548 if (isSaml) {
1549 mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE");
1550 } else if (isOAuth) {
1551 mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_OAUTH2, "TRUE");
1552 }
1553
1554 setAccountAuthenticatorResult(intent.getExtras());
1555 setResult(RESULT_OK, intent);
1556
1557 return true;
1558 }
1559 }
1560
1561
1562 /**
1563 * Starts and activity to open the 'new account' page in the ownCloud web site
1564 *
1565 * @param view 'Account register' button
1566 */
1567 public void onRegisterClick(View view) {
1568 Intent register = new Intent(
1569 Intent.ACTION_VIEW, Uri.parse(getString(R.string.welcome_link_url))
1570 );
1571 setResult(RESULT_CANCELED);
1572 startActivity(register);
1573 }
1574
1575
1576 /**
1577 * Updates the content and visibility state of the icon and text associated
1578 * to the last check on the ownCloud server.
1579 */
1580 private void showServerStatus() {
1581 if (mServerStatusIcon == 0 && mServerStatusText == 0) {
1582 mServerStatusView.setVisibility(View.INVISIBLE);
1583
1584 } else {
1585 mServerStatusView.setText(mServerStatusText);
1586 mServerStatusView.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon, 0, 0, 0);
1587 mServerStatusView.setVisibility(View.VISIBLE);
1588 }
1589
1590 }
1591
1592
1593 /**
1594 * Updates the content and visibility state of the icon and text associated
1595 * to the interactions with the OAuth authorization server.
1596 */
1597 private void showAuthStatus() {
1598 if (mAuthStatusIcon == 0 && mAuthStatusText == 0) {
1599 mAuthStatusView.setVisibility(View.INVISIBLE);
1600
1601 } else {
1602 mAuthStatusView.setText(mAuthStatusText);
1603 mAuthStatusView.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon, 0, 0, 0);
1604 mAuthStatusView.setVisibility(View.VISIBLE);
1605 }
1606 }
1607
1608
1609 private void showRefreshButton (boolean show) {
1610 if (show) {
1611 mRefreshButton.setVisibility(View.VISIBLE);
1612 } else {
1613 mRefreshButton.setVisibility(View.GONE);
1614 }
1615 }
1616
1617 /**
1618 * Called when the refresh button in the input field for ownCloud host is clicked.
1619 *
1620 * Performs a new check on the URL in the input field.
1621 *
1622 * @param view Refresh 'button'
1623 */
1624 public void onRefreshClick(View view) {
1625 checkOcServer();
1626 }
1627
1628
1629 /**
1630 * Called when the eye icon in the password field is clicked.
1631 *
1632 * Toggles the visibility of the password in the field.
1633 */
1634 public void onViewPasswordClick() {
1635 int selectionStart = mPasswordInput.getSelectionStart();
1636 int selectionEnd = mPasswordInput.getSelectionEnd();
1637 if (isPasswordVisible()) {
1638 hidePassword();
1639 } else {
1640 showPassword();
1641 }
1642 mPasswordInput.setSelection(selectionStart, selectionEnd);
1643 }
1644
1645
1646 /**
1647 * Called when the checkbox for OAuth authorization is clicked.
1648 *
1649 * Hides or shows the input fields for user & password.
1650 *
1651 * @param view 'View password' 'button'
1652 */
1653 public void onCheckClick(View view) {
1654 CheckBox oAuth2Check = (CheckBox)view;
1655 if (oAuth2Check.isChecked()) {
1656 mAuthTokenType = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());
1657 } else {
1658 mAuthTokenType = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());
1659 }
1660 updateAuthenticationPreFragmentVisibility();
1661 }
1662
1663
1664 /**
1665 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1666 *
1667 * Used to trigger the authentication check when the user presses 'enter' after writing the
1668 * password, or to throw the server test when the only field on screen is the URL input field.
1669 */
1670 @Override
1671 public boolean onEditorAction(TextView inputField, int actionId, KeyEvent event) {
1672 if (actionId == EditorInfo.IME_ACTION_DONE && inputField != null &&
1673 inputField.equals(mPasswordInput)) {
1674 if (mOkButton.isEnabled()) {
1675 mOkButton.performClick();
1676 }
1677
1678 } else if (actionId == EditorInfo.IME_ACTION_NEXT && inputField != null &&
1679 inputField.equals(mHostUrlInput)) {
1680 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
1681 equals(mAuthTokenType)) {
1682 checkOcServer();
1683 }
1684 }
1685 return false; // always return false to grant that the software keyboard is hidden anyway
1686 }
1687
1688
1689 private abstract static class RightDrawableOnTouchListener implements OnTouchListener {
1690
1691 private int fuzz = 75;
1692
1693 /**
1694 * {@inheritDoc}
1695 */
1696 @Override
1697 public boolean onTouch(View view, MotionEvent event) {
1698 Drawable rightDrawable = null;
1699 if (view instanceof TextView) {
1700 Drawable[] drawables = ((TextView)view).getCompoundDrawables();
1701 if (drawables.length > 2) {
1702 rightDrawable = drawables[2];
1703 }
1704 }
1705 if (rightDrawable != null) {
1706 final int x = (int) event.getX();
1707 final int y = (int) event.getY();
1708 final Rect bounds = rightDrawable.getBounds();
1709 if ( x >= (view.getRight() - bounds.width() - fuzz) &&
1710 x <= (view.getRight() - view.getPaddingRight() + fuzz) &&
1711 y >= (view.getPaddingTop() - fuzz) &&
1712 y <= (view.getHeight() - view.getPaddingBottom()) + fuzz) {
1713
1714 return onDrawableTouch(event);
1715 }
1716 }
1717 return false;
1718 }
1719
1720 public abstract boolean onDrawableTouch(final MotionEvent event);
1721 }
1722
1723
1724 private void getRemoteUserNameOperation(String sessionCookie, boolean followRedirects) {
1725
1726 Intent getUserNameIntent = new Intent();
1727 getUserNameIntent.setAction(OperationsService.ACTION_GET_USER_NAME);
1728 getUserNameIntent.putExtra(OperationsService.EXTRA_SERVER_URL, mServerInfo.mBaseUrl);
1729 getUserNameIntent.putExtra(OperationsService.EXTRA_COOKIE, sessionCookie);
1730
1731 if (mOperationsServiceBinder != null) {
1732 //Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." );
1733 mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getUserNameIntent);
1734 }
1735 }
1736
1737
1738 @Override
1739 public void onSsoFinished(String sessionCookie) {
1740 if (sessionCookie != null && sessionCookie.length() > 0) {
1741 Log_OC.d(TAG, "Successful SSO - time to save the account");
1742 mAuthToken = sessionCookie;
1743 getRemoteUserNameOperation(sessionCookie, true);
1744 Fragment fd = getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG);
1745 if (fd != null && fd instanceof SherlockDialogFragment) {
1746 Dialog d = ((SherlockDialogFragment)fd).getDialog();
1747 if (d != null && d.isShowing()) {
1748 d.dismiss();
1749 }
1750 }
1751
1752 } else {
1753 // TODO - show fail
1754 Log_OC.d(TAG, "SSO failed");
1755 }
1756
1757 }
1758
1759 @Override
1760 public boolean onTouchEvent(MotionEvent event) {
1761 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
1762 equals(mAuthTokenType) &&
1763 mHostUrlInput.hasFocus() && event.getAction() == MotionEvent.ACTION_DOWN) {
1764 checkOcServer();
1765 }
1766 return super.onTouchEvent(event);
1767 }
1768
1769
1770 /**
1771 * Show untrusted cert dialog
1772 */
1773 public void showUntrustedCertDialog(
1774 X509Certificate x509Certificate, SslError error, SslErrorHandler handler
1775 ) {
1776 // Show a dialog with the certificate info
1777 SslUntrustedCertDialog dialog = null;
1778 if (x509Certificate == null) {
1779 dialog = SslUntrustedCertDialog.newInstanceForEmptySslError(error, handler);
1780 } else {
1781 dialog = SslUntrustedCertDialog.
1782 newInstanceForFullSslError(x509Certificate, error, handler);
1783 }
1784 FragmentManager fm = getSupportFragmentManager();
1785 FragmentTransaction ft = fm.beginTransaction();
1786 ft.addToBackStack(null);
1787 dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);
1788 }
1789
1790
1791 /**
1792 * Show untrusted cert dialog
1793 */
1794 private void showUntrustedCertDialog(RemoteOperationResult result) {
1795 // Show a dialog with the certificate info
1796 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.
1797 newInstanceForFullSslError((CertificateCombinedException)result.getException());
1798 FragmentManager fm = getSupportFragmentManager();
1799 FragmentTransaction ft = fm.beginTransaction();
1800 ft.addToBackStack(null);
1801 dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);
1802
1803 }
1804
1805 /**
1806 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1807 */
1808 public void onSavedCertificate() {
1809 Fragment fd = getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG);
1810 if (fd == null) {
1811 // if SAML dialog is not shown,
1812 // the SslDialog was shown due to an SSL error in the server check
1813 checkOcServer();
1814 }
1815 }
1816
1817 /**
1818 * Called from SslValidatorDialog when a new server certificate could not be saved
1819 * when the user requested it.
1820 */
1821 @Override
1822 public void onFailedSavingCertificate() {
1823 dismissDialog(SAML_DIALOG_TAG);
1824 Toast.makeText(this, R.string.ssl_validator_not_saved, Toast.LENGTH_LONG).show();
1825 }
1826
1827 @Override
1828 public void onCancelCertificate() {
1829 dismissDialog(SAML_DIALOG_TAG);
1830 }
1831
1832
1833 private void doOnResumeAndBound() {
1834 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1835 mOperationsServiceBinder.addOperationListener(AuthenticatorActivity.this, mHandler);
1836 if (mWaitingForOpId <= Integer.MAX_VALUE) {
1837 mOperationsServiceBinder.dispatchResultIfFinished((int)mWaitingForOpId, this);
1838 }
1839
1840 if (mPendingAutoCheck) {
1841 checkOcServer();
1842 }
1843 }
1844
1845
1846 private void dismissDialog(String dialogTag){
1847 Fragment frag = getSupportFragmentManager().findFragmentByTag(dialogTag);
1848 if (frag != null && frag instanceof SherlockDialogFragment) {
1849 SherlockDialogFragment dialog = (SherlockDialogFragment) frag;
1850 dialog.dismiss();
1851 }
1852 }
1853
1854
1855 /**
1856 * Implements callback methods for service binding.
1857 */
1858 private class OperationsServiceConnection implements ServiceConnection {
1859
1860 @Override
1861 public void onServiceConnected(ComponentName component, IBinder service) {
1862 if (component.equals(
1863 new ComponentName(AuthenticatorActivity.this, OperationsService.class)
1864 )) {
1865 //Log_OC.wtf(TAG, "Operations service connected");
1866 mOperationsServiceBinder = (OperationsServiceBinder) service;
1867
1868 doOnResumeAndBound();
1869
1870 } else {
1871 return;
1872 }
1873
1874 }
1875
1876 @Override
1877 public void onServiceDisconnected(ComponentName component) {
1878 if (component.equals(
1879 new ComponentName(AuthenticatorActivity.this, OperationsService.class)
1880 )) {
1881 Log_OC.e(TAG, "Operations service crashed");
1882 mOperationsServiceBinder = null;
1883 }
1884 }
1885
1886 }
1887
1888 /**
1889 * Create and show dialog for request authentication to the user
1890 * @param webView
1891 * @param handler
1892 */
1893 public void createAuthenticationDialog(WebView webView, HttpAuthHandler handler) {
1894
1895 // Show a dialog with the certificate info
1896 CredentialsDialogFragment dialog =
1897 CredentialsDialogFragment.newInstanceForCredentials(webView, handler);
1898 FragmentManager fm = getSupportFragmentManager();
1899 FragmentTransaction ft = fm.beginTransaction();
1900 ft.addToBackStack(null);
1901 dialog.setCancelable(false);
1902 dialog.show(ft, CREDENTIALS_DIALOG_TAG);
1903
1904 if (!mIsFirstAuthAttempt) {
1905 Toast.makeText(
1906 getApplicationContext(),
1907 getText(R.string.saml_authentication_wrong_pass),
1908 Toast.LENGTH_LONG
1909 ).show();
1910 } else {
1911 mIsFirstAuthAttempt = false;
1912 }
1913 }
1914
1915 /**
1916 * For retrieving the clicking on authentication cancel button
1917 */
1918 public void doNegativeAuthenticatioDialogClick(){
1919 mIsFirstAuthAttempt = true;
1920 }
1921
1922
1923 @Override
1924 public void onAuthenticatorTaskCallback(RemoteOperationResult result) {
1925 //Log_OC.wtf(TAG, "received detection response through callback" );
1926 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
1927 equals(mAuthTokenType)) {
1928 onSamlBasedFederatedSingleSignOnAuthorizationStart(result);
1929
1930 } else {
1931 onAuthorizationCheckFinish(result);
1932 }
1933 }
1934 }