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