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