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