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