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