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