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