Kill former session when authentication token is updated
[pub/Android/ownCloud.git] / src / com / owncloud / android / authentication / AuthenticatorActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package com.owncloud.android.authentication;
20
21 import java.io.IOException;
22 import java.security.cert.X509Certificate;
23 import java.util.Map;
24
25 import android.accounts.Account;
26 import android.accounts.AccountManager;
27 import android.accounts.AuthenticatorException;
28 import android.accounts.OperationCanceledException;
29 import android.app.Dialog;
30 import android.content.ComponentName;
31 import android.content.Context;
32 import android.content.Intent;
33 import android.content.ServiceConnection;
34 import android.content.SharedPreferences;
35 import android.graphics.Rect;
36 import android.graphics.drawable.Drawable;
37 import android.net.Uri;
38 import android.net.http.SslError;
39 import android.os.Bundle;
40 import android.os.Handler;
41 import android.os.IBinder;
42 import android.preference.PreferenceManager;
43 import android.support.v4.app.Fragment;
44 import android.support.v4.app.FragmentManager;
45 import android.support.v4.app.FragmentTransaction;
46 import android.text.Editable;
47 import android.text.InputType;
48 import android.text.TextWatcher;
49 import android.view.KeyEvent;
50 import android.view.MotionEvent;
51 import android.view.View;
52 import android.view.View.OnFocusChangeListener;
53 import android.view.View.OnTouchListener;
54 import android.view.Window;
55 import android.view.inputmethod.EditorInfo;
56 import android.webkit.HttpAuthHandler;
57 import android.webkit.SslErrorHandler;
58 import android.webkit.WebView;
59 import android.widget.Button;
60 import android.widget.CheckBox;
61 import android.widget.EditText;
62 import android.widget.TextView;
63 import android.widget.TextView.OnEditorActionListener;
64 import android.widget.Toast;
65
66 import com.actionbarsherlock.app.SherlockDialogFragment;
67 import com.owncloud.android.MainApp;
68 import com.owncloud.android.R;
69 import com.owncloud.android.authentication.SsoWebViewClient.SsoWebViewClientListener;
70 import com.owncloud.android.lib.common.OwnCloudAccount;
71 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
72 import com.owncloud.android.lib.common.accounts.AccountTypeUtils;
73 import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;
74 import com.owncloud.android.lib.common.network.CertificateCombinedException;
75 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;
76 import com.owncloud.android.lib.common.operations.RemoteOperation;
77 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
78 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
79 import com.owncloud.android.lib.common.utils.Log_OC;
80 import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
81 import com.owncloud.android.lib.resources.status.OwnCloudVersion;
82 import com.owncloud.android.lib.resources.users.GetRemoteUserNameOperation;
83 import com.owncloud.android.operations.DetectAuthenticationMethodOperation.AuthenticationMethod;
84 import com.owncloud.android.operations.GetServerInfoOperation;
85 import com.owncloud.android.operations.OAuth2GetAccessToken;
86 import com.owncloud.android.services.OperationsService;
87 import com.owncloud.android.services.OperationsService.OperationsServiceBinder;
88 import com.owncloud.android.ui.dialog.CredentialsDialogFragment;
89 import com.owncloud.android.ui.dialog.IndeterminateProgressDialog;
90 import com.owncloud.android.ui.dialog.SamlWebViewDialog;
91 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
92 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
93 import com.owncloud.android.utils.DisplayUtils;
94
95 /**
96 * This Activity is used to add an ownCloud account to the App
97 *
98 * @author Bartek Przybylski
99 * @author David A. Velasco
100 * @author masensio
101 */
102 public class AuthenticatorActivity extends AccountAuthenticatorActivity
103 implements OnRemoteOperationListener, OnFocusChangeListener, OnEditorActionListener,
104 SsoWebViewClientListener, OnSslUntrustedCertListener,
105 AuthenticatorAsyncTask.OnAuthenticatorTaskListener {
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 AuthenticatorAsyncTask asyncTask = new AuthenticatorAsyncTask(this);
896 String[] params = { mServerInfo.mBaseUrl, username, password, mAuthToken, mAuthTokenType};
897 asyncTask.execute(params);
898
899 }
900
901 /**
902 * Starts the OAuth 'grant type' flow to get an access token, with
903 * a GET AUTHORIZATION request to the BUILT-IN authorization server.
904 */
905 private void startOauthorization() {
906 // be gentle with the user
907 mAuthStatusIcon = R.drawable.progress_small;
908 mAuthStatusText = R.string.oauth_login_connection;
909 showAuthStatus();
910
911 // GET AUTHORIZATION request
912 Uri uri = Uri.parse(mOAuthAuthEndpointText.getText().toString().trim());
913 Uri.Builder uriBuilder = uri.buildUpon();
914 uriBuilder.appendQueryParameter(
915 OAuth2Constants.KEY_RESPONSE_TYPE, getString(R.string.oauth2_response_type)
916 );
917 uriBuilder.appendQueryParameter(
918 OAuth2Constants.KEY_REDIRECT_URI, getString(R.string.oauth2_redirect_uri)
919 );
920 uriBuilder.appendQueryParameter(
921 OAuth2Constants.KEY_CLIENT_ID, getString(R.string.oauth2_client_id)
922 );
923 uriBuilder.appendQueryParameter(
924 OAuth2Constants.KEY_SCOPE, getString(R.string.oauth2_scope)
925 );
926 uri = uriBuilder.build();
927 Log_OC.d(TAG, "Starting browser to view " + uri.toString());
928 Intent i = new Intent(Intent.ACTION_VIEW, uri);
929 startActivity(i);
930 }
931
932
933 /**
934 * Starts the Web Single Sign On flow to get access to the root folder
935 * in the server.
936 */
937 private void startSamlBasedFederatedSingleSignOnAuthorization() {
938 // be gentle with the user
939 mAuthStatusIcon = R.drawable.progress_small;
940 mAuthStatusText = R.string.auth_connecting_auth_server;
941 showAuthStatus();
942 IndeterminateProgressDialog dialog =
943 IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);
944 dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
945
946 /// validate credentials accessing the root folder
947 accessRootFolderRemoteOperation("", "");
948
949 }
950
951 /**
952 * Callback method invoked when a RemoteOperation executed by this Activity finishes.
953 *
954 * Dispatches the operation flow to the right method.
955 */
956 @Override
957 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
958
959 if (operation instanceof GetServerInfoOperation) {
960 if (operation.hashCode() == mWaitingForOpId) {
961 onGetServerInfoFinish(result);
962 } // else nothing ; only the last check operation is considered;
963 // multiple can be started if the user amends a URL quickly
964
965 } else if (operation instanceof OAuth2GetAccessToken) {
966 onGetOAuthAccessTokenFinish(result);
967
968 } else if (operation instanceof ExistenceCheckRemoteOperation) {
969 // TODO : remove this response??
970 //Log_OC.wtf(TAG, "received detection response through callback" );
971 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
972 equals(mAuthTokenType)) {
973 onSamlBasedFederatedSingleSignOnAuthorizationStart(result);
974
975 } else {
976 onAuthorizationCheckFinish(result);
977 }
978 } else if (operation instanceof GetRemoteUserNameOperation) {
979 onGetUserNameFinish(result);
980 }
981
982 }
983
984 private void onGetUserNameFinish(RemoteOperationResult result) {
985 mWaitingForOpId = Long.MAX_VALUE;
986 if (result.isSuccess()) {
987 boolean success = false;
988 String username = (String) result.getData().get(0);
989
990 if ( mAction == ACTION_CREATE) {
991 mUsernameInput.setText(username);
992 success = createAccount();
993 } else {
994
995 if (!mUsernameInput.getText().toString().equals(username)) {
996 // fail - not a new account, but an existing one; disallow
997 result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME);
998 mAuthToken = "";
999 updateAuthStatusIconAndText(result);
1000 showAuthStatus();
1001 Log_OC.d(TAG, result.getLogMessage());
1002 } else {
1003 updateAccountAuthentication();
1004 success = true;
1005 }
1006 }
1007
1008 if (success)
1009 finish();
1010 } else {
1011 updateStatusIconFailUserName();
1012 showAuthStatus();
1013 Log_OC.e(TAG, "Access to user name failed: " + result.getLogMessage());
1014 }
1015
1016 }
1017
1018 private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result) {
1019 mWaitingForOpId = Long.MAX_VALUE;
1020 dismissDialog(WAIT_DIALOG_TAG);
1021
1022 if (result.isIdPRedirection()) {
1023 String targetUrl = mServerInfo.mBaseUrl
1024 + AccountUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType);
1025
1026 // Show dialog
1027 SamlWebViewDialog dialog = SamlWebViewDialog.newInstance(targetUrl, targetUrl);
1028 dialog.show(getSupportFragmentManager(), SAML_DIALOG_TAG);
1029
1030 mAuthStatusIcon = 0;
1031 mAuthStatusText = 0;
1032
1033 } else {
1034 mAuthStatusIcon = R.drawable.common_error;
1035 mAuthStatusText = R.string.auth_unsupported_auth_method;
1036
1037 }
1038 showAuthStatus();
1039 }
1040
1041
1042 /**
1043 * Processes the result of the server check performed when the user finishes the enter of the
1044 * server URL.
1045 *
1046 * @param result Result of the check.
1047 */
1048 private void onGetServerInfoFinish(RemoteOperationResult result) {
1049 /// update activity state
1050 mServerIsChecked = true;
1051 mWaitingForOpId = Long.MAX_VALUE;
1052
1053 // update server status, but don't show it yet
1054 updateServerStatusIconAndText(result);
1055
1056 if (result.isSuccess()) {
1057 /// SUCCESS means:
1058 // 1. connection succeeded, and we know if it's SSL or not
1059 // 2. server is installed
1060 // 3. we got the server version
1061 // 4. we got the authentication method required by the server
1062 mServerInfo = (GetServerInfoOperation.ServerInfo) (result.getData().get(0));
1063
1064 if (!authSupported(mServerInfo.mAuthMethod)) {
1065
1066 updateServerStatusIconNoRegularAuth(); // overrides updateServerStatusIconAndText()
1067 mServerIsValid = false;
1068
1069 } else {
1070 mServerIsValid = true;
1071 }
1072
1073 } else {
1074 mServerIsValid = false;
1075 }
1076
1077 // refresh UI
1078 showRefreshButton(!mServerIsValid);
1079 showServerStatus();
1080 mOkButton.setEnabled(mServerIsValid);
1081
1082 /// very special case (TODO: move to a common place for all the remote operations)
1083 if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
1084 showUntrustedCertDialog(result);
1085 }
1086 }
1087
1088
1089 private boolean authSupported(AuthenticationMethod authMethod) {
1090 String basic = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());
1091 String oAuth = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());
1092 String saml = AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType());
1093
1094 return (( mAuthTokenType.equals(basic) &&
1095 authMethod.equals(AuthenticationMethod.BASIC_HTTP_AUTH) ) ||
1096 ( mAuthTokenType.equals(oAuth) &&
1097 authMethod.equals(AuthenticationMethod.BEARER_TOKEN)) ||
1098 ( mAuthTokenType.equals(saml) &&
1099 authMethod.equals(AuthenticationMethod.SAML_WEB_SSO))
1100 );
1101 }
1102
1103
1104 // TODO remove, if possible
1105 private String normalizeUrl(String url, boolean sslWhenUnprefixed) {
1106 if (url != null && url.length() > 0) {
1107 url = url.trim();
1108 if (!url.toLowerCase().startsWith("http://") &&
1109 !url.toLowerCase().startsWith("https://")) {
1110 if (sslWhenUnprefixed) {
1111 url = "https://" + url;
1112 } else {
1113 url = "http://" + url;
1114 }
1115 }
1116
1117 url = normalizeUrlSuffix(url);
1118 }
1119 return (url != null ? url : "");
1120 }
1121
1122
1123 private String normalizeUrlSuffix(String url) {
1124 if (url.endsWith("/")) {
1125 url = url.substring(0, url.length() - 1);
1126 }
1127 url = trimUrlWebdav(url);
1128 return url;
1129 }
1130
1131
1132 // TODO remove, if possible
1133 private String trimUrlWebdav(String url){
1134 if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0)){
1135 url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0.length());
1136 } else if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_2_0)){
1137 url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_2_0.length());
1138 } else if (url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_1_2)){
1139 url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_1_2.length());
1140 }
1141 return (url != null ? url : "");
1142 }
1143
1144
1145 /**
1146 * Chooses the right icon and text to show to the user for the received operation result.
1147 *
1148 * @param result Result of a remote operation performed in this activity
1149 */
1150 private void updateServerStatusIconAndText(RemoteOperationResult result) {
1151 mServerStatusIcon = R.drawable.common_error; // the most common case in the switch below
1152
1153 switch (result.getCode()) {
1154 case OK_SSL:
1155 mServerStatusIcon = android.R.drawable.ic_secure;
1156 mServerStatusText = R.string.auth_secure_connection;
1157 break;
1158
1159 case OK_NO_SSL:
1160 case OK:
1161 if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1162 mServerStatusText = R.string.auth_connection_established;
1163 mServerStatusIcon = R.drawable.ic_ok;
1164 } else {
1165 mServerStatusText = R.string.auth_nossl_plain_ok_title;
1166 mServerStatusIcon = android.R.drawable.ic_partial_secure;
1167 }
1168 break;
1169
1170 case NO_NETWORK_CONNECTION:
1171 mServerStatusIcon = R.drawable.no_network;
1172 mServerStatusText = R.string.auth_no_net_conn_title;
1173 break;
1174
1175 case SSL_RECOVERABLE_PEER_UNVERIFIED:
1176 mServerStatusText = R.string.auth_ssl_unverified_server_title;
1177 break;
1178 case BAD_OC_VERSION:
1179 mServerStatusText = R.string.auth_bad_oc_version_title;
1180 break;
1181 case WRONG_CONNECTION:
1182 mServerStatusText = R.string.auth_wrong_connection_title;
1183 break;
1184 case TIMEOUT:
1185 mServerStatusText = R.string.auth_timeout_title;
1186 break;
1187 case INCORRECT_ADDRESS:
1188 mServerStatusText = R.string.auth_incorrect_address_title;
1189 break;
1190 case SSL_ERROR:
1191 mServerStatusText = R.string.auth_ssl_general_error_title;
1192 break;
1193 case UNAUTHORIZED:
1194 mServerStatusText = R.string.auth_unauthorized;
1195 break;
1196 case HOST_NOT_AVAILABLE:
1197 mServerStatusText = R.string.auth_unknown_host_title;
1198 break;
1199 case INSTANCE_NOT_CONFIGURED:
1200 mServerStatusText = R.string.auth_not_configured_title;
1201 break;
1202 case FILE_NOT_FOUND:
1203 mServerStatusText = R.string.auth_incorrect_path_title;
1204 break;
1205 case OAUTH2_ERROR:
1206 mServerStatusText = R.string.auth_oauth_error;
1207 break;
1208 case OAUTH2_ERROR_ACCESS_DENIED:
1209 mServerStatusText = R.string.auth_oauth_error_access_denied;
1210 break;
1211 case UNHANDLED_HTTP_CODE:
1212 case UNKNOWN_ERROR:
1213 mServerStatusText = R.string.auth_unknown_error_title;
1214 break;
1215 case OK_REDIRECT_TO_NON_SECURE_CONNECTION:
1216 mServerStatusIcon = android.R.drawable.ic_partial_secure;
1217 mServerStatusText = R.string.auth_redirect_non_secure_connection_title;
1218 break;
1219 default:
1220 mServerStatusText = 0;
1221 mServerStatusIcon = 0;
1222 }
1223 }
1224
1225
1226 /**
1227 * Chooses the right icon and text to show to the user for the received operation result.
1228 *
1229 * @param result Result of a remote operation performed in this activity
1230 */
1231 private void updateAuthStatusIconAndText(RemoteOperationResult result) {
1232 mAuthStatusIcon = R.drawable.common_error; // the most common case in the switch below
1233
1234 switch (result.getCode()) {
1235 case OK_SSL:
1236 mAuthStatusIcon = android.R.drawable.ic_secure;
1237 mAuthStatusText = R.string.auth_secure_connection;
1238 break;
1239
1240 case OK_NO_SSL:
1241 case OK:
1242 if (mHostUrlInput.getText().toString().trim().toLowerCase().startsWith("http://") ) {
1243 mAuthStatusText = R.string.auth_connection_established;
1244 mAuthStatusIcon = R.drawable.ic_ok;
1245 } else {
1246 mAuthStatusText = R.string.auth_nossl_plain_ok_title;
1247 mAuthStatusIcon = android.R.drawable.ic_partial_secure;
1248 }
1249 break;
1250
1251 case NO_NETWORK_CONNECTION:
1252 mAuthStatusIcon = R.drawable.no_network;
1253 mAuthStatusText = R.string.auth_no_net_conn_title;
1254 break;
1255
1256 case SSL_RECOVERABLE_PEER_UNVERIFIED:
1257 mAuthStatusText = R.string.auth_ssl_unverified_server_title;
1258 break;
1259 case BAD_OC_VERSION:
1260 mAuthStatusText = R.string.auth_bad_oc_version_title;
1261 break;
1262 case WRONG_CONNECTION:
1263 mAuthStatusText = R.string.auth_wrong_connection_title;
1264 break;
1265 case TIMEOUT:
1266 mAuthStatusText = R.string.auth_timeout_title;
1267 break;
1268 case INCORRECT_ADDRESS:
1269 mAuthStatusText = R.string.auth_incorrect_address_title;
1270 break;
1271 case SSL_ERROR:
1272 mAuthStatusText = R.string.auth_ssl_general_error_title;
1273 break;
1274 case UNAUTHORIZED:
1275 mAuthStatusText = R.string.auth_unauthorized;
1276 break;
1277 case HOST_NOT_AVAILABLE:
1278 mAuthStatusText = R.string.auth_unknown_host_title;
1279 break;
1280 case INSTANCE_NOT_CONFIGURED:
1281 mAuthStatusText = R.string.auth_not_configured_title;
1282 break;
1283 case FILE_NOT_FOUND:
1284 mAuthStatusText = R.string.auth_incorrect_path_title;
1285 break;
1286 case OAUTH2_ERROR:
1287 mAuthStatusText = R.string.auth_oauth_error;
1288 break;
1289 case OAUTH2_ERROR_ACCESS_DENIED:
1290 mAuthStatusText = R.string.auth_oauth_error_access_denied;
1291 break;
1292 case ACCOUNT_NOT_NEW:
1293 mAuthStatusText = R.string.auth_account_not_new;
1294 break;
1295 case ACCOUNT_NOT_THE_SAME:
1296 mAuthStatusText = R.string.auth_account_not_the_same;
1297 break;
1298 case UNHANDLED_HTTP_CODE:
1299 case UNKNOWN_ERROR:
1300 mAuthStatusText = R.string.auth_unknown_error_title;
1301 break;
1302 default:
1303 mAuthStatusText = 0;
1304 mAuthStatusIcon = 0;
1305 }
1306 }
1307
1308
1309 private void updateStatusIconFailUserName(){
1310 mAuthStatusIcon = R.drawable.common_error;
1311 mAuthStatusText = R.string.auth_fail_get_user_name;
1312 }
1313
1314 private void updateServerStatusIconNoRegularAuth(){
1315 mServerStatusIcon = R.drawable.common_error;
1316 mServerStatusText = R.string.auth_can_not_auth_against_server;
1317 }
1318
1319 /**
1320 * Processes the result of the request for and access token send
1321 * to an OAuth authorization server.
1322 *
1323 * @param result Result of the operation.
1324 */
1325 private void onGetOAuthAccessTokenFinish(RemoteOperationResult result) {
1326 mWaitingForOpId = Long.MAX_VALUE;
1327 dismissDialog(WAIT_DIALOG_TAG);
1328
1329 if (result.isSuccess()) {
1330 /// be gentle with the user
1331 IndeterminateProgressDialog dialog =
1332 IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);
1333 dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);
1334
1335 /// time to test the retrieved access token on the ownCloud server
1336 @SuppressWarnings("unchecked")
1337 Map<String, String> tokens = (Map<String, String>)(result.getData().get(0));
1338 mAuthToken = tokens.get(OAuth2Constants.KEY_ACCESS_TOKEN);
1339 Log_OC.d(TAG, "Got ACCESS TOKEN: " + mAuthToken);
1340
1341 accessRootFolderRemoteOperation("", "");
1342
1343 } else {
1344 updateAuthStatusIconAndText(result);
1345 showAuthStatus();
1346 Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
1347 }
1348 }
1349
1350
1351 /**
1352 * Processes the result of the access check performed to try the user credentials.
1353 *
1354 * Creates a new account through the AccountManager.
1355 *
1356 * @param result Result of the operation.
1357 */
1358 private void onAuthorizationCheckFinish(RemoteOperationResult result) {
1359 mWaitingForOpId = Long.MAX_VALUE;
1360 dismissDialog(WAIT_DIALOG_TAG);
1361
1362 if (result.isSuccess()) {
1363 Log_OC.d(TAG, "Successful access - time to save the account");
1364
1365 boolean success = false;
1366 if (mAction == ACTION_CREATE) {
1367 success = createAccount();
1368
1369 } else {
1370 updateAccountAuthentication();
1371 success = true;
1372 }
1373
1374 if (success) {
1375 finish();
1376 }
1377
1378 } else if (result.isServerFail() || result.isException()) {
1379 /// server errors or exceptions in authorization take to requiring a new check of
1380 /// the server
1381 mServerIsChecked = true;
1382 mServerIsValid = false;
1383 mServerInfo = new GetServerInfoOperation.ServerInfo();
1384
1385 // update status icon and text
1386 updateServerStatusIconAndText(result);
1387 showServerStatus();
1388 mAuthStatusIcon = 0;
1389 mAuthStatusText = 0;
1390 showAuthStatus();
1391
1392 // update input controls state
1393 showRefreshButton(true);
1394 mOkButton.setEnabled(false);
1395
1396 // very special case (TODO: move to a common place for all the remote operations)
1397 if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
1398 showUntrustedCertDialog(result);
1399 }
1400
1401 } else { // authorization fail due to client side - probably wrong credentials
1402 updateAuthStatusIconAndText(result);
1403 showAuthStatus();
1404 Log_OC.d(TAG, "Access failed: " + result.getLogMessage());
1405 }
1406 }
1407
1408
1409
1410
1411 /**
1412 * Updates the authentication token.
1413 *
1414 * Sets the proper response so that the AccountAuthenticator that started this activity
1415 * saves a new authorization token for mAccount.
1416 *
1417 * Kills the session kept by OwnCloudClientManager so that a new one will created with
1418 * the new credentials when needed.
1419 */
1420 private void updateAccountAuthentication() {
1421
1422 try {
1423 OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(
1424 new OwnCloudAccount(mAccount, this) // TODO avoid this creation may block the main thread
1425 );
1426 } catch (Exception e) {
1427 e.printStackTrace();
1428 }
1429
1430
1431 Bundle response = new Bundle();
1432 response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
1433 response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);
1434
1435 if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).
1436 equals(mAuthTokenType)) {
1437 response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
1438 // the next line is necessary, notifications are calling directly to the
1439 // AuthenticatorActivity to update, without AccountManager intervention
1440 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1441
1442 } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
1443 equals(mAuthTokenType)) {
1444
1445 response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
1446 // the next line is necessary; by now, notifications are calling directly to the
1447 // AuthenticatorActivity to update, without AccountManager intervention
1448 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1449
1450 } else {
1451 response.putString(AccountManager.KEY_AUTHTOKEN, mPasswordInput.getText().toString());
1452 mAccountMgr.setPassword(mAccount, mPasswordInput.getText().toString());
1453 }
1454 setAccountAuthenticatorResult(response);
1455
1456 }
1457
1458
1459 /**
1460 * Creates a new account through the Account Authenticator that started this activity.
1461 *
1462 * This makes the account permanent.
1463 *
1464 * TODO Decide how to name the OAuth accounts
1465 */
1466 private boolean createAccount() {
1467 /// create and save new ownCloud account
1468 boolean isOAuth = AccountTypeUtils.
1469 getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType);
1470 boolean isSaml = AccountTypeUtils.
1471 getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType);
1472
1473 Uri uri = Uri.parse(mServerInfo.mBaseUrl);
1474 String username = mUsernameInput.getText().toString().trim();
1475 if (isOAuth) {
1476 username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();
1477 }
1478 String accountName = com.owncloud.android.lib.common.accounts.AccountUtils.
1479 buildAccountName(uri, username);
1480 Account newAccount = new Account(accountName, MainApp.getAccountType());
1481 if (AccountUtils.exists(newAccount, getApplicationContext())) {
1482 // fail - not a new account, but an existing one; disallow
1483 RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW);
1484 updateAuthStatusIconAndText(result);
1485 showAuthStatus();
1486 Log_OC.d(TAG, result.getLogMessage());
1487 return false;
1488
1489 } else {
1490 mAccount = newAccount;
1491
1492 if (isOAuth || isSaml) {
1493 // with external authorizations, the password is never input in the app
1494 mAccountMgr.addAccountExplicitly(mAccount, "", null);
1495 } else {
1496 mAccountMgr.addAccountExplicitly(
1497 mAccount, mPasswordInput.getText().toString(), null
1498 );
1499 }
1500
1501 /// add the new account as default in preferences, if there is none already
1502 Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
1503 if (defaultAccount == null) {
1504 SharedPreferences.Editor editor = PreferenceManager
1505 .getDefaultSharedPreferences(this).edit();
1506 editor.putString("select_oc_account", accountName);
1507 editor.commit();
1508 }
1509
1510 /// prepare result to return to the Authenticator
1511 // TODO check again what the Authenticator makes with it; probably has the same
1512 // effect as addAccountExplicitly, but it's not well done
1513 final Intent intent = new Intent();
1514 intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, MainApp.getAccountType());
1515 intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
1516 /*if (!isOAuth)
1517 intent.putExtra(AccountManager.KEY_AUTHTOKEN, MainApp.getAccountType()); */
1518 intent.putExtra(AccountManager.KEY_USERDATA, username);
1519 if (isOAuth || isSaml) {
1520 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
1521 }
1522 /// add user data to the new account; TODO probably can be done in the last parameter
1523 // addAccountExplicitly, or in KEY_USERDATA
1524 mAccountMgr.setUserData(
1525 mAccount, Constants.KEY_OC_VERSION, mServerInfo.mVersion.getVersion()
1526 );
1527 mAccountMgr.setUserData(
1528 mAccount, Constants.KEY_OC_BASE_URL, mServerInfo.mBaseUrl
1529 );
1530
1531 if (isSaml) {
1532 mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE");
1533 } else if (isOAuth) {
1534 mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_OAUTH2, "TRUE");
1535 }
1536
1537 setAccountAuthenticatorResult(intent.getExtras());
1538 setResult(RESULT_OK, intent);
1539
1540 return true;
1541 }
1542 }
1543
1544
1545 /**
1546 * Starts and activity to open the 'new account' page in the ownCloud web site
1547 *
1548 * @param view 'Account register' button
1549 */
1550 public void onRegisterClick(View view) {
1551 Intent register = new Intent(
1552 Intent.ACTION_VIEW, Uri.parse(getString(R.string.welcome_link_url))
1553 );
1554 setResult(RESULT_CANCELED);
1555 startActivity(register);
1556 }
1557
1558
1559 /**
1560 * Updates the content and visibility state of the icon and text associated
1561 * to the last check on the ownCloud server.
1562 */
1563 private void showServerStatus() {
1564 if (mServerStatusIcon == 0 && mServerStatusText == 0) {
1565 mServerStatusView.setVisibility(View.INVISIBLE);
1566
1567 } else {
1568 mServerStatusView.setText(mServerStatusText);
1569 mServerStatusView.setCompoundDrawablesWithIntrinsicBounds(mServerStatusIcon, 0, 0, 0);
1570 mServerStatusView.setVisibility(View.VISIBLE);
1571 }
1572
1573 }
1574
1575
1576 /**
1577 * Updates the content and visibility state of the icon and text associated
1578 * to the interactions with the OAuth authorization server.
1579 */
1580 private void showAuthStatus() {
1581 if (mAuthStatusIcon == 0 && mAuthStatusText == 0) {
1582 mAuthStatusView.setVisibility(View.INVISIBLE);
1583
1584 } else {
1585 mAuthStatusView.setText(mAuthStatusText);
1586 mAuthStatusView.setCompoundDrawablesWithIntrinsicBounds(mAuthStatusIcon, 0, 0, 0);
1587 mAuthStatusView.setVisibility(View.VISIBLE);
1588 }
1589 }
1590
1591
1592 private void showRefreshButton (boolean show) {
1593 if (show) {
1594 mRefreshButton.setVisibility(View.VISIBLE);
1595 } else {
1596 mRefreshButton.setVisibility(View.GONE);
1597 }
1598 }
1599
1600 /**
1601 * Called when the refresh button in the input field for ownCloud host is clicked.
1602 *
1603 * Performs a new check on the URL in the input field.
1604 *
1605 * @param view Refresh 'button'
1606 */
1607 public void onRefreshClick(View view) {
1608 checkOcServer();
1609 }
1610
1611
1612 /**
1613 * Called when the eye icon in the password field is clicked.
1614 *
1615 * Toggles the visibility of the password in the field.
1616 */
1617 public void onViewPasswordClick() {
1618 int selectionStart = mPasswordInput.getSelectionStart();
1619 int selectionEnd = mPasswordInput.getSelectionEnd();
1620 if (isPasswordVisible()) {
1621 hidePassword();
1622 } else {
1623 showPassword();
1624 }
1625 mPasswordInput.setSelection(selectionStart, selectionEnd);
1626 }
1627
1628
1629 /**
1630 * Called when the checkbox for OAuth authorization is clicked.
1631 *
1632 * Hides or shows the input fields for user & password.
1633 *
1634 * @param view 'View password' 'button'
1635 */
1636 public void onCheckClick(View view) {
1637 CheckBox oAuth2Check = (CheckBox)view;
1638 if (oAuth2Check.isChecked()) {
1639 mAuthTokenType = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());
1640 } else {
1641 mAuthTokenType = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());
1642 }
1643 updateAuthenticationPreFragmentVisibility();
1644 }
1645
1646
1647 /**
1648 * Called when the 'action' button in an IME is pressed ('enter' in software keyboard).
1649 *
1650 * Used to trigger the authentication check when the user presses 'enter' after writing the
1651 * password, or to throw the server test when the only field on screen is the URL input field.
1652 */
1653 @Override
1654 public boolean onEditorAction(TextView inputField, int actionId, KeyEvent event) {
1655 if (actionId == EditorInfo.IME_ACTION_DONE && inputField != null &&
1656 inputField.equals(mPasswordInput)) {
1657 if (mOkButton.isEnabled()) {
1658 mOkButton.performClick();
1659 }
1660
1661 } else if (actionId == EditorInfo.IME_ACTION_NEXT && inputField != null &&
1662 inputField.equals(mHostUrlInput)) {
1663 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
1664 equals(mAuthTokenType)) {
1665 checkOcServer();
1666 }
1667 }
1668 return false; // always return false to grant that the software keyboard is hidden anyway
1669 }
1670
1671
1672 private abstract static class RightDrawableOnTouchListener implements OnTouchListener {
1673
1674 private int fuzz = 75;
1675
1676 /**
1677 * {@inheritDoc}
1678 */
1679 @Override
1680 public boolean onTouch(View view, MotionEvent event) {
1681 Drawable rightDrawable = null;
1682 if (view instanceof TextView) {
1683 Drawable[] drawables = ((TextView)view).getCompoundDrawables();
1684 if (drawables.length > 2) {
1685 rightDrawable = drawables[2];
1686 }
1687 }
1688 if (rightDrawable != null) {
1689 final int x = (int) event.getX();
1690 final int y = (int) event.getY();
1691 final Rect bounds = rightDrawable.getBounds();
1692 if ( x >= (view.getRight() - bounds.width() - fuzz) &&
1693 x <= (view.getRight() - view.getPaddingRight() + fuzz) &&
1694 y >= (view.getPaddingTop() - fuzz) &&
1695 y <= (view.getHeight() - view.getPaddingBottom()) + fuzz) {
1696
1697 return onDrawableTouch(event);
1698 }
1699 }
1700 return false;
1701 }
1702
1703 public abstract boolean onDrawableTouch(final MotionEvent event);
1704 }
1705
1706
1707 private void getRemoteUserNameOperation(String sessionCookie, boolean followRedirects) {
1708
1709 Intent getUserNameIntent = new Intent();
1710 getUserNameIntent.setAction(OperationsService.ACTION_GET_USER_NAME);
1711 getUserNameIntent.putExtra(OperationsService.EXTRA_SERVER_URL, mServerInfo.mBaseUrl);
1712 getUserNameIntent.putExtra(OperationsService.EXTRA_COOKIE, sessionCookie);
1713
1714 if (mOperationsServiceBinder != null) {
1715 //Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." );
1716 mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getUserNameIntent);
1717 }
1718 }
1719
1720
1721 @Override
1722 public void onSsoFinished(String sessionCookie) {
1723 if (sessionCookie != null && sessionCookie.length() > 0) {
1724 Log_OC.d(TAG, "Successful SSO - time to save the account");
1725 mAuthToken = sessionCookie;
1726 getRemoteUserNameOperation(sessionCookie, true);
1727 Fragment fd = getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG);
1728 if (fd != null && fd instanceof SherlockDialogFragment) {
1729 Dialog d = ((SherlockDialogFragment)fd).getDialog();
1730 if (d != null && d.isShowing()) {
1731 d.dismiss();
1732 }
1733 }
1734
1735 } else {
1736 // TODO - show fail
1737 Log_OC.d(TAG, "SSO failed");
1738 }
1739
1740 }
1741
1742 @Override
1743 public boolean onTouchEvent(MotionEvent event) {
1744 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
1745 equals(mAuthTokenType) &&
1746 mHostUrlInput.hasFocus() && event.getAction() == MotionEvent.ACTION_DOWN) {
1747 checkOcServer();
1748 }
1749 return super.onTouchEvent(event);
1750 }
1751
1752
1753 /**
1754 * Show untrusted cert dialog
1755 */
1756 public void showUntrustedCertDialog(
1757 X509Certificate x509Certificate, SslError error, SslErrorHandler handler
1758 ) {
1759 // Show a dialog with the certificate info
1760 SslUntrustedCertDialog dialog = null;
1761 if (x509Certificate == null) {
1762 dialog = SslUntrustedCertDialog.newInstanceForEmptySslError(error, handler);
1763 } else {
1764 dialog = SslUntrustedCertDialog.
1765 newInstanceForFullSslError(x509Certificate, error, handler);
1766 }
1767 FragmentManager fm = getSupportFragmentManager();
1768 FragmentTransaction ft = fm.beginTransaction();
1769 ft.addToBackStack(null);
1770 dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);
1771 }
1772
1773
1774 /**
1775 * Show untrusted cert dialog
1776 */
1777 private void showUntrustedCertDialog(RemoteOperationResult result) {
1778 // Show a dialog with the certificate info
1779 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.
1780 newInstanceForFullSslError((CertificateCombinedException)result.getException());
1781 FragmentManager fm = getSupportFragmentManager();
1782 FragmentTransaction ft = fm.beginTransaction();
1783 ft.addToBackStack(null);
1784 dialog.show(ft, UNTRUSTED_CERT_DIALOG_TAG);
1785
1786 }
1787
1788 /**
1789 * Called from SslValidatorDialog when a new server certificate was correctly saved.
1790 */
1791 public void onSavedCertificate() {
1792 Fragment fd = getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG);
1793 if (fd == null) {
1794 // if SAML dialog is not shown,
1795 // the SslDialog was shown due to an SSL error in the server check
1796 checkOcServer();
1797 }
1798 }
1799
1800 /**
1801 * Called from SslValidatorDialog when a new server certificate could not be saved
1802 * when the user requested it.
1803 */
1804 @Override
1805 public void onFailedSavingCertificate() {
1806 dismissDialog(SAML_DIALOG_TAG);
1807 Toast.makeText(this, R.string.ssl_validator_not_saved, Toast.LENGTH_LONG).show();
1808 }
1809
1810 @Override
1811 public void onCancelCertificate() {
1812 dismissDialog(SAML_DIALOG_TAG);
1813 }
1814
1815
1816 private void doOnResumeAndBound() {
1817 //Log_OC.wtf(TAG, "registering to listen for operation callbacks" );
1818 mOperationsServiceBinder.addOperationListener(AuthenticatorActivity.this, mHandler);
1819 if (mWaitingForOpId <= Integer.MAX_VALUE) {
1820 mOperationsServiceBinder.dispatchResultIfFinished((int)mWaitingForOpId, this);
1821 }
1822
1823 if (mPendingAutoCheck) {
1824 checkOcServer();
1825 }
1826 }
1827
1828
1829 private void dismissDialog(String dialogTag){
1830 Fragment frag = getSupportFragmentManager().findFragmentByTag(dialogTag);
1831 if (frag != null && frag instanceof SherlockDialogFragment) {
1832 SherlockDialogFragment dialog = (SherlockDialogFragment) frag;
1833 dialog.dismiss();
1834 }
1835 }
1836
1837
1838 /**
1839 * Implements callback methods for service binding.
1840 */
1841 private class OperationsServiceConnection implements ServiceConnection {
1842
1843 @Override
1844 public void onServiceConnected(ComponentName component, IBinder service) {
1845 if (component.equals(
1846 new ComponentName(AuthenticatorActivity.this, OperationsService.class)
1847 )) {
1848 //Log_OC.wtf(TAG, "Operations service connected");
1849 mOperationsServiceBinder = (OperationsServiceBinder) service;
1850
1851 doOnResumeAndBound();
1852
1853 } else {
1854 return;
1855 }
1856
1857 }
1858
1859 @Override
1860 public void onServiceDisconnected(ComponentName component) {
1861 if (component.equals(
1862 new ComponentName(AuthenticatorActivity.this, OperationsService.class)
1863 )) {
1864 Log_OC.e(TAG, "Operations service crashed");
1865 mOperationsServiceBinder = null;
1866 }
1867 }
1868
1869 }
1870
1871 /**
1872 * Create and show dialog for request authentication to the user
1873 * @param webView
1874 * @param handler
1875 */
1876 public void createAuthenticationDialog(WebView webView, HttpAuthHandler handler) {
1877
1878 // Show a dialog with the certificate info
1879 CredentialsDialogFragment dialog =
1880 CredentialsDialogFragment.newInstanceForCredentials(webView, handler);
1881 FragmentManager fm = getSupportFragmentManager();
1882 FragmentTransaction ft = fm.beginTransaction();
1883 ft.addToBackStack(null);
1884 dialog.setCancelable(false);
1885 dialog.show(ft, CREDENTIALS_DIALOG_TAG);
1886
1887 if (!mIsFirstAuthAttempt) {
1888 Toast.makeText(
1889 getApplicationContext(),
1890 getText(R.string.saml_authentication_wrong_pass),
1891 Toast.LENGTH_LONG
1892 ).show();
1893 } else {
1894 mIsFirstAuthAttempt = false;
1895 }
1896 }
1897
1898 /**
1899 * For retrieving the clicking on authentication cancel button
1900 */
1901 public void doNegativeAuthenticatioDialogClick(){
1902 mIsFirstAuthAttempt = true;
1903 }
1904
1905
1906 @Override
1907 public void onAuthenticatorTaskCallback(RemoteOperationResult result) {
1908 //Log_OC.wtf(TAG, "received detection response through callback" );
1909 if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).
1910 equals(mAuthTokenType)) {
1911 onSamlBasedFederatedSingleSignOnAuthorizationStart(result);
1912
1913 } else {
1914 onAuthorizationCheckFinish(result);
1915 }
1916 }
1917 }