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