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