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