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