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