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