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