Merge branch 'master' into copy
[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 // Handle internationalized domain names
805 uri = DisplayUtils.convertIdn(uri, true);
806
807 mServerStatusText = R.string.auth_testing_connection;
808 mServerStatusIcon = R.drawable.progress_small;
809 showServerStatus();
810
811 Intent getServerInfoIntent = new Intent();
812 getServerInfoIntent.setAction(OperationsService.ACTION_GET_SERVER_INFO);
813 getServerInfoIntent.putExtra(
814 OperationsService.EXTRA_SERVER_URL,
815 normalizeUrlSuffix(uri)
816 );
817 if (mOperationsServiceBinder != null) {
818 mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getServerInfoIntent);
819 } else {
820 Log_OC.wtf(TAG, "Server check tried with OperationService unbound!" );
821 }
822
823 } else {
824 mServerStatusText = 0;
825 mServerStatusIcon = 0;
826 showServerStatus();
827 }
828 }
829
830
831 /**
832 * Handles changes in focus on the text input for the password (basic authorization).
833 *
834 * When (hasFocus), the button to toggle password visibility is shown.
835 *
836 * When (!hasFocus), the button is made invisible and the password is hidden.
837 *
838 * @param hasFocus 'True' if focus is received, 'false' if is lost
839 */
840 private void onPasswordFocusChanged(boolean hasFocus) {
841 if (hasFocus) {
842 showViewPasswordButton();
843 } else {
844 hidePassword();
845 hidePasswordButton();
846 }
847 }
848
849
850 private void showViewPasswordButton() {
851 int drawable = R.drawable.ic_view;
852 if (isPasswordVisible()) {
853 drawable = R.drawable.ic_hide;
854 }
855 mPasswordInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, drawable, 0);
856 }
857
858 private boolean isPasswordVisible() {
859 return ((mPasswordInput.getInputType() & InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) ==
860 InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
861 }
862
863 private void hidePasswordButton() {
864 mPasswordInput.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
865 }
866
867 private void showPassword() {
868 mPasswordInput.setInputType(
869 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
870 );
871 showViewPasswordButton();
872 }
873
874 private void hidePassword() {
875 mPasswordInput.setInputType(
876 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
877 );
878 showViewPasswordButton();
879 }
880
881 /**
882 * Checks the credentials of the user in the root of the ownCloud server
883 * before creating a new local account.
884 *
885 * For basic authorization, a check of existence of the root folder is
886 * performed.
887 *
888 * For OAuth, starts the flow to get an access token; the credentials test
889 * is postponed until it is available.
890 *
891 * IMPORTANT ENTRY POINT 4
892 */
893 public void onOkClick() {
894 // this check should be unnecessary
895 if (mServerInfo.mVersion == null ||
896 !mServerInfo.mVersion.isVersionValid() ||
897 mServerInfo.mBaseUrl == null ||
898 mServerInfo.mBaseUrl.length() == 0) {
899 mServerStatusIcon = R.drawable.common_error;
900 mServerStatusText = R.string.auth_wtf_reenter_URL;
901 showServerStatus();
902 mOkButton.setEnabled(false);
903 return;
904 }
905
906 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).
907 equals(mAuthTokenType)) {
908
909 startOauthorization();
910 } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
911 equals(mAuthTokenType)) {
912
913 startSamlBasedFederatedSingleSignOnAuthorization();
914 } else {
915 checkBasicAuthorization();
916 }
917 }
918
919
920 /**
921 * Tests the credentials entered by the user performing a check of existence on
922 * the root folder of the ownCloud server.
923 */
924 private void checkBasicAuthorization() {
925 /// get basic credentials entered by user
926 String username = mUsernameInput.getText().toString();
927 String password = mPasswordInput.getText().toString();
928
929 /// be gentle with the user
930 IndeterminateProgressDialog dialog =
931 IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);
932 dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
933
934 /// validate credentials accessing the root folder
935 OwnCloudCredentials credentials = OwnCloudCredentialsFactory.newBasicCredentials(username,
936 password);
937 accessRootFolder(credentials);
938 }
939
940 private void accessRootFolder(OwnCloudCredentials credentials) {
941 mAsyncTask = new AuthenticatorAsyncTask(this);
942 Object[] params = { mServerInfo.mBaseUrl, credentials };
943 mAsyncTask.execute(params);
944 }
945
946
947 /**
948 * Starts the OAuth 'grant type' flow to get an access token, with
949 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
950 */
951 private void startOauthorization() {
952 // be gentle with the user
953 mAuthStatusIcon = R.drawable.progress_small;
954 mAuthStatusText = R.string.oauth_login_connection;
955 showAuthStatus();
956
957 // GET AUTHORIZATION request
958 Uri uri = Uri.parse(mOAuthAuthEndpointText.getText().toString().trim());
959 Uri.Builder uriBuilder = uri.buildUpon();
960 uriBuilder.appendQueryParameter(
961 OAuth2Constants.KEY_RESPONSE_TYPE, getString(R.string.oauth2_response_type)
962 );
963 uriBuilder.appendQueryParameter(
964 OAuth2Constants.KEY_REDIRECT_URI, getString(R.string.oauth2_redirect_uri)
965 );
966 uriBuilder.appendQueryParameter(
967 OAuth2Constants.KEY_CLIENT_ID, getString(R.string.oauth2_client_id)
968 );
969 uriBuilder.appendQueryParameter(
970 OAuth2Constants.KEY_SCOPE, getString(R.string.oauth2_scope)
971 );
972 uri = uriBuilder.build();
973 Log_OC.d(TAG, "Starting browser to view " + uri.toString());
974 Intent i = new Intent(Intent.ACTION_VIEW, uri);
975 startActivity(i);
976 }
977
978
979 /**
980 * Starts the Web Single Sign On flow to get access to the root folder
981 * in the server.
982 */
983 private void startSamlBasedFederatedSingleSignOnAuthorization() {
984 /// be gentle with the user
985 mAuthStatusIcon = R.drawable.progress_small;
986 mAuthStatusText = R.string.auth_connecting_auth_server;
987 showAuthStatus();
988
989 /// Show SAML-based SSO web dialog
990 String targetUrl = mServerInfo.mBaseUrl
991 + AccountUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType);
992 SamlWebViewDialog dialog = SamlWebViewDialog.newInstance(targetUrl, targetUrl);
993 dialog.show(getSupportFragmentManager(), SAML_DIALOG_TAG);
994 }
995
996 /**
997 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
998 *
999 * Dispatches the operation flow to the right method.
1000 */
1001 @Override
1002 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1003
1004 if (operation instanceof GetServerInfoOperation) {
1005 if (operation.hashCode() == mWaitingForOpId) {
1006 onGetServerInfoFinish(result);
1007 } // else nothing ; only the last check operation is considered;
1008 // multiple can be started if the user amends a URL quickly
1009
1010 } else if (operation instanceof OAuth2GetAccessToken) {
1011 onGetOAuthAccessTokenFinish(result);
1012
1013 } else if (operation instanceof GetRemoteUserNameOperation) {
1014 onGetUserNameFinish(result);
1015 }
1016
1017 }
1018
1019 private void onGetUserNameFinish(RemoteOperationResult result) {
1020 mWaitingForOpId = Long.MAX_VALUE;
1021 if (result.isSuccess()) {
1022 boolean success = false;
1023 String username = (String) result.getData().get(0);
1024
1025 if ( mAction == ACTION_CREATE) {
1026 mUsernameInput.setText(username);
1027 success = createAccount(result);
1028 } else {
1029
1030 if (!mUsernameInput.getText().toString().equals(username)) {
1031 // fail - not a new account, but an existing one; disallow
1032 result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME);
1033 mAuthToken = "";
1034 updateAuthStatusIconAndText(result);
1035 showAuthStatus();
1036 Log_OC.d(TAG, result.getLogMessage());
1037 } else {
1038 try {
1039 updateAccountAuthentication();
1040 success = true;
1041
1042 } catch (AccountNotFoundException e) {
1043 Log_OC.e(TAG, "Account " + mAccount + " was removed!", e);
1044 Toast.makeText(this, R.string.auth_account_does_not_exist,
1045 Toast.LENGTH_SHORT).show();
1046 finish();
1047 }
1048 }
1049 }
1050
1051 if (success)
1052 finish();
1053 } else {
1054 updateStatusIconFailUserName();
1055 showAuthStatus();
1056 Log_OC.e(TAG, "Access to user name failed: " + result.getLogMessage());
1057 }
1058
1059 }
1060
1061 /**
1062 * Processes the result of the server check performed when the user finishes the enter of the
1063 * server URL.
1064 *
1065 * @param result Result of the check.
1066 */
1067 private void onGetServerInfoFinish(RemoteOperationResult result) {
1068 /// update activity state
1069 mServerIsChecked = true;
1070 mWaitingForOpId = Long.MAX_VALUE;
1071
1072 // update server status, but don't show it yet
1073 updateServerStatusIconAndText(result);
1074
1075 if (result.isSuccess()) {
1076 /// SUCCESS means:
1077 // 1. connection succeeded, and we know if it's SSL or not
1078 // 2. server is installed
1079 // 3. we got the server version
1080 // 4. we got the authentication method required by the server
1081 mServerInfo = (GetServerInfoOperation.ServerInfo) (result.getData().get(0));
1082
1083 if (!authSupported(mServerInfo.mAuthMethod)) {
1084
1085 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1086 mServerIsValid = false;
1087
1088 } else {
1089 mServerIsValid = true;
1090 }
1091
1092 } else {
1093 mServerIsValid = false;
1094 }
1095
1096 // refresh UI
1097 showRefreshButton(!mServerIsValid);
1098 showServerStatus();
1099 mOkButton.setEnabled(mServerIsValid);
1100
1101 /// very special case (TODO: move to a common place for all the remote operations)
1102 if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
1103 showUntrustedCertDialog(result);
1104 }
1105 }
1106
1107
1108 private boolean authSupported(AuthenticationMethod authMethod) {
1109 return (( BASIC_TOKEN_TYPE.equals(mAuthTokenType) &&
1110 AuthenticationMethod.BASIC_HTTP_AUTH.equals(authMethod) ) ||
1111 ( OAUTH_TOKEN_TYPE.equals(mAuthTokenType) &&
1112 AuthenticationMethod.BEARER_TOKEN.equals(authMethod)) ||
1113 ( SAML_TOKEN_TYPE.equals(mAuthTokenType) &&
1114 AuthenticationMethod.SAML_WEB_SSO.equals(authMethod))
1115 );
1116 }
1117
1118
1119 // TODO remove, if possible
1120 private String normalizeUrl(String url, boolean sslWhenUnprefixed) {
1121 if (url != null && url.length() > 0) {
1122 url = url.trim();
1123 if (!url.toLowerCase().startsWith("http://") &&
1124 !url.toLowerCase().startsWith("https://")) {
1125 if (sslWhenUnprefixed) {
1126 url = "https://" + url;
1127 } else {
1128 url = "http://" + url;
1129 }
1130 }
1131
1132 url = normalizeUrlSuffix(url);
1133 }
1134 return (url != null ? url : "");
1135 }
1136
1137
1138 private String normalizeUrlSuffix(String url) {
1139 if (url.endsWith("/")) {
1140 url = url.substring(0, url.length() - 1);
1141 }
1142 url = trimUrlWebdav(url);
1143 return url;
1144 }
1145
1146
1147 // TODO remove, if possible
1148 private String trimUrlWebdav(String url){
1149 if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0_AND_LATER)){
1150 url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0_AND_LATER.length());
1151 }
1152 return url;
1153 }
1154
1155
1156 /**
1157 * Chooses the right icon and text to show to the user for the received operation result.
1158 *
1159 * @param result Result of a remote operation performed in this activity
1160 */
1161 private void updateServerStatusIconAndText(RemoteOperationResult result) {
1162 mServerStatusIcon = R.drawable.common_error; // the most common case in the switch below
1163
1164 switch (result.getCode()) {
1165 case OK_SSL:
1166 mServerStatusIcon = R.drawable.ic_lock;
1167 mServerStatusText = R.string.auth_secure_connection;
1168 break;
1169
1170 case OK_NO_SSL:
1171 case OK:
1172 if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1173 mServerStatusText = R.string.auth_connection_established;
1174 mServerStatusIcon = R.drawable.ic_ok;
1175 } else {
1176 mServerStatusText = R.string.auth_nossl_plain_ok_title;
1177 mServerStatusIcon = R.drawable.ic_lock_open;
1178 }
1179 break;
1180
1181 case NO_NETWORK_CONNECTION:
1182 mServerStatusIcon = R.drawable.no_network;
1183 mServerStatusText = R.string.auth_no_net_conn_title;
1184 break;
1185
1186 case SSL_RECOVERABLE_PEER_UNVERIFIED:
1187 mServerStatusText = R.string.auth_ssl_unverified_server_title;
1188 break;
1189 case BAD_OC_VERSION:
1190 mServerStatusText = R.string.auth_bad_oc_version_title;
1191 break;
1192 case WRONG_CONNECTION:
1193 mServerStatusText = R.string.auth_wrong_connection_title;
1194 break;
1195 case TIMEOUT:
1196 mServerStatusText = R.string.auth_timeout_title;
1197 break;
1198 case INCORRECT_ADDRESS:
1199 mServerStatusText = R.string.auth_incorrect_address_title;
1200 break;
1201 case SSL_ERROR:
1202 mServerStatusText = R.string.auth_ssl_general_error_title;
1203 break;
1204 case UNAUTHORIZED:
1205 mServerStatusText = R.string.auth_unauthorized;
1206 break;
1207 case HOST_NOT_AVAILABLE:
1208 mServerStatusText = R.string.auth_unknown_host_title;
1209 break;
1210 case INSTANCE_NOT_CONFIGURED:
1211 mServerStatusText = R.string.auth_not_configured_title;
1212 break;
1213 case FILE_NOT_FOUND:
1214 mServerStatusText = R.string.auth_incorrect_path_title;
1215 break;
1216 case OAUTH2_ERROR:
1217 mServerStatusText = R.string.auth_oauth_error;
1218 break;
1219 case OAUTH2_ERROR_ACCESS_DENIED:
1220 mServerStatusText = R.string.auth_oauth_error_access_denied;
1221 break;
1222 case UNHANDLED_HTTP_CODE:
1223 case UNKNOWN_ERROR:
1224 mServerStatusText = R.string.auth_unknown_error_title;
1225 break;
1226 case OK_REDIRECT_TO_NON_SECURE_CONNECTION:
1227 mServerStatusIcon = R.drawable.ic_lock_open;
1228 mServerStatusText = R.string.auth_redirect_non_secure_connection_title;
1229 break;
1230 default:
1231 mServerStatusText = 0;
1232 mServerStatusIcon = 0;
1233 }
1234 }
1235
1236
1237 /**
1238 * Chooses the right icon and text to show to the user for the received operation result.
1239 *
1240 * @param result Result of a remote operation performed in this activity
1241 */
1242 private void updateAuthStatusIconAndText(RemoteOperationResult result) {
1243 mAuthStatusIcon = R.drawable.common_error; // the most common case in the switch below
1244
1245 switch (result.getCode()) {
1246 case OK_SSL:
1247 mAuthStatusIcon = R.drawable.ic_lock;
1248 mAuthStatusText = R.string.auth_secure_connection;
1249 break;
1250
1251 case OK_NO_SSL:
1252 case OK:
1253 if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1254 mAuthStatusText = R.string.auth_connection_established;
1255 mAuthStatusIcon = R.drawable.ic_ok;
1256 } else {
1257 mAuthStatusText = R.string.auth_nossl_plain_ok_title;
1258 mAuthStatusIcon = R.drawable.ic_lock_open;
1259 }
1260 break;
1261
1262 case NO_NETWORK_CONNECTION:
1263 mAuthStatusIcon = R.drawable.no_network;
1264 mAuthStatusText = R.string.auth_no_net_conn_title;
1265 break;
1266
1267 case SSL_RECOVERABLE_PEER_UNVERIFIED:
1268 mAuthStatusText = R.string.auth_ssl_unverified_server_title;
1269 break;
1270 case BAD_OC_VERSION:
1271 mAuthStatusText = R.string.auth_bad_oc_version_title;
1272 break;
1273 case WRONG_CONNECTION:
1274 mAuthStatusText = R.string.auth_wrong_connection_title;
1275 break;
1276 case TIMEOUT:
1277 mAuthStatusText = R.string.auth_timeout_title;
1278 break;
1279 case INCORRECT_ADDRESS:
1280 mAuthStatusText = R.string.auth_incorrect_address_title;
1281 break;
1282 case SSL_ERROR:
1283 mAuthStatusText = R.string.auth_ssl_general_error_title;
1284 break;
1285 case UNAUTHORIZED:
1286 mAuthStatusText = R.string.auth_unauthorized;
1287 break;
1288 case HOST_NOT_AVAILABLE:
1289 mAuthStatusText = R.string.auth_unknown_host_title;
1290 break;
1291 case INSTANCE_NOT_CONFIGURED:
1292 mAuthStatusText = R.string.auth_not_configured_title;
1293 break;
1294 case FILE_NOT_FOUND:
1295 mAuthStatusText = R.string.auth_incorrect_path_title;
1296 break;
1297 case OAUTH2_ERROR:
1298 mAuthStatusText = R.string.auth_oauth_error;
1299 break;
1300 case OAUTH2_ERROR_ACCESS_DENIED:
1301 mAuthStatusText = R.string.auth_oauth_error_access_denied;
1302 break;
1303 case ACCOUNT_NOT_NEW:
1304 mAuthStatusText = R.string.auth_account_not_new;
1305 break;
1306 case ACCOUNT_NOT_THE_SAME:
1307 mAuthStatusText = R.string.auth_account_not_the_same;
1308 break;
1309 case UNHANDLED_HTTP_CODE:
1310 case UNKNOWN_ERROR:
1311 mAuthStatusText = R.string.auth_unknown_error_title;
1312 break;
1313 default:
1314 mAuthStatusText = 0;
1315 mAuthStatusIcon = 0;
1316 }
1317 }
1318
1319
1320 private void updateStatusIconFailUserName(){
1321 mAuthStatusIcon = R.drawable.common_error;
1322 mAuthStatusText = R.string.auth_fail_get_user_name;
1323 }
1324
1325 private void updateServerStatusIconNoRegularAuth(){
1326 mServerStatusIcon = R.drawable.common_error;
1327 mServerStatusText = R.string.auth_can_not_auth_against_server;
1328 }
1329
1330 /**
1331 * Processes the result of the request for and access token send
1332 * to an OAuth authorization server.
1333 *
1334 * @param result Result of the operation.
1335 */
1336 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result) {
1337 mWaitingForOpId = Long.MAX_VALUE;
1338 dismissDialog(WAIT_DIALOG_TAG);
1339
1340 if (result.isSuccess()) {
1341 /// be gentle with the user
1342 IndeterminateProgressDialog dialog =
1343 IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);
1344 dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
1345
1346 /// time to test the retrieved access token on the ownCloud server
1347 @SuppressWarnings("unchecked")
1348 Map<String, String> tokens = (Map<String, String>)(result.getData().get(0));
1349 mAuthToken = tokens.get(OAuth2Constants.KEY_ACCESS_TOKEN);
1350 Log_OC.d(TAG, "Got ACCESS TOKEN: " + mAuthToken);
1351
1352 /// validate token accessing to root folder / getting session
1353 OwnCloudCredentials credentials = OwnCloudCredentialsFactory.newBearerCredentials(
1354 mAuthToken);
1355 accessRootFolder(credentials);
1356
1357 } else {
1358 updateAuthStatusIconAndText(result);
1359 showAuthStatus();
1360 Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
1361 }
1362 }
1363
1364
1365 /**
1366 * Processes the result of the access check performed to try the user credentials.
1367 *
1368 * Creates a new account through the AccountManager.
1369 *
1370 * @param result Result of the operation.
1371 */
1372 @Override
1373 public void onAuthenticatorTaskCallback(RemoteOperationResult result) {
1374 mWaitingForOpId = Long.MAX_VALUE;
1375 dismissDialog(WAIT_DIALOG_TAG);
1376
1377 if (result.isSuccess()) {
1378 Log_OC.d(TAG, "Successful access - time to save the account");
1379
1380 boolean success = false;
1381
1382 if (mAction == ACTION_CREATE) {
1383 success = createAccount(result);
1384
1385 } else {
1386 try {
1387 updateAccountAuthentication();
1388 success = true;
1389
1390 } catch (AccountNotFoundException e) {
1391 Log_OC.e(TAG, "Account " + mAccount + " was removed!", e);
1392 Toast.makeText(this, R.string.auth_account_does_not_exist,
1393 Toast.LENGTH_SHORT).show();
1394 finish();
1395 }
1396 }
1397
1398 if (success) {
1399 finish();
1400 }
1401
1402 } else if (result.isServerFail() || result.isException()) {
1403 /// server errors or exceptions in authorization take to requiring a new check of
1404 /// the server
1405 mServerIsChecked = true;
1406 mServerIsValid = false;
1407 mServerInfo = new GetServerInfoOperation.ServerInfo();
1408
1409 // update status icon and text
1410 updateServerStatusIconAndText(result);
1411 showServerStatus();
1412 mAuthStatusIcon = 0;
1413 mAuthStatusText = 0;
1414 showAuthStatus();
1415
1416 // update input controls state
1417 showRefreshButton(true);
1418 mOkButton.setEnabled(false);
1419
1420 // very special case (TODO: move to a common place for all the remote operations)
1421 if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
1422 showUntrustedCertDialog(result);
1423 }
1424
1425 } else { // authorization fail due to client side - probably wrong credentials
1426 updateAuthStatusIconAndText(result);
1427 showAuthStatus();
1428 Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
1429 }
1430 }
1431
1432
1433
1434
1435 /**
1436 * Updates the authentication token.
1437 *
1438 * Sets the proper response so that the AccountAuthenticator that started this activity
1439 * saves a new authorization token for mAccount.
1440 *
1441 * Kills the session kept by OwnCloudClientManager so that a new one will created with
1442 * the new credentials when needed.
1443 */
1444 private void updateAccountAuthentication() throws AccountNotFoundException {
1445
1446 Bundle response = new Bundle();
1447 response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
1448 response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);
1449
1450 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).
1451 equals(mAuthTokenType)) {
1452 response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
1453 // the next line is necessary, notifications are calling directly to the
1454 // AuthenticatorActivity to update, without AccountManager intervention
1455 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1456
1457 } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
1458 equals(mAuthTokenType)) {
1459
1460 response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
1461 // the next line is necessary; by now, notifications are calling directly to the
1462 // AuthenticatorActivity to update, without AccountManager intervention
1463 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1464
1465 } else {
1466 response.putString(AccountManager.KEY_AUTHTOKEN, mPasswordInput.getText().toString());
1467 mAccountMgr.setPassword(mAccount, mPasswordInput.getText().toString());
1468 }
1469 setAccountAuthenticatorResult(response);
1470
1471 }
1472
1473
1474 /**
1475 * Creates a new account through the Account Authenticator that started this activity.
1476 *
1477 * This makes the account permanent.
1478 *
1479 * TODO Decide how to name the OAuth accounts
1480 */
1481 private boolean createAccount(RemoteOperationResult authResult) {
1482 /// create and save new ownCloud account
1483 boolean isOAuth = AccountTypeUtils.
1484 getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType);
1485 boolean isSaml = AccountTypeUtils.
1486 getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType);
1487
1488 String lastPermanentLocation = authResult.getLastPermanentLocation();
1489 if (lastPermanentLocation != null) {
1490 mServerInfo.mBaseUrl = AccountUtils.trimWebdavSuffix(lastPermanentLocation);
1491 }
1492
1493 Uri uri = Uri.parse(mServerInfo.mBaseUrl);
1494 String username = mUsernameInput.getText().toString().trim();
1495 if (isOAuth) {
1496 username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();
1497 }
1498 String accountName = com.owncloud.android.lib.common.accounts.AccountUtils.
1499 buildAccountName(uri, username);
1500 Account newAccount = new Account(accountName, MainApp.getAccountType());
1501 if (AccountUtils.exists(newAccount, getApplicationContext())) {
1502 // fail - not a new account, but an existing one; disallow
1503 RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW);
1504 updateAuthStatusIconAndText(result);
1505 showAuthStatus();
1506 Log_OC.d(TAG, result.getLogMessage());
1507 return false;
1508
1509 } else {
1510 mAccount = newAccount;
1511
1512 if (isOAuth || isSaml) {
1513 // with external authorizations, the password is never input in the app
1514 mAccountMgr.addAccountExplicitly(mAccount, "", null);
1515 } else {
1516 mAccountMgr.addAccountExplicitly(
1517 mAccount, mPasswordInput.getText().toString(), null
1518 );
1519 }
1520
1521 // include account version with the new account
1522 mAccountMgr.setUserData(
1523 mAccount,
1524 Constants.KEY_OC_ACCOUNT_VERSION,
1525 Integer.toString(AccountUtils.ACCOUNT_VERSION)
1526 );
1527
1528 /// add the new account as default in preferences, if there is none already
1529 Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
1530 if (defaultAccount == null) {
1531 SharedPreferences.Editor editor = PreferenceManager
1532 .getDefaultSharedPreferences(this).edit();
1533 editor.putString("select_oc_account", accountName);
1534 editor.commit();
1535 }
1536
1537 /// prepare result to return to the Authenticator
1538 // TODO check again what the Authenticator makes with it; probably has the same
1539 // effect as addAccountExplicitly, but it's not well done
1540 final Intent intent = new Intent();
1541 intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, MainApp.getAccountType());
1542 intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
1543 intent.putExtra(AccountManager.KEY_USERDATA, username);
1544 if (isOAuth || isSaml) {
1545 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1546 }
1547 /// add user data to the new account; TODO probably can be done in the last parameter
1548 // addAccountExplicitly, or in KEY_USERDATA
1549 mAccountMgr.setUserData(
1550 mAccount, Constants.KEY_OC_VERSION, mServerInfo.mVersion.getVersion()
1551 );
1552 mAccountMgr.setUserData(
1553 mAccount, Constants.KEY_OC_BASE_URL, mServerInfo.mBaseUrl
1554 );
1555
1556 if (isSaml) {
1557 mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE");
1558 } else if (isOAuth) {
1559 mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_OAUTH2, "TRUE");
1560 }
1561
1562 setAccountAuthenticatorResult(intent.getExtras());
1563 setResult(RESULT_OK, intent);
1564
1565 return true;
1566 }
1567 }
1568
1569
1570 /**
1571 * Starts and activity to open the 'new account' page in the ownCloud web site
1572 *
1573 * @param view 'Account register' button
1574 */
1575 public void onRegisterClick(View view) {
1576 Intent register = new Intent(
1577 Intent.ACTION_VIEW, Uri.parse(getString(R.string.welcome_link_url))
1578 );
1579 setResult(RESULT_CANCELED);
1580 startActivity(register);
1581 }
1582
1583
1584 /**
1585 * Updates the content and visibility state of the icon and text associated
1586 * to the last check on the ownCloud server.
1587 *
1588 */
1589 private void showServerStatus() {
1590 if (mServerStatusIcon == 0 && mServerStatusText == 0) {
1591 mServerStatusView.setVisibility(View.INVISIBLE);
1592
1593 } else {
1594 mServerStatusView.setText(mServerStatusText);
1595 mServerStatusView.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon, 0, 0, 0);
1596 mServerStatusView.setVisibility(View.VISIBLE);
1597 }
1598
1599 }
1600
1601
1602 /**
1603 * Updates the content and visibility state of the icon and text associated
1604 * to the interactions with the OAuth authorization server.
1605 */
1606 private void showAuthStatus() {
1607 if (mAuthStatusIcon == 0 && mAuthStatusText == 0) {
1608 mAuthStatusView.setVisibility(View.INVISIBLE);
1609
1610 } else {
1611 mAuthStatusView.setText(mAuthStatusText);
1612 mAuthStatusView.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon, 0, 0, 0);
1613 mAuthStatusView.setVisibility(View.VISIBLE);
1614 }
1615 }
1616
1617
1618 private void showRefreshButton (boolean show) {
1619 if (show) {
1620 mRefreshButton.setVisibility(View.VISIBLE);
1621 } else {
1622 mRefreshButton.setVisibility(View.GONE);
1623 }
1624 }
1625
1626 /**
1627 * Called when the refresh button in the input field for ownCloud host is clicked.
1628 *
1629 * Performs a new check on the URL in the input field.
1630 *
1631 * @param view Refresh 'button'
1632 */
1633 public void onRefreshClick(View view) {
1634 checkOcServer();
1635 }
1636
1637
1638 /**
1639 * Called when the eye icon in the password field is clicked.
1640 *
1641 * Toggles the visibility of the password in the field.
1642 */
1643 public void onViewPasswordClick() {
1644 int selectionStart = mPasswordInput.getSelectionStart();
1645 int selectionEnd = mPasswordInput.getSelectionEnd();
1646 if (isPasswordVisible()) {
1647 hidePassword();
1648 } else {
1649 showPassword();
1650 }
1651 mPasswordInput.setSelection(selectionStart, selectionEnd);
1652 }
1653
1654
1655 /**
1656 * Called when the checkbox for OAuth authorization is clicked.
1657 *
1658 * Hides or shows the input fields for user & password.
1659 *
1660 * @param view 'View password' 'button'
1661 */
1662 public void onCheckClick(View view) {
1663 CheckBox oAuth2Check = (CheckBox)view;
1664 if (oAuth2Check.isChecked()) {
1665 mAuthTokenType = OAUTH_TOKEN_TYPE;
1666 } else {
1667 mAuthTokenType = BASIC_TOKEN_TYPE;
1668 }
1669 updateAuthenticationPreFragmentVisibility();
1670 }
1671
1672
1673 /**
1674 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1675 *
1676 * Used to trigger the authentication check when the user presses 'enter' after writing the
1677 * password, or to throw the server test when the only field on screen is the URL input field.
1678 */
1679 @Override
1680 public boolean onEditorAction(TextView inputField, int actionId, KeyEvent event) {
1681 if (actionId == EditorInfo.IME_ACTION_DONE && inputField != null &&
1682 inputField.equals(mPasswordInput)) {
1683 if (mOkButton.isEnabled()) {
1684 mOkButton.performClick();
1685 }
1686
1687 } else if (actionId == EditorInfo.IME_ACTION_NEXT && inputField != null &&
1688 inputField.equals(mHostUrlInput)) {
1689 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
1690 equals(mAuthTokenType)) {
1691 checkOcServer();
1692 }
1693 }
1694 return false; // always return false to grant that the software keyboard is hidden anyway
1695 }
1696
1697
1698 private abstract static class RightDrawableOnTouchListener implements OnTouchListener {
1699
1700 private int fuzz = 75;
1701
1702 /**
1703 * {@inheritDoc}
1704 */
1705 @Override
1706 public boolean onTouch(View view, MotionEvent event) {
1707 Drawable rightDrawable = null;
1708 if (view instanceof TextView) {
1709 Drawable[] drawables = ((TextView)view).getCompoundDrawables();
1710 if (drawables.length > 2) {
1711 rightDrawable = drawables[2];
1712 }
1713 }
1714 if (rightDrawable != null) {
1715 final int x = (int) event.getX();
1716 final int y = (int) event.getY();
1717 final Rect bounds = rightDrawable.getBounds();
1718 if ( x >= (view.getRight() - bounds.width() - fuzz) &&
1719 x <= (view.getRight() - view.getPaddingRight() + fuzz) &&
1720 y >= (view.getPaddingTop() - fuzz) &&
1721 y <= (view.getHeight() - view.getPaddingBottom()) + fuzz) {
1722
1723 return onDrawableTouch(event);
1724 }
1725 }
1726 return false;
1727 }
1728
1729 public abstract boolean onDrawableTouch(final MotionEvent event);
1730 }
1731
1732
1733 private void getRemoteUserNameOperation(String sessionCookie) {
1734
1735 Intent getUserNameIntent = new Intent();
1736 getUserNameIntent.setAction(OperationsService.ACTION_GET_USER_NAME);
1737 getUserNameIntent.putExtra(OperationsService.EXTRA_SERVER_URL, mServerInfo.mBaseUrl);
1738 getUserNameIntent.putExtra(OperationsService.EXTRA_COOKIE, sessionCookie);
1739
1740 if (mOperationsServiceBinder != null) {
1741 mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getUserNameIntent);
1742 }
1743 }
1744
1745
1746 @Override
1747 public void onSsoFinished(String sessionCookie) {
1748 if (sessionCookie != null && sessionCookie.length() > 0) {
1749 Log_OC.d(TAG, "Successful SSO - time to save the account");
1750 mAuthToken = sessionCookie;
1751 getRemoteUserNameOperation(sessionCookie);
1752 Fragment fd = getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG);
1753 if (fd != null && fd instanceof DialogFragment) {
1754 Dialog d = ((DialogFragment)fd).getDialog();
1755 if (d != null && d.isShowing()) {
1756 d.dismiss();
1757 }
1758 }
1759
1760 } else {
1761 // TODO - show fail
1762 Log_OC.d(TAG, "SSO failed");
1763 }
1764
1765 }
1766
1767 @Override
1768 public boolean onTouchEvent(MotionEvent event) {
1769 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
1770 equals(mAuthTokenType) &&
1771 mHostUrlInput.hasFocus() && event.getAction() == MotionEvent.ACTION_DOWN) {
1772 checkOcServer();
1773 }
1774 return super.onTouchEvent(event);
1775 }
1776
1777
1778 /**
1779 * Show untrusted cert dialog
1780 */
1781 public void showUntrustedCertDialog(
1782 X509Certificate x509Certificate, SslError error, SslErrorHandler handler
1783 ) {
1784 // Show a dialog with the certificate info
1785 SslUntrustedCertDialog dialog;
1786 if (x509Certificate == null) {
1787 dialog = SslUntrustedCertDialog.newInstanceForEmptySslError(error, handler);
1788 } else {
1789 dialog = SslUntrustedCertDialog.
1790 newInstanceForFullSslError(x509Certificate, error, handler);
1791 }
1792 FragmentManager fm = getSupportFragmentManager();
1793 FragmentTransaction ft = fm.beginTransaction();
1794 ft.addToBackStack(null);
1795 dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);
1796 }
1797
1798
1799 /**
1800 * Show untrusted cert dialog
1801 */
1802 private void showUntrustedCertDialog(RemoteOperationResult result) {
1803 // Show a dialog with the certificate info
1804 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.
1805 newInstanceForFullSslError((CertificateCombinedException)result.getException());
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 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1815 */
1816 public void onSavedCertificate() {
1817 Fragment fd = getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG);
1818 if (fd == null) {
1819 // if SAML dialog is not shown,
1820 // the SslDialog was shown due to an SSL error in the server check
1821 checkOcServer();
1822 }
1823 }
1824
1825 /**
1826 * Called from SslValidatorDialog when a new server certificate could not be saved
1827 * when the user requested it.
1828 */
1829 @Override
1830 public void onFailedSavingCertificate() {
1831 dismissDialog(SAML_DIALOG_TAG);
1832 Toast.makeText(this, R.string.ssl_validator_not_saved, Toast.LENGTH_LONG).show();
1833 }
1834
1835 @Override
1836 public void onCancelCertificate() {
1837 dismissDialog(SAML_DIALOG_TAG);
1838 }
1839
1840
1841 private void doOnResumeAndBound() {
1842 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1843 mOperationsServiceBinder.addOperationListener(AuthenticatorActivity.this, mHandler);
1844 if (mWaitingForOpId <= Integer.MAX_VALUE) {
1845 mOperationsServiceBinder.dispatchResultIfFinished((int)mWaitingForOpId, this);
1846 }
1847
1848 if (mPendingAutoCheck) {
1849 checkOcServer();
1850 }
1851 }
1852
1853
1854 private void dismissDialog(String dialogTag){
1855 Fragment frag = getSupportFragmentManager().findFragmentByTag(dialogTag);
1856 if (frag != null && frag instanceof DialogFragment) {
1857 DialogFragment dialog = (DialogFragment) frag;
1858 dialog.dismiss();
1859 }
1860 }
1861
1862
1863 /**
1864 * Implements callback methods for service binding.
1865 */
1866 private class OperationsServiceConnection implements ServiceConnection {
1867
1868 @Override
1869 public void onServiceConnected(ComponentName component, IBinder service) {
1870 if (component.equals(
1871 new ComponentName(AuthenticatorActivity.this, OperationsService.class)
1872 )) {
1873 mOperationsServiceBinder = (OperationsServiceBinder) service;
1874
1875 doOnResumeAndBound();
1876
1877 }
1878
1879 }
1880
1881 @Override
1882 public void onServiceDisconnected(ComponentName component) {
1883 if (component.equals(
1884 new ComponentName(AuthenticatorActivity.this, OperationsService.class)
1885 )) {
1886 Log_OC.e(TAG, "Operations service crashed");
1887 mOperationsServiceBinder = null;
1888 }
1889 }
1890
1891 }
1892
1893 /**
1894 * Create and show dialog for request authentication to the user
1895 * @param webView Web view to emebd into the authentication dialog.
1896 * @param handler Object responsible for catching and recovering HTTP authentication fails.
1897 */
1898 public void createAuthenticationDialog(WebView webView, HttpAuthHandler handler) {
1899
1900 // Show a dialog with the certificate info
1901 CredentialsDialogFragment dialog =
1902 CredentialsDialogFragment.newInstanceForCredentials(webView, handler);
1903 FragmentManager fm = getSupportFragmentManager();
1904 FragmentTransaction ft = fm.beginTransaction();
1905 ft.addToBackStack(null);
1906 dialog.setCancelable(false);
1907 dialog.show(ft, CREDENTIALS_DIALOG_TAG);
1908
1909 if (!mIsFirstAuthAttempt) {
1910 Toast.makeText(
1911 getApplicationContext(),
1912 getText(R.string.saml_authentication_wrong_pass),
1913 Toast.LENGTH_LONG
1914 ).show();
1915 } else {
1916 mIsFirstAuthAttempt = false;
1917 }
1918 }
1919
1920 /**
1921 * For retrieving the clicking on authentication cancel button
1922 */
1923 public void doNegativeAuthenticatioDialogClick(){
1924 mIsFirstAuthAttempt = true;
1925 }
1926
1927 }