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