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