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