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