Merge branch 'develop' into download_folder
[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 url = result.getRedirectedLocation();
1024 String targetUrl = mServerInfo.mBaseUrl
1025 + AccountUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType);
1026
1027 // Show dialog
1028 SamlWebViewDialog dialog = SamlWebViewDialog.newInstance(url, targetUrl);
1029 dialog.show(getSupportFragmentManager(), SAML_DIALOG_TAG);
1030
1031 mAuthStatusIcon = 0;
1032 mAuthStatusText = 0;
1033
1034 } else {
1035 mAuthStatusIcon = R.drawable.common_error;
1036 mAuthStatusText = R.string.auth_unsupported_auth_method;
1037
1038 }
1039 showAuthStatus();
1040 }
1041
1042
1043 /**
1044 * Processes the result of the server check performed when the user finishes the enter of the
1045 * server URL.
1046 *
1047 * @param operation Server check performed.
1048 * @param result Result of the check.
1049 */
1050 private void onGetServerInfoFinish(RemoteOperationResult result) {
1051 /// update activity state
1052 mServerIsChecked = true;
1053 mWaitingForOpId = Long.MAX_VALUE;
1054
1055 // update server status, but don't show it yet
1056 updateServerStatusIconAndText(result);
1057
1058 if (result.isSuccess()) {
1059 /// SUCCESS means:
1060 // 1. connection succeeded, and we know if it's SSL or not
1061 // 2. server is installed
1062 // 3. we got the server version
1063 // 4. we got the authentication method required by the server
1064 mServerInfo = (GetServerInfoOperation.ServerInfo) (result.getData().get(0));
1065
1066 if (!authSupported(mServerInfo.mAuthMethod)) {
1067
1068 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1069 mServerIsValid = false;
1070
1071 } else {
1072 mServerIsValid = true;
1073 }
1074
1075 } else {
1076 mServerIsValid = false;
1077 }
1078
1079 // refresh UI
1080 showRefreshButton(!mServerIsValid);
1081 showServerStatus();
1082 mOkButton.setEnabled(mServerIsValid);
1083
1084 /// very special case (TODO: move to a common place for all the remote operations)
1085 if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
1086 showUntrustedCertDialog(result);
1087 }
1088 }
1089
1090
1091 private boolean authSupported(AuthenticationMethod authMethod) {
1092 String basic = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());
1093 String oAuth = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());
1094 String saml = AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType());
1095
1096 return (( mAuthTokenType.equals(basic) &&
1097 authMethod.equals(AuthenticationMethod.BASIC_HTTP_AUTH) ) ||
1098 ( mAuthTokenType.equals(oAuth) &&
1099 authMethod.equals(AuthenticationMethod.BEARER_TOKEN)) ||
1100 ( mAuthTokenType.equals(saml) &&
1101 authMethod.equals(AuthenticationMethod.SAML_WEB_SSO))
1102 );
1103 }
1104
1105
1106 // TODO remove, if possible
1107 private String normalizeUrl(String url, boolean sslWhenUnprefixed) {
1108 if (url != null && url.length() > 0) {
1109 url = url.trim();
1110 if (!url.toLowerCase().startsWith("http://") &&
1111 !url.toLowerCase().startsWith("https://")) {
1112 if (sslWhenUnprefixed) {
1113 url = "https://" + url;
1114 } else {
1115 url = "http://" + url;
1116 }
1117 }
1118
1119 url = normalizeUrlSuffix(url);
1120 }
1121 return (url != null ? url : "");
1122 }
1123
1124
1125 private String normalizeUrlSuffix(String url) {
1126 if (url.endsWith("/")) {
1127 url = url.substring(0, url.length() - 1);
1128 }
1129 url = trimUrlWebdav(url);
1130 return url;
1131 }
1132
1133
1134 // TODO remove, if possible
1135 private String trimUrlWebdav(String url){
1136 if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0)){
1137 url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0.length());
1138 } else if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_2_0)){
1139 url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_2_0.length());
1140 } else if (url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_1_2)){
1141 url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_1_2.length());
1142 }
1143 return (url != null ? url : "");
1144 }
1145
1146
1147 /**
1148 * Chooses the right icon and text to show to the user for the received operation result.
1149 *
1150 * @param result Result of a remote operation performed in this activity
1151 */
1152 private void updateServerStatusIconAndText(RemoteOperationResult result) {
1153 mServerStatusIcon = R.drawable.common_error; // the most common case in the switch below
1154
1155 switch (result.getCode()) {
1156 case OK_SSL:
1157 mServerStatusIcon = android.R.drawable.ic_secure;
1158 mServerStatusText = R.string.auth_secure_connection;
1159 break;
1160
1161 case OK_NO_SSL:
1162 case OK:
1163 if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1164 mServerStatusText = R.string.auth_connection_established;
1165 mServerStatusIcon = R.drawable.ic_ok;
1166 } else {
1167 mServerStatusText = R.string.auth_nossl_plain_ok_title;
1168 mServerStatusIcon = android.R.drawable.ic_partial_secure;
1169 }
1170 break;
1171
1172 case NO_NETWORK_CONNECTION:
1173 mServerStatusIcon = R.drawable.no_network;
1174 mServerStatusText = R.string.auth_no_net_conn_title;
1175 break;
1176
1177 case SSL_RECOVERABLE_PEER_UNVERIFIED:
1178 mServerStatusText = R.string.auth_ssl_unverified_server_title;
1179 break;
1180 case BAD_OC_VERSION:
1181 mServerStatusText = R.string.auth_bad_oc_version_title;
1182 break;
1183 case WRONG_CONNECTION:
1184 mServerStatusText = R.string.auth_wrong_connection_title;
1185 break;
1186 case TIMEOUT:
1187 mServerStatusText = R.string.auth_timeout_title;
1188 break;
1189 case INCORRECT_ADDRESS:
1190 mServerStatusText = R.string.auth_incorrect_address_title;
1191 break;
1192 case SSL_ERROR:
1193 mServerStatusText = R.string.auth_ssl_general_error_title;
1194 break;
1195 case UNAUTHORIZED:
1196 mServerStatusText = R.string.auth_unauthorized;
1197 break;
1198 case HOST_NOT_AVAILABLE:
1199 mServerStatusText = R.string.auth_unknown_host_title;
1200 break;
1201 case INSTANCE_NOT_CONFIGURED:
1202 mServerStatusText = R.string.auth_not_configured_title;
1203 break;
1204 case FILE_NOT_FOUND:
1205 mServerStatusText = R.string.auth_incorrect_path_title;
1206 break;
1207 case OAUTH2_ERROR:
1208 mServerStatusText = R.string.auth_oauth_error;
1209 break;
1210 case OAUTH2_ERROR_ACCESS_DENIED:
1211 mServerStatusText = R.string.auth_oauth_error_access_denied;
1212 break;
1213 case UNHANDLED_HTTP_CODE:
1214 case UNKNOWN_ERROR:
1215 mServerStatusText = R.string.auth_unknown_error_title;
1216 break;
1217 case OK_REDIRECT_TO_NON_SECURE_CONNECTION:
1218 mServerStatusIcon = android.R.drawable.ic_partial_secure;
1219 mServerStatusText = R.string.auth_redirect_non_secure_connection_title;
1220 break;
1221 default:
1222 mServerStatusText = 0;
1223 mServerStatusIcon = 0;
1224 }
1225 }
1226
1227
1228 /**
1229 * Chooses the right icon and text to show to the user for the received operation result.
1230 *
1231 * @param result Result of a remote operation performed in this activity
1232 */
1233 private void updateAuthStatusIconAndText(RemoteOperationResult result) {
1234 mAuthStatusIcon = R.drawable.common_error; // the most common case in the switch below
1235
1236 switch (result.getCode()) {
1237 case OK_SSL:
1238 mAuthStatusIcon = android.R.drawable.ic_secure;
1239 mAuthStatusText = R.string.auth_secure_connection;
1240 break;
1241
1242 case OK_NO_SSL:
1243 case OK:
1244 if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1245 mAuthStatusText = R.string.auth_connection_established;
1246 mAuthStatusIcon = R.drawable.ic_ok;
1247 } else {
1248 mAuthStatusText = R.string.auth_nossl_plain_ok_title;
1249 mAuthStatusIcon = android.R.drawable.ic_partial_secure;
1250 }
1251 break;
1252
1253 case NO_NETWORK_CONNECTION:
1254 mAuthStatusIcon = R.drawable.no_network;
1255 mAuthStatusText = R.string.auth_no_net_conn_title;
1256 break;
1257
1258 case SSL_RECOVERABLE_PEER_UNVERIFIED:
1259 mAuthStatusText = R.string.auth_ssl_unverified_server_title;
1260 break;
1261 case BAD_OC_VERSION:
1262 mAuthStatusText = R.string.auth_bad_oc_version_title;
1263 break;
1264 case WRONG_CONNECTION:
1265 mAuthStatusText = R.string.auth_wrong_connection_title;
1266 break;
1267 case TIMEOUT:
1268 mAuthStatusText = R.string.auth_timeout_title;
1269 break;
1270 case INCORRECT_ADDRESS:
1271 mAuthStatusText = R.string.auth_incorrect_address_title;
1272 break;
1273 case SSL_ERROR:
1274 mAuthStatusText = R.string.auth_ssl_general_error_title;
1275 break;
1276 case UNAUTHORIZED:
1277 mAuthStatusText = R.string.auth_unauthorized;
1278 break;
1279 case HOST_NOT_AVAILABLE:
1280 mAuthStatusText = R.string.auth_unknown_host_title;
1281 break;
1282 case INSTANCE_NOT_CONFIGURED:
1283 mAuthStatusText = R.string.auth_not_configured_title;
1284 break;
1285 case FILE_NOT_FOUND:
1286 mAuthStatusText = R.string.auth_incorrect_path_title;
1287 break;
1288 case OAUTH2_ERROR:
1289 mAuthStatusText = R.string.auth_oauth_error;
1290 break;
1291 case OAUTH2_ERROR_ACCESS_DENIED:
1292 mAuthStatusText = R.string.auth_oauth_error_access_denied;
1293 break;
1294 case ACCOUNT_NOT_NEW:
1295 mAuthStatusText = R.string.auth_account_not_new;
1296 break;
1297 case ACCOUNT_NOT_THE_SAME:
1298 mAuthStatusText = R.string.auth_account_not_the_same;
1299 break;
1300 case UNHANDLED_HTTP_CODE:
1301 case UNKNOWN_ERROR:
1302 mAuthStatusText = R.string.auth_unknown_error_title;
1303 break;
1304 default:
1305 mAuthStatusText = 0;
1306 mAuthStatusIcon = 0;
1307 }
1308 }
1309
1310
1311 private void updateStatusIconFailUserName(){
1312 mAuthStatusIcon = R.drawable.common_error;
1313 mAuthStatusText = R.string.auth_fail_get_user_name;
1314 }
1315
1316 private void updateServerStatusIconNoRegularAuth(){
1317 mServerStatusIcon = R.drawable.common_error;
1318 mServerStatusText = R.string.auth_can_not_auth_against_server;
1319 }
1320
1321 /**
1322 * Processes the result of the request for and access token send
1323 * to an OAuth authorization server.
1324 *
1325 * @param result Result of the operation.
1326 */
1327 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result) {
1328 mWaitingForOpId = Long.MAX_VALUE;
1329 dismissDialog(WAIT_DIALOG_TAG);
1330
1331 if (result.isSuccess()) {
1332 /// be gentle with the user
1333 IndeterminateProgressDialog dialog =
1334 IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);
1335 dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
1336
1337 /// time to test the retrieved access token on the ownCloud server
1338 @SuppressWarnings("unchecked")
1339 Map<String, String> tokens = (Map<String, String>)(result.getData().get(0));
1340 mAuthToken = tokens.get(OAuth2Constants.KEY_ACCESS_TOKEN);
1341 Log_OC.d(TAG, "Got ACCESS TOKEN: " + mAuthToken);
1342
1343 accessRootFolderRemoteOperation("", "");
1344
1345 } else {
1346 updateAuthStatusIconAndText(result);
1347 showAuthStatus();
1348 Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
1349 }
1350 }
1351
1352
1353 /**
1354 * Processes the result of the access check performed to try the user credentials.
1355 *
1356 * Creates a new account through the AccountManager.
1357 *
1358 * @param operation Access check performed.
1359 * @param result Result of the operation.
1360 */
1361 private void onAuthorizationCheckFinish(RemoteOperationResult result) {
1362 mWaitingForOpId = Long.MAX_VALUE;
1363 dismissDialog(WAIT_DIALOG_TAG);
1364
1365 if (result.isSuccess()) {
1366 Log_OC.d(TAG, "Successful access - time to save the account");
1367
1368 boolean success = false;
1369 if (mAction == ACTION_CREATE) {
1370 success = createAccount();
1371
1372 } else {
1373 updateToken();
1374 success = true;
1375 }
1376
1377 if (success) {
1378 finish();
1379 }
1380
1381 } else if (result.isServerFail() || result.isException()) {
1382 /// server errors or exceptions in authorization take to requiring a new check of
1383 /// the server
1384 mServerIsChecked = true;
1385 mServerIsValid = false;
1386 mServerInfo = new GetServerInfoOperation.ServerInfo();
1387
1388 // update status icon and text
1389 updateServerStatusIconAndText(result);
1390 showServerStatus();
1391 mAuthStatusIcon = 0;
1392 mAuthStatusText = 0;
1393 showAuthStatus();
1394
1395 // update input controls state
1396 showRefreshButton(true);
1397 mOkButton.setEnabled(false);
1398
1399 // very special case (TODO: move to a common place for all the remote operations)
1400 if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
1401 showUntrustedCertDialog(result);
1402 }
1403
1404 } else { // authorization fail due to client side - probably wrong credentials
1405 updateAuthStatusIconAndText(result);
1406 showAuthStatus();
1407 Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
1408 }
1409 }
1410
1411
1412
1413
1414 /**
1415 * Sets the proper response to get that the Account Authenticator that started this activity
1416 * saves a new authorization token for mAccount.
1417 */
1418 private void updateToken() {
1419 Bundle response = new Bundle();
1420 response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
1421 response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);
1422
1423 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).
1424 equals(mAuthTokenType)) {
1425 response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
1426 // the next line is necessary, notifications are calling directly to the
1427 // AuthenticatorActivity to update, without AccountManager intervention
1428 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1429
1430 } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
1431 equals(mAuthTokenType)) {
1432
1433 response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
1434 // the next line is necessary; by now, notifications are calling directly to the
1435 // AuthenticatorActivity to update, without AccountManager intervention
1436 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1437
1438 } else {
1439 response.putString(AccountManager.KEY_AUTHTOKEN, mPasswordInput.getText().toString());
1440 mAccountMgr.setPassword(mAccount, mPasswordInput.getText().toString());
1441 }
1442 setAccountAuthenticatorResult(response);
1443
1444 }
1445
1446
1447 /**
1448 * Creates a new account through the Account Authenticator that started this activity.
1449 *
1450 * This makes the account permanent.
1451 *
1452 * TODO Decide how to name the OAuth accounts
1453 */
1454 private boolean createAccount() {
1455 /// create and save new ownCloud account
1456 boolean isOAuth = AccountTypeUtils.
1457 getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType);
1458 boolean isSaml = AccountTypeUtils.
1459 getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType);
1460
1461 Uri uri = Uri.parse(mServerInfo.mBaseUrl);
1462 String username = mUsernameInput.getText().toString().trim();
1463 if (isOAuth) {
1464 username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();
1465 }
1466 String accountName = com.owncloud.android.lib.common.accounts.AccountUtils.
1467 buildAccountName(uri, username);
1468 Account newAccount = new Account(accountName, MainApp.getAccountType());
1469 if (AccountUtils.exists(newAccount, getApplicationContext())) {
1470 // fail - not a new account, but an existing one; disallow
1471 RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW);
1472 updateAuthStatusIconAndText(result);
1473 showAuthStatus();
1474 Log_OC.d(TAG, result.getLogMessage());
1475 return false;
1476
1477 } else {
1478 mAccount = newAccount;
1479
1480 if (isOAuth || isSaml) {
1481 // with external authorizations, the password is never input in the app
1482 mAccountMgr.addAccountExplicitly(mAccount, "", null);
1483 } else {
1484 mAccountMgr.addAccountExplicitly(
1485 mAccount, mPasswordInput.getText().toString(), null
1486 );
1487 }
1488
1489 /// add the new account as default in preferences, if there is none already
1490 Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
1491 if (defaultAccount == null) {
1492 SharedPreferences.Editor editor = PreferenceManager
1493 .getDefaultSharedPreferences(this).edit();
1494 editor.putString("select_oc_account", accountName);
1495 editor.commit();
1496 }
1497
1498 /// prepare result to return to the Authenticator
1499 // TODO check again what the Authenticator makes with it; probably has the same
1500 // effect as addAccountExplicitly, but it's not well done
1501 final Intent intent = new Intent();
1502 intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, MainApp.getAccountType());
1503 intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
1504 /*if (!isOAuth)
1505 intent.putExtra(AccountManager.KEY_AUTHTOKEN, MainApp.getAccountType()); */
1506 intent.putExtra(AccountManager.KEY_USERDATA, username);
1507 if (isOAuth || isSaml) {
1508 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1509 }
1510 /// add user data to the new account; TODO probably can be done in the last parameter
1511 // addAccountExplicitly, or in KEY_USERDATA
1512 mAccountMgr.setUserData(
1513 mAccount, Constants.KEY_OC_VERSION, mServerInfo.mVersion.getVersion()
1514 );
1515 mAccountMgr.setUserData(
1516 mAccount, Constants.KEY_OC_BASE_URL, mServerInfo.mBaseUrl
1517 );
1518
1519 if (isSaml) {
1520 mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE");
1521 } else if (isOAuth) {
1522 mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_OAUTH2, "TRUE");
1523 }
1524
1525 setAccountAuthenticatorResult(intent.getExtras());
1526 setResult(RESULT_OK, intent);
1527
1528 return true;
1529 }
1530 }
1531
1532
1533 /**
1534 * Starts and activity to open the 'new account' page in the ownCloud web site
1535 *
1536 * @param view 'Account register' button
1537 */
1538 public void onRegisterClick(View view) {
1539 Intent register = new Intent(
1540 Intent.ACTION_VIEW, Uri.parse(getString(R.string.welcome_link_url))
1541 );
1542 setResult(RESULT_CANCELED);
1543 startActivity(register);
1544 }
1545
1546
1547 /**
1548 * Updates the content and visibility state of the icon and text associated
1549 * to the last check on the ownCloud server.
1550 *
1551 * @param serverStatusText Resource identifier of the text to show.
1552 * @param serverStatusIcon Resource identifier of the icon to show.
1553 */
1554 private void showServerStatus() {
1555 if (mServerStatusIcon == 0 && mServerStatusText == 0) {
1556 mServerStatusView.setVisibility(View.INVISIBLE);
1557
1558 } else {
1559 mServerStatusView.setText(mServerStatusText);
1560 mServerStatusView.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon, 0, 0, 0);
1561 mServerStatusView.setVisibility(View.VISIBLE);
1562 }
1563
1564 }
1565
1566
1567 /**
1568 * Updates the content and visibility state of the icon and text associated
1569 * to the interactions with the OAuth authorization server.
1570 */
1571 private void showAuthStatus() {
1572 if (mAuthStatusIcon == 0 && mAuthStatusText == 0) {
1573 mAuthStatusView.setVisibility(View.INVISIBLE);
1574
1575 } else {
1576 mAuthStatusView.setText(mAuthStatusText);
1577 mAuthStatusView.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon, 0, 0, 0);
1578 mAuthStatusView.setVisibility(View.VISIBLE);
1579 }
1580 }
1581
1582
1583 private void showRefreshButton (boolean show) {
1584 if (show) {
1585 mRefreshButton.setVisibility(View.VISIBLE);
1586 } else {
1587 mRefreshButton.setVisibility(View.GONE);
1588 }
1589 }
1590
1591 /**
1592 * Called when the refresh button in the input field for ownCloud host is clicked.
1593 *
1594 * Performs a new check on the URL in the input field.
1595 *
1596 * @param view Refresh 'button'
1597 */
1598 public void onRefreshClick(View view) {
1599 checkOcServer();
1600 }
1601
1602
1603 /**
1604 * Called when the eye icon in the password field is clicked.
1605 *
1606 * Toggles the visibility of the password in the field.
1607 */
1608 public void onViewPasswordClick() {
1609 int selectionStart = mPasswordInput.getSelectionStart();
1610 int selectionEnd = mPasswordInput.getSelectionEnd();
1611 if (isPasswordVisible()) {
1612 hidePassword();
1613 } else {
1614 showPassword();
1615 }
1616 mPasswordInput.setSelection(selectionStart, selectionEnd);
1617 }
1618
1619
1620 /**
1621 * Called when the checkbox for OAuth authorization is clicked.
1622 *
1623 * Hides or shows the input fields for user & password.
1624 *
1625 * @param view 'View password' 'button'
1626 */
1627 public void onCheckClick(View view) {
1628 CheckBox oAuth2Check = (CheckBox)view;
1629 if (oAuth2Check.isChecked()) {
1630 mAuthTokenType = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());
1631 } else {
1632 mAuthTokenType = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());
1633 }
1634 updateAuthenticationPreFragmentVisibility();
1635 }
1636
1637
1638 /**
1639 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1640 *
1641 * Used to trigger the authentication check when the user presses 'enter' after writing the
1642 * password, or to throw the server test when the only field on screen is the URL input field.
1643 */
1644 @Override
1645 public boolean onEditorAction(TextView inputField, int actionId, KeyEvent event) {
1646 if (actionId == EditorInfo.IME_ACTION_DONE && inputField != null &&
1647 inputField.equals(mPasswordInput)) {
1648 if (mOkButton.isEnabled()) {
1649 mOkButton.performClick();
1650 }
1651
1652 } else if (actionId == EditorInfo.IME_ACTION_NEXT && inputField != null &&
1653 inputField.equals(mHostUrlInput)) {
1654 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
1655 equals(mAuthTokenType)) {
1656 checkOcServer();
1657 }
1658 }
1659 return false; // always return false to grant that the software keyboard is hidden anyway
1660 }
1661
1662
1663 private abstract static class RightDrawableOnTouchListener implements OnTouchListener {
1664
1665 private int fuzz = 75;
1666
1667 /**
1668 * {@inheritDoc}
1669 */
1670 @Override
1671 public boolean onTouch(View view, MotionEvent event) {
1672 Drawable rightDrawable = null;
1673 if (view instanceof TextView) {
1674 Drawable[] drawables = ((TextView)view).getCompoundDrawables();
1675 if (drawables.length > 2) {
1676 rightDrawable = drawables[2];
1677 }
1678 }
1679 if (rightDrawable != null) {
1680 final int x = (int) event.getX();
1681 final int y = (int) event.getY();
1682 final Rect bounds = rightDrawable.getBounds();
1683 if ( x >= (view.getRight() - bounds.width() - fuzz) &&
1684 x <= (view.getRight() - view.getPaddingRight() + fuzz) &&
1685 y >= (view.getPaddingTop() - fuzz) &&
1686 y <= (view.getHeight() - view.getPaddingBottom()) + fuzz) {
1687
1688 return onDrawableTouch(event);
1689 }
1690 }
1691 return false;
1692 }
1693
1694 public abstract boolean onDrawableTouch(final MotionEvent event);
1695 }
1696
1697
1698 private void getRemoteUserNameOperation(String sessionCookie, boolean followRedirects) {
1699
1700 Intent getUserNameIntent = new Intent();
1701 getUserNameIntent.setAction(OperationsService.ACTION_GET_USER_NAME);
1702 getUserNameIntent.putExtra(OperationsService.EXTRA_SERVER_URL, mServerInfo.mBaseUrl);
1703 getUserNameIntent.putExtra(OperationsService.EXTRA_COOKIE, sessionCookie);
1704
1705 if (mOperationsServiceBinder != null) {
1706 //Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." );
1707 mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getUserNameIntent);
1708 }
1709 }
1710
1711
1712 @Override
1713 public void onSsoFinished(String sessionCookie) {
1714 if (sessionCookie != null && sessionCookie.length() > 0) {
1715 Log_OC.d(TAG, "Successful SSO - time to save the account");
1716 mAuthToken = sessionCookie;
1717 getRemoteUserNameOperation(sessionCookie, true);
1718 Fragment fd = getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG);
1719 if (fd != null && fd instanceof SherlockDialogFragment) {
1720 Dialog d = ((SherlockDialogFragment)fd).getDialog();
1721 if (d != null && d.isShowing()) {
1722 d.dismiss();
1723 }
1724 }
1725
1726 } else {
1727 // TODO - show fail
1728 Log_OC.d(TAG, "SSO failed");
1729 }
1730
1731 }
1732
1733 @Override
1734 public boolean onTouchEvent(MotionEvent event) {
1735 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
1736 equals(mAuthTokenType) &&
1737 mHostUrlInput.hasFocus() && event.getAction() == MotionEvent.ACTION_DOWN) {
1738 checkOcServer();
1739 }
1740 return super.onTouchEvent(event);
1741 }
1742
1743
1744 /**
1745 * Show untrusted cert dialog
1746 */
1747 public void showUntrustedCertDialog(
1748 X509Certificate x509Certificate, SslError error, SslErrorHandler handler
1749 ) {
1750 // Show a dialog with the certificate info
1751 SslUntrustedCertDialog dialog = null;
1752 if (x509Certificate == null) {
1753 dialog = SslUntrustedCertDialog.newInstanceForEmptySslError(error, handler);
1754 } else {
1755 dialog = SslUntrustedCertDialog.
1756 newInstanceForFullSslError(x509Certificate, error, handler);
1757 }
1758 FragmentManager fm = getSupportFragmentManager();
1759 FragmentTransaction ft = fm.beginTransaction();
1760 ft.addToBackStack(null);
1761 dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);
1762 }
1763
1764
1765 /**
1766 * Show untrusted cert dialog
1767 */
1768 private void showUntrustedCertDialog(RemoteOperationResult result) {
1769 // Show a dialog with the certificate info
1770 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.
1771 newInstanceForFullSslError((CertificateCombinedException)result.getException());
1772 FragmentManager fm = getSupportFragmentManager();
1773 FragmentTransaction ft = fm.beginTransaction();
1774 ft.addToBackStack(null);
1775 dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);
1776
1777 }
1778
1779 /**
1780 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1781 */
1782 public void onSavedCertificate() {
1783 Fragment fd = getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG);
1784 if (fd == null) {
1785 // if SAML dialog is not shown,
1786 // the SslDialog was shown due to an SSL error in the server check
1787 checkOcServer();
1788 }
1789 }
1790
1791 /**
1792 * Called from SslValidatorDialog when a new server certificate could not be saved
1793 * when the user requested it.
1794 */
1795 @Override
1796 public void onFailedSavingCertificate() {
1797 dismissDialog(SAML_DIALOG_TAG);
1798 Toast.makeText(this, R.string.ssl_validator_not_saved, Toast.LENGTH_LONG).show();
1799 }
1800
1801 @Override
1802 public void onCancelCertificate() {
1803 dismissDialog(SAML_DIALOG_TAG);
1804 }
1805
1806
1807 private void doOnResumeAndBound() {
1808 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1809 mOperationsServiceBinder.addOperationListener(AuthenticatorActivity.this, mHandler);
1810 if (mWaitingForOpId <= Integer.MAX_VALUE) {
1811 mOperationsServiceBinder.dispatchResultIfFinished((int)mWaitingForOpId, this);
1812 }
1813
1814 if (mPendingAutoCheck) {
1815 checkOcServer();
1816 }
1817 }
1818
1819
1820 private void dismissDialog(String dialogTag){
1821 Fragment frag = getSupportFragmentManager().findFragmentByTag(dialogTag);
1822 if (frag != null && frag instanceof SherlockDialogFragment) {
1823 SherlockDialogFragment dialog = (SherlockDialogFragment) frag;
1824 dialog.dismiss();
1825 }
1826 }
1827
1828
1829 /**
1830 * Implements callback methods for service binding.
1831 */
1832 private class OperationsServiceConnection implements ServiceConnection {
1833
1834 @Override
1835 public void onServiceConnected(ComponentName component, IBinder service) {
1836 if (component.equals(
1837 new ComponentName(AuthenticatorActivity.this, OperationsService.class)
1838 )) {
1839 //Log_OC.wtf(TAG, "Operations service connected");
1840 mOperationsServiceBinder = (OperationsServiceBinder) service;
1841
1842 doOnResumeAndBound();
1843
1844 } else {
1845 return;
1846 }
1847
1848 }
1849
1850 @Override
1851 public void onServiceDisconnected(ComponentName component) {
1852 if (component.equals(
1853 new ComponentName(AuthenticatorActivity.this, OperationsService.class)
1854 )) {
1855 Log_OC.e(TAG, "Operations service crashed");
1856 mOperationsServiceBinder = null;
1857 }
1858 }
1859
1860 }
1861
1862 /**
1863 * Create and show dialog for request authentication to the user
1864 * @param webView
1865 * @param handler
1866 */
1867 public void createAuthenticationDialog(WebView webView, HttpAuthHandler handler) {
1868
1869 // Show a dialog with the certificate info
1870 CredentialsDialogFragment dialog =
1871 CredentialsDialogFragment.newInstanceForCredentials(webView, handler);
1872 FragmentManager fm = getSupportFragmentManager();
1873 FragmentTransaction ft = fm.beginTransaction();
1874 ft.addToBackStack(null);
1875 dialog.setCancelable(false);
1876 dialog.show(ft, CREDENTIALS_DIALOG_TAG);
1877
1878 if (!mIsFirstAuthAttempt) {
1879 Toast.makeText(
1880 getApplicationContext(),
1881 getText(R.string.saml_authentication_wrong_pass),
1882 Toast.LENGTH_LONG
1883 ).show();
1884 } else {
1885 mIsFirstAuthAttempt = false;
1886 }
1887 }
1888
1889 /**
1890 * For retrieving the clicking on authentication cancel button
1891 */
1892 public void doNegativeAuthenticatioDialogClick(){
1893 mIsFirstAuthAttempt = true;
1894 }
1895 }