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