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