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