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