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